]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/HierarchyTransformer.php
17e153e0562b0b8f2cc1fdbc9c30044f44e64c59
[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     // TODO - Test setting book cover image from API
20     //   Ensure we can update without resetting image accidentally
21     //   Ensure api docs correct.
22     // TODO - As above but for shelves.
23
24     public function transformChapterToBook(Chapter $chapter): Book
25     {
26         // TODO - Check permissions before call
27         //   Permissions: edit-chapter, delete-chapter, create-book
28         $inputData = $this->cloner->entityToInputData($chapter);
29         $book = $this->bookRepo->create($inputData);
30
31         // TODO - Copy permissions
32
33         /** @var Page $page */
34         foreach ($chapter->pages as $page) {
35             $page->chapter_id = 0;
36             $page->changeBook($book->id);
37         }
38
39         $this->trashCan->destroyEntity($chapter);
40
41         // TODO - Log activity for change
42         return $book;
43     }
44
45     public function transformBookToShelf(Book $book): Bookshelf
46     {
47         // TODO - Check permissions before call
48         //   Permissions: edit-book, delete-book, create-shelf
49         $inputData = $this->cloner->entityToInputData($book);
50         $shelf = $this->shelfRepo->create($inputData, []);
51
52         // TODO - Copy permissions?
53
54         $shelfBookSyncData = [];
55
56         /** @var Chapter $chapter */
57         foreach ($book->chapters as $index => $chapter) {
58             $newBook = $this->transformChapterToBook($chapter);
59             $shelfBookSyncData[$newBook->id] = ['order' => $index];
60         }
61
62         $shelf->books()->sync($shelfBookSyncData);
63
64         if ($book->directPages->count() > 0) {
65             $book->name .= ' ' . trans('entities.pages');
66         } else {
67             $this->trashCan->destroyEntity($book);
68         }
69
70         // TODO - Log activity for change
71         return $shelf;
72     }
73 }