]> BookStack Code Mirror - bookstack/blob - app/Entities/Tools/HierarchyTransformer.php
7304962b379c9a4578db8598971053631f194906
[bookstack] / app / Entities / Tools / HierarchyTransformer.php
1 <?php
2
3 namespace BookStack\Entities\Tools;
4
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;
13
14 class HierarchyTransformer
15 {
16     protected BookRepo $bookRepo;
17     protected BookshelfRepo $shelfRepo;
18     protected Cloner $cloner;
19     protected TrashCan $trashCan;
20
21     public function __construct(BookRepo $bookRepo, BookshelfRepo $shelfRepo, Cloner $cloner, TrashCan $trashCan)
22     {
23         $this->bookRepo = $bookRepo;
24         $this->shelfRepo = $shelfRepo;
25         $this->cloner = $cloner;
26         $this->trashCan = $trashCan;
27     }
28
29     /**
30      * Transform a chapter into a book.
31      * Does not check permissions, check before calling.
32      */
33     public function transformChapterToBook(Chapter $chapter): Book
34     {
35         $inputData = $this->cloner->entityToInputData($chapter);
36         $book = $this->bookRepo->create($inputData);
37         $this->cloner->copyEntityPermissions($chapter, $book);
38
39         /** @var Page $page */
40         foreach ($chapter->pages as $page) {
41             $page->chapter_id = 0;
42             $page->changeBook($book->id);
43         }
44
45         $this->trashCan->destroyEntity($chapter);
46
47         Activity::add(ActivityType::BOOK_CREATE_FROM_CHAPTER);
48         return $book;
49     }
50
51     public function transformBookToShelf(Book $book): Bookshelf
52     {
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);
58
59         $shelfBookSyncData = [];
60
61         /** @var Chapter $chapter */
62         foreach ($book->chapters as $index => $chapter) {
63             $newBook = $this->transformChapterToBook($chapter);
64             $shelfBookSyncData[$newBook->id] = ['order' => $index];
65         }
66
67         $shelf->books()->sync($shelfBookSyncData);
68
69         if ($book->directPages->count() > 0) {
70             $book->name .= ' ' . trans('entities.pages');
71         } else {
72             $this->trashCan->destroyEntity($book);
73         }
74
75         // TODO - Log activity for change
76         return $shelf;
77     }
78 }