3 namespace BookStack\Entities\Repos;
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;
14 public function __construct(
15 protected BaseRepo $baseRepo,
16 protected BookQueries $bookQueries,
17 protected TrashCan $trashCan,
22 * Create a new shelf in the system.
24 public function create(array $input, array $bookIds): Bookshelf
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);
36 * Update an existing shelf in the system using the given input.
38 public function update(Bookshelf $shelf, array $input, ?array $bookIds): Bookshelf
40 $this->baseRepo->update($shelf, $input);
42 if (!is_null($bookIds)) {
43 $this->updateBooks($shelf, $bookIds);
46 if (array_key_exists('image', $input)) {
47 $this->baseRepo->updateCoverImage($shelf, $input['image'], $input['image'] === null);
50 Activity::add(ActivityType::BOOKSHELF_UPDATE, $shelf);
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.
59 protected function updateBooks(Bookshelf $shelf, array $bookIds)
61 $numericIDs = collect($bookIds)->map(function ($id) {
65 $syncData = $this->bookQueries->visibleForList()
66 ->whereIn('id', $bookIds)
68 ->mapWithKeys(function ($bookId) use ($numericIDs) {
69 return [$bookId => ['order' => $numericIDs->search($bookId)]];
72 $shelf->books()->sync($syncData);
76 * Remove a bookshelf from the system.
80 public function destroy(Bookshelf $shelf)
82 $this->trashCan->softDestroyShelf($shelf);
83 Activity::add(ActivityType::BOOKSHELF_DELETE, $shelf);
84 $this->trashCan->autoClearOld();