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 public function transformChapterToBook(Chapter $chapter): Book
21 // TODO - Check permissions before call
22 // Permissions: edit-chapter, delete-chapter, create-book
23 $inputData = $this->cloner->entityToInputData($chapter);
24 $book = $this->bookRepo->create($inputData);
25 $this->cloner->copyEntityPermissions($chapter, $book);
27 /** @var Page $page */
28 foreach ($chapter->pages as $page) {
29 $page->chapter_id = 0;
30 $page->changeBook($book->id);
33 $this->trashCan->destroyEntity($chapter);
35 // TODO - Log activity for change
39 public function transformBookToShelf(Book $book): Bookshelf
41 // TODO - Check permissions before call
42 // Permissions: edit-book, delete-book, create-shelf
43 $inputData = $this->cloner->entityToInputData($book);
44 $shelf = $this->shelfRepo->create($inputData, []);
45 $this->cloner->copyEntityPermissions($book, $shelf);
47 $shelfBookSyncData = [];
49 /** @var Chapter $chapter */
50 foreach ($book->chapters as $index => $chapter) {
51 $newBook = $this->transformChapterToBook($chapter);
52 $shelfBookSyncData[$newBook->id] = ['order' => $index];
55 $shelf->books()->sync($shelfBookSyncData);
57 if ($book->directPages->count() > 0) {
58 $book->name .= ' ' . trans('entities.pages');
60 $this->trashCan->destroyEntity($book);
63 // TODO - Log activity for change