]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/BookshelfRepo.php
Queries: Migrated bookshelf repo queries to new class
[bookstack] / app / Entities / Repos / BookshelfRepo.php
1 <?php
2
3 namespace BookStack\Entities\Repos;
4
5 use BookStack\Activity\ActivityType;
6 use BookStack\Entities\Models\Book;
7 use BookStack\Entities\Models\Bookshelf;
8 use BookStack\Entities\Tools\TrashCan;
9 use BookStack\Facades\Activity;
10 use Exception;
11
12 class BookshelfRepo
13 {
14     public function __construct(
15         protected BaseRepo $baseRepo,
16     ) {
17     }
18
19     /**
20      * Create a new shelf in the system.
21      */
22     public function create(array $input, array $bookIds): Bookshelf
23     {
24         $shelf = new Bookshelf();
25         $this->baseRepo->create($shelf, $input);
26         $this->baseRepo->updateCoverImage($shelf, $input['image'] ?? null);
27         $this->updateBooks($shelf, $bookIds);
28         Activity::add(ActivityType::BOOKSHELF_CREATE, $shelf);
29
30         return $shelf;
31     }
32
33     /**
34      * Update an existing shelf in the system using the given input.
35      */
36     public function update(Bookshelf $shelf, array $input, ?array $bookIds): Bookshelf
37     {
38         $this->baseRepo->update($shelf, $input);
39
40         if (!is_null($bookIds)) {
41             $this->updateBooks($shelf, $bookIds);
42         }
43
44         if (array_key_exists('image', $input)) {
45             $this->baseRepo->updateCoverImage($shelf, $input['image'], $input['image'] === null);
46         }
47
48         Activity::add(ActivityType::BOOKSHELF_UPDATE, $shelf);
49
50         return $shelf;
51     }
52
53     /**
54      * Update which books are assigned to this shelf by syncing the given book ids.
55      * Function ensures the books are visible to the current user and existing.
56      */
57     protected function updateBooks(Bookshelf $shelf, array $bookIds)
58     {
59         $numericIDs = collect($bookIds)->map(function ($id) {
60             return intval($id);
61         });
62
63         $syncData = Book::visible()
64             ->whereIn('id', $bookIds)
65             ->pluck('id')
66             ->mapWithKeys(function ($bookId) use ($numericIDs) {
67                 return [$bookId => ['order' => $numericIDs->search($bookId)]];
68             });
69
70         $shelf->books()->sync($syncData);
71     }
72
73     /**
74      * Remove a bookshelf from the system.
75      *
76      * @throws Exception
77      */
78     public function destroy(Bookshelf $shelf)
79     {
80         $trashCan = new TrashCan();
81         $trashCan->softDestroyShelf($shelf);
82         Activity::add(ActivityType::BOOKSHELF_DELETE, $shelf);
83         $trashCan->autoClearOld();
84     }
85 }