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