]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/HierarchyTransformer.php
c95d5fa5307e4d4e7d9bd930d8a031f7b15de804
[bookstack] / app / Entities / Tools / HierarchyTransformer.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
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;
11
12 class HierarchyTransformer
13 {
14     protected BookRepo $bookRepo;
15     protected BookshelfRepo $shelfRepo;
16     protected Cloner $cloner;
17     protected TrashCan $trashCan;
18
19     public function transformChapterToBook(Chapter $chapter): Book
20     {
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);
26
27         /** @var Page $page */
28         foreach ($chapter->pages as $page) {
29             $page->chapter_id = 0;
30             $page->changeBook($book->id);
31         }
32
33         $this->trashCan->destroyEntity($chapter);
34
35         // TODO - Log activity for change
36         return $book;
37     }
38
39     public function transformBookToShelf(Book $book): Bookshelf
40     {
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);
46
47         $shelfBookSyncData = [];
48
49         /** @var Chapter $chapter */
50         foreach ($book->chapters as $index => $chapter) {
51             $newBook = $this->transformChapterToBook($chapter);
52             $shelfBookSyncData[$newBook->id] = ['order' => $index];
53         }
54
55         $shelf->books()->sync($shelfBookSyncData);
56
57         if ($book->directPages->count() > 0) {
58             $book->name .= ' ' . trans('entities.pages');
59         } else {
60             $this->trashCan->destroyEntity($book);
61         }
62
63         // TODO - Log activity for change
64         return $shelf;
65     }
66 }