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 protected BookRepo $bookRepo;
17 protected BookshelfRepo $shelfRepo;
18 protected Cloner $cloner;
19 protected TrashCan $trashCan;
21 public function __construct(BookRepo $bookRepo, BookshelfRepo $shelfRepo, Cloner $cloner, TrashCan $trashCan)
23 $this->bookRepo = $bookRepo;
24 $this->shelfRepo = $shelfRepo;
25 $this->cloner = $cloner;
26 $this->trashCan = $trashCan;
30 * Transform a chapter into a book.
31 * Does not check permissions, check before calling.
33 public function transformChapterToBook(Chapter $chapter): Book
35 $inputData = $this->cloner->entityToInputData($chapter);
36 $book = $this->bookRepo->create($inputData);
37 $this->cloner->copyEntityPermissions($chapter, $book);
39 /** @var Page $page */
40 foreach ($chapter->pages as $page) {
41 $page->chapter_id = 0;
42 $page->changeBook($book->id);
45 $this->trashCan->destroyEntity($chapter);
47 Activity::add(ActivityType::BOOK_CREATE_FROM_CHAPTER, $book);
53 * Transform a book into a shelf.
54 * Does not check permissions, check before calling.
56 public function transformBookToShelf(Book $book): Bookshelf
58 $inputData = $this->cloner->entityToInputData($book);
59 $shelf = $this->shelfRepo->create($inputData, []);
60 $this->cloner->copyEntityPermissions($book, $shelf);
62 $shelfBookSyncData = [];
64 /** @var Chapter $chapter */
65 foreach ($book->chapters as $index => $chapter) {
66 $newBook = $this->transformChapterToBook($chapter);
67 $shelfBookSyncData[$newBook->id] = ['order' => $index];
68 if (!$newBook->hasPermissions()) {
69 $this->cloner->copyEntityPermissions($shelf, $newBook);
73 if ($book->directPages->count() > 0) {
74 $book->name .= ' ' . trans('entities.pages');
75 $shelfBookSyncData[$book->id] = ['order' => count($shelfBookSyncData) + 1];
78 $this->trashCan->destroyEntity($book);
81 $shelf->books()->sync($shelfBookSyncData);
83 Activity::add(ActivityType::BOOKSHELF_CREATE_FROM_BOOK, $shelf);