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 * Update the permissions of a chapter.
68 public function updatePermissions(Chapter $chapter, bool $restricted, Collection $permissions = null)
70 $this->baseRepo->updatePermissions($chapter, $restricted, $permissions);
74 * Remove a chapter from the system.
77 public function destroy(Chapter $chapter)
79 $trashCan = new TrashCan();
80 $trashCan->softDestroyChapter($chapter);
81 Activity::addForEntity($chapter, ActivityType::CHAPTER_DELETE);
82 $trashCan->autoClearOld();
86 * Move the given chapter into a new parent book.
87 * The $parentIdentifier must be a string of the following format:
88 * 'book:<id>' (book:5)
89 * @throws MoveOperationException
91 public function move(Chapter $chapter, string $parentIdentifier): Book
93 $stringExploded = explode(':', $parentIdentifier);
94 $entityType = $stringExploded[0];
95 $entityId = intval($stringExploded[1]);
97 if ($entityType !== 'book') {
98 throw new MoveOperationException('Chapters can only be moved into books');
101 /** @var Book $parent */
102 $parent = Book::visible()->where('id', '=', $entityId)->first();
103 if ($parent === null) {
104 throw new MoveOperationException('Book to move chapter into not found');
107 $chapter->changeBook($parent->id);
108 $chapter->rebuildPermissions();
109 Activity::addForEntity($chapter, ActivityType::CHAPTER_MOVE);