1 <?php namespace BookStack\Entities\Repos;
3 use BookStack\Actions\ActivityType;
4 use BookStack\Entities\Models\Book;
5 use BookStack\Entities\Models\Chapter;
6 use BookStack\Entities\Tools\BookContents;
7 use BookStack\Entities\Tools\TrashCan;
8 use BookStack\Exceptions\MoveOperationException;
9 use BookStack\Exceptions\NotFoundException;
10 use BookStack\Facades\Activity;
12 use Illuminate\Support\Collection;
20 * ChapterRepo constructor.
22 public function __construct(BaseRepo $baseRepo)
24 $this->baseRepo = $baseRepo;
28 * Get a chapter via the slug.
29 * @throws NotFoundException
31 public function getBySlug(string $bookSlug, string $chapterSlug): Chapter
33 $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->first();
35 if ($chapter === null) {
36 throw new NotFoundException(trans('errors.chapter_not_found'));
43 * Create a new chapter in the system.
45 public function create(array $input, Book $parentBook): Chapter
47 $chapter = new Chapter();
48 $chapter->book_id = $parentBook->id;
49 $chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1;
50 $this->baseRepo->create($chapter, $input);
51 Activity::addForEntity($chapter, ActivityType::CHAPTER_CREATE);
56 * Update the given chapter.
58 public function update(Chapter $chapter, array $input): Chapter
60 $this->baseRepo->update($chapter, $input);
61 Activity::addForEntity($chapter, ActivityType::CHAPTER_UPDATE);
66 * Remove a chapter from the system.
69 public function destroy(Chapter $chapter)
71 $trashCan = new TrashCan();
72 $trashCan->softDestroyChapter($chapter);
73 Activity::addForEntity($chapter, ActivityType::CHAPTER_DELETE);
74 $trashCan->autoClearOld();
78 * Move the given chapter into a new parent book.
79 * The $parentIdentifier must be a string of the following format:
80 * 'book:<id>' (book:5)
81 * @throws MoveOperationException
83 public function move(Chapter $chapter, string $parentIdentifier): Book
85 $stringExploded = explode(':', $parentIdentifier);
86 $entityType = $stringExploded[0];
87 $entityId = intval($stringExploded[1]);
89 if ($entityType !== 'book') {
90 throw new MoveOperationException('Chapters can only be moved into books');
93 /** @var Book $parent */
94 $parent = Book::visible()->where('id', '=', $entityId)->first();
95 if ($parent === null) {
96 throw new MoveOperationException('Book to move chapter into not found');
99 $chapter->changeBook($parent->id);
100 $chapter->rebuildPermissions();
101 Activity::addForEntity($chapter, ActivityType::CHAPTER_MOVE);