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\Models\Entity;
9 use BookStack\Entities\Tools\BookContents;
10 use BookStack\Entities\Tools\TrashCan;
11 use BookStack\Exceptions\MoveOperationException;
12 use BookStack\Exceptions\NotFoundException;
13 use BookStack\Facades\Activity;
21 * ChapterRepo constructor.
23 public function __construct(BaseRepo $baseRepo)
25 $this->baseRepo = $baseRepo;
29 * Get a chapter via the slug.
31 * @throws NotFoundException
33 public function getBySlug(string $bookSlug, string $chapterSlug): Chapter
35 $chapter = Chapter::visible()->whereSlugs($bookSlug, $chapterSlug)->first();
37 if ($chapter === null) {
38 throw new NotFoundException(trans('errors.chapter_not_found'));
45 * Create a new chapter in the system.
47 public function create(array $input, Book $parentBook): Chapter
49 $chapter = new Chapter();
50 $chapter->book_id = $parentBook->id;
51 $chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1;
52 $this->baseRepo->create($chapter, $input);
53 Activity::add(ActivityType::CHAPTER_CREATE, $chapter);
59 * Update the given chapter.
61 public function update(Chapter $chapter, array $input): Chapter
63 $this->baseRepo->update($chapter, $input);
64 Activity::add(ActivityType::CHAPTER_UPDATE, $chapter);
70 * Remove a chapter from the system.
74 public function destroy(Chapter $chapter)
76 $trashCan = new TrashCan();
77 $trashCan->softDestroyChapter($chapter);
78 Activity::add(ActivityType::CHAPTER_DELETE, $chapter);
79 $trashCan->autoClearOld();
83 * Move the given chapter into a new parent book.
84 * The $parentIdentifier must be a string of the following format:
85 * 'book:<id>' (book:5).
87 * @throws MoveOperationException
89 public function move(Chapter $chapter, string $parentIdentifier): Book
91 /** @var Book $parent */
92 $parent = $this->findParentByIdentifier($parentIdentifier);
93 if (is_null($parent)) {
94 throw new MoveOperationException('Book to move chapter into not found');
97 $chapter->changeBook($parent->id);
98 $chapter->rebuildPermissions();
99 Activity::add(ActivityType::CHAPTER_MOVE, $chapter);
105 * Find a page parent entity via an identifier string in the format:
109 * @throws MoveOperationException
111 public function findParentByIdentifier(string $identifier): ?Book
113 $stringExploded = explode(':', $identifier);
114 $entityType = $stringExploded[0];
115 $entityId = intval($stringExploded[1]);
117 if ($entityType !== 'book') {
118 throw new MoveOperationException('Chapters can only be in books');
121 return Book::visible()->where('id', '=', $entityId)->first();