3 namespace BookStack\Entities\Repos;
5 use BookStack\Actions\ActivityType;
6 use BookStack\Actions\TagRepo;
7 use BookStack\Entities\Models\Entity;
8 use BookStack\Entities\Models\HasCoverImage;
9 use BookStack\Exceptions\ImageUploadException;
10 use BookStack\Facades\Activity;
11 use BookStack\Uploads\ImageRepo;
12 use Illuminate\Http\UploadedFile;
13 use Illuminate\Support\Collection;
22 public function __construct(TagRepo $tagRepo, ImageRepo $imageRepo)
24 $this->tagRepo = $tagRepo;
25 $this->imageRepo = $imageRepo;
29 * Create a new entity in the system
31 public function create(Entity $entity, array $input)
33 $entity->fill($input);
35 'created_by' => user()->id,
36 'updated_by' => user()->id,
38 $entity->refreshSlug();
41 if (isset($input['tags'])) {
42 $this->tagRepo->saveTagsToEntity($entity, $input['tags']);
45 $entity->rebuildPermissions();
46 $entity->indexForSearch();
50 * Update the given entity.
52 public function update(Entity $entity, array $input)
54 $entity->fill($input);
55 $entity->updated_by = user()->id;
57 if ($entity->isDirty('name')) {
58 $entity->refreshSlug();
63 if (isset($input['tags'])) {
64 $this->tagRepo->saveTagsToEntity($entity, $input['tags']);
67 $entity->rebuildPermissions();
68 $entity->indexForSearch();
72 * Update the given items' cover image, or clear it.
73 * @throws ImageUploadException
76 public function updateCoverImage(HasCoverImage $entity, ?UploadedFile $coverImage, bool $removeImage = false)
79 $this->imageRepo->destroyImage($entity->cover);
80 $image = $this->imageRepo->saveNew($coverImage, 'cover_book', $entity->id, 512, 512, true);
81 $entity->cover()->associate($image);
86 $this->imageRepo->destroyImage($entity->cover);
87 $entity->image_id = 0;
93 * Update the permissions of an entity.
95 public function updatePermissions(Entity $entity, bool $restricted, Collection $permissions = null)
97 $entity->restricted = $restricted;
98 $entity->permissions()->delete();
100 if (!is_null($permissions)) {
101 $entityPermissionData = $permissions->flatMap(function ($restrictions, $roleId) {
102 return collect($restrictions)->keys()->map(function ($action) use ($roleId) {
104 'role_id' => $roleId,
105 'action' => strtolower($action),
110 $entity->permissions()->createMany($entityPermissionData);
114 $entity->rebuildPermissions();
115 Activity::addForEntity($entity, ActivityType::PERMISSIONS_UPDATE);