3 namespace BookStack\Entities\Tools;
5 use BookStack\Activity\ActivityType;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Models\Chapter;
9 use BookStack\Entities\Models\Page;
10 use BookStack\Entities\Repos\BookRepo;
11 use BookStack\Entities\Repos\BookshelfRepo;
12 use BookStack\Facades\Activity;
14 class HierarchyTransformer
16 public function __construct(
17 protected BookRepo $bookRepo,
18 protected BookshelfRepo $shelfRepo,
19 protected Cloner $cloner,
20 protected TrashCan $trashCan
25 * Transform a chapter into a book.
26 * Does not check permissions, check before calling.
28 public function transformChapterToBook(Chapter $chapter): Book
30 $inputData = $this->cloner->entityToInputData($chapter);
31 $book = $this->bookRepo->create($inputData);
32 $this->cloner->copyEntityPermissions($chapter, $book);
34 /** @var Page $page */
35 foreach ($chapter->pages as $page) {
36 $page->chapter_id = 0;
37 $page->changeBook($book->id);
40 $this->trashCan->destroyEntity($chapter);
42 Activity::add(ActivityType::BOOK_CREATE_FROM_CHAPTER, $book);
48 * Transform a book into a shelf.
49 * Does not check permissions, check before calling.
51 public function transformBookToShelf(Book $book): Bookshelf
53 $inputData = $this->cloner->entityToInputData($book);
54 $shelf = $this->shelfRepo->create($inputData, []);
55 $this->cloner->copyEntityPermissions($book, $shelf);
57 $shelfBookSyncData = [];
59 /** @var Chapter $chapter */
60 foreach ($book->chapters as $index => $chapter) {
61 $newBook = $this->transformChapterToBook($chapter);
62 $shelfBookSyncData[$newBook->id] = ['order' => $index];
63 if (!$newBook->hasPermissions()) {
64 $this->cloner->copyEntityPermissions($shelf, $newBook);
68 if ($book->directPages->count() > 0) {
69 $book->name .= ' ' . trans('entities.pages');
70 $shelfBookSyncData[$book->id] = ['order' => count($shelfBookSyncData) + 1];
73 $this->trashCan->destroyEntity($book);
76 $shelf->books()->sync($shelfBookSyncData);
78 Activity::add(ActivityType::BOOKSHELF_CREATE_FROM_BOOK, $shelf);