3 namespace BookStack\Entities\Tools;
5 use BookStack\Entities\Models\Book;
6 use BookStack\Entities\Models\Bookshelf;
7 use BookStack\Entities\Models\Chapter;
8 use BookStack\Entities\Models\Page;
9 use BookStack\Entities\Repos\BookRepo;
10 use BookStack\Entities\Repos\BookshelfRepo;
12 class HierarchyTransformer
14 protected BookRepo $bookRepo;
15 protected BookshelfRepo $shelfRepo;
16 protected Cloner $cloner;
17 protected TrashCan $trashCan;
19 // TODO - Test setting book cover image from API
20 // Ensure we can update without resetting image accidentally
21 // Ensure api docs correct.
22 // TODO - As above but for shelves.
24 public function transformChapterToBook(Chapter $chapter): Book
26 // TODO - Check permissions before call
27 // Permissions: edit-chapter, delete-chapter, create-book
28 $inputData = $this->cloner->entityToInputData($chapter);
29 $book = $this->bookRepo->create($inputData);
31 // TODO - Copy permissions
33 /** @var Page $page */
34 foreach ($chapter->pages as $page) {
35 $page->chapter_id = 0;
36 $page->changeBook($book->id);
39 $this->trashCan->destroyEntity($chapter);
41 // TODO - Log activity for change
45 public function transformBookToShelf(Book $book): Bookshelf
47 // TODO - Check permissions before call
48 // Permissions: edit-book, delete-book, create-shelf
49 $inputData = $this->cloner->entityToInputData($book);
50 $shelf = $this->shelfRepo->create($inputData, []);
52 // TODO - Copy permissions?
54 $shelfBookSyncData = [];
56 /** @var Chapter $chapter */
57 foreach ($book->chapters as $index => $chapter) {
58 $newBook = $this->transformChapterToBook($chapter);
59 $shelfBookSyncData[$newBook->id] = ['order' => $index];
62 $shelf->books()->sync($shelfBookSyncData);
64 if ($book->directPages->count() > 0) {
65 $book->name .= ' ' . trans('entities.pages');
67 $this->trashCan->destroyEntity($book);
70 // TODO - Log activity for change