3 namespace BookStack\Entities\Repos;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Tools\BookContents;
9 use BookStack\Entities\Tools\TrashCan;
10 use BookStack\Exceptions\MoveOperationException;
11 use BookStack\Exceptions\NotFoundException;
12 use BookStack\Facades\Activity;
20 * ChapterRepo constructor.
22 public function __construct(BaseRepo $baseRepo)
24 $this->baseRepo = $baseRepo;
28 * Get a chapter via the slug.
30 * @throws NotFoundException
32 public function getBySlug(string $bookSlug, string $chapterSlug): Chapter
34 $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->first();
36 if ($chapter === null) {
37 throw new NotFoundException(trans('errors.chapter_not_found'));
44 * Create a new chapter in the system.
46 public function create(array $input, Book $parentBook): Chapter
48 $chapter = new Chapter();
49 $chapter->book_id = $parentBook->id;
50 $chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1;
51 $this->baseRepo->create($chapter, $input);
52 Activity::addForEntity($chapter, ActivityType::CHAPTER_CREATE);
58 * Update the given chapter.
60 public function update(Chapter $chapter, array $input): Chapter
62 $this->baseRepo->update($chapter, $input);
63 Activity::addForEntity($chapter, ActivityType::CHAPTER_UPDATE);
69 * Remove a chapter from the system.
73 public function destroy(Chapter $chapter)
75 $trashCan = new TrashCan();
76 $trashCan->softDestroyChapter($chapter);
77 Activity::addForEntity($chapter, ActivityType::CHAPTER_DELETE);
78 $trashCan->autoClearOld();
82 * Move the given chapter into a new parent book.
83 * The $parentIdentifier must be a string of the following format:
84 * 'book:<id>' (book:5).
86 * @throws MoveOperationException
88 public function move(Chapter $chapter, string $parentIdentifier): Book
90 $stringExploded = explode(':', $parentIdentifier);
91 $entityType = $stringExploded[0];
92 $entityId = intval($stringExploded[1]);
94 if ($entityType !== 'book') {
95 throw new MoveOperationException('Chapters can only be moved into books');
98 /** @var Book $parent */
99 $parent = Book::visible()->where('id', '=', $entityId)->first();
100 if ($parent === null) {
101 throw new MoveOperationException('Book to move chapter into not found');
104 $chapter->changeBook($parent->id);
105 $chapter->rebuildPermissions();
106 Activity::addForEntity($chapter, ActivityType::CHAPTER_MOVE);