3 namespace BookStack\Entities\Tools;
5 use BookStack\Actions\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);
51 public function transformBookToShelf(Book $book): Bookshelf
53 // TODO - Check permissions before call
54 // Permissions: edit-book, delete-book, create-shelf
55 $inputData = $this->cloner->entityToInputData($book);
56 $shelf = $this->shelfRepo->create($inputData, []);
57 $this->cloner->copyEntityPermissions($book, $shelf);
59 $shelfBookSyncData = [];
61 /** @var Chapter $chapter */
62 foreach ($book->chapters as $index => $chapter) {
63 $newBook = $this->transformChapterToBook($chapter);
64 $shelfBookSyncData[$newBook->id] = ['order' => $index];
67 $shelf->books()->sync($shelfBookSyncData);
69 if ($book->directPages->count() > 0) {
70 $book->name .= ' ' . trans('entities.pages');
72 $this->trashCan->destroyEntity($book);
75 // TODO - Log activity for change