]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/BookshelfRepo.php
Updated translator & dependency attribution before release v25.05.1
[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\Bookshelf;
7 use BookStack\Entities\Queries\BookQueries;
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         protected BookQueries $bookQueries,
17         protected TrashCan $trashCan,
18     ) {
19     }
20
21     /**
22      * Create a new shelf in the system.
23      */
24     public function create(array $input, array $bookIds): Bookshelf
25     {
26         $shelf = new Bookshelf();
27         $this->baseRepo->create($shelf, $input);
28         $this->baseRepo->updateCoverImage($shelf, $input['image'] ?? null);
29         $this->updateBooks($shelf, $bookIds);
30         Activity::add(ActivityType::BOOKSHELF_CREATE, $shelf);
31
32         return $shelf;
33     }
34
35     /**
36      * Update an existing shelf in the system using the given input.
37      */
38     public function update(Bookshelf $shelf, array $input, ?array $bookIds): Bookshelf
39     {
40         $this->baseRepo->update($shelf, $input);
41
42         if (!is_null($bookIds)) {
43             $this->updateBooks($shelf, $bookIds);
44         }
45
46         if (array_key_exists('image', $input)) {
47             $this->baseRepo->updateCoverImage($shelf, $input['image'], $input['image'] === null);
48         }
49
50         Activity::add(ActivityType::BOOKSHELF_UPDATE, $shelf);
51
52         return $shelf;
53     }
54
55     /**
56      * Update which books are assigned to this shelf by syncing the given book ids.
57      * Function ensures the books are visible to the current user and existing.
58      */
59     protected function updateBooks(Bookshelf $shelf, array $bookIds)
60     {
61         $numericIDs = collect($bookIds)->map(function ($id) {
62             return intval($id);
63         });
64
65         $syncData = $this->bookQueries->visibleForList()
66             ->whereIn('id', $bookIds)
67             ->pluck('id')
68             ->mapWithKeys(function ($bookId) use ($numericIDs) {
69                 return [$bookId => ['order' => $numericIDs->search($bookId)]];
70             });
71
72         $shelf->books()->sync($syncData);
73     }
74
75     /**
76      * Remove a bookshelf from the system.
77      *
78      * @throws Exception
79      */
80     public function destroy(Bookshelf $shelf)
81     {
82         $this->trashCan->softDestroyShelf($shelf);
83         Activity::add(ActivityType::BOOKSHELF_DELETE, $shelf);
84         $this->trashCan->autoClearOld();
85     }
86 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.