3 namespace BookStack\Entities\Repos;
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;
14 public function __construct(
15 protected BaseRepo $baseRepo,
20 * Create a new shelf in the system.
22 public function create(array $input, array $bookIds): Bookshelf
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);
34 * Update an existing shelf in the system using the given input.
36 public function update(Bookshelf $shelf, array $input, ?array $bookIds): Bookshelf
38 $this->baseRepo->update($shelf, $input);
40 if (!is_null($bookIds)) {
41 $this->updateBooks($shelf, $bookIds);
44 if (array_key_exists('image', $input)) {
45 $this->baseRepo->updateCoverImage($shelf, $input['image'], $input['image'] === null);
48 Activity::add(ActivityType::BOOKSHELF_UPDATE, $shelf);
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.
57 protected function updateBooks(Bookshelf $shelf, array $bookIds)
59 $numericIDs = collect($bookIds)->map(function ($id) {
63 $syncData = Book::visible()
64 ->whereIn('id', $bookIds)
66 ->mapWithKeys(function ($bookId) use ($numericIDs) {
67 return [$bookId => ['order' => $numericIDs->search($bookId)]];
70 $shelf->books()->sync($syncData);
74 * Remove a bookshelf from the system.
78 public function destroy(Bookshelf $shelf)
80 $trashCan = new TrashCan();
81 $trashCan->softDestroyShelf($shelf);
82 Activity::add(ActivityType::BOOKSHELF_DELETE, $shelf);
83 $trashCan->autoClearOld();