3 namespace BookStack\Entities\Repos;
5 use BookStack\Activity\ActivityType;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Queries\EntityQueries;
9 use BookStack\Entities\Tools\BookContents;
10 use BookStack\Entities\Tools\TrashCan;
11 use BookStack\Exceptions\MoveOperationException;
12 use BookStack\Exceptions\PermissionsException;
13 use BookStack\Facades\Activity;
14 use BookStack\Util\DatabaseTransaction;
19 public function __construct(
20 protected BaseRepo $baseRepo,
21 protected EntityQueries $entityQueries,
22 protected TrashCan $trashCan,
27 * Create a new chapter in the system.
29 public function create(array $input, Book $parentBook): Chapter
31 return (new DatabaseTransaction(function () use ($input, $parentBook) {
32 $chapter = new Chapter();
33 $chapter->book_id = $parentBook->id;
34 $chapter->priority = (new BookContents($parentBook))->getLastPriority() + 1;
35 $this->baseRepo->create($chapter, $input);
36 $this->baseRepo->updateDefaultTemplate($chapter, intval($input['default_template_id'] ?? null));
37 Activity::add(ActivityType::CHAPTER_CREATE, $chapter);
39 $this->baseRepo->sortParent($chapter);
46 * Update the given chapter.
48 public function update(Chapter $chapter, array $input): Chapter
50 $this->baseRepo->update($chapter, $input);
52 if (array_key_exists('default_template_id', $input)) {
53 $this->baseRepo->updateDefaultTemplate($chapter, intval($input['default_template_id']));
56 Activity::add(ActivityType::CHAPTER_UPDATE, $chapter);
58 $this->baseRepo->sortParent($chapter);
64 * Remove a chapter from the system.
68 public function destroy(Chapter $chapter)
70 $this->trashCan->softDestroyChapter($chapter);
71 Activity::add(ActivityType::CHAPTER_DELETE, $chapter);
72 $this->trashCan->autoClearOld();
76 * Move the given chapter into a new parent book.
77 * The $parentIdentifier must be a string of the following format:
78 * 'book:<id>' (book:5).
80 * @throws MoveOperationException
81 * @throws PermissionsException
83 public function move(Chapter $chapter, string $parentIdentifier): Book
85 $parent = $this->entityQueries->findVisibleByStringIdentifier($parentIdentifier);
86 if (!$parent instanceof Book) {
87 throw new MoveOperationException('Book to move chapter into not found');
90 if (!userCan('chapter-create', $parent)) {
91 throw new PermissionsException('User does not have permission to create a chapter within the chosen book');
94 return (new DatabaseTransaction(function () use ($chapter, $parent) {
95 $chapter->changeBook($parent->id);
96 $chapter->rebuildPermissions();
97 Activity::add(ActivityType::CHAPTER_MOVE, $chapter);
99 $this->baseRepo->sortParent($chapter);