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,
37 'owned_by' => user()->id,
39 $entity->refreshSlug();
42 if (isset($input['tags'])) {
43 $this->tagRepo->saveTagsToEntity($entity, $input['tags']);
46 $entity->rebuildPermissions();
47 $entity->indexForSearch();
51 * Update the given entity.
53 public function update(Entity $entity, array $input)
55 $entity->fill($input);
56 $entity->updated_by = user()->id;
58 if ($entity->isDirty('name')) {
59 $entity->refreshSlug();
64 if (isset($input['tags'])) {
65 $this->tagRepo->saveTagsToEntity($entity, $input['tags']);
68 $entity->rebuildPermissions();
69 $entity->indexForSearch();
73 * Update the given items' cover image, or clear it.
74 * @throws ImageUploadException
77 public function updateCoverImage(HasCoverImage $entity, ?UploadedFile $coverImage, bool $removeImage = false)
80 $this->imageRepo->destroyImage($entity->cover);
81 $image = $this->imageRepo->saveNew($coverImage, 'cover_book', $entity->id, 512, 512, true);
82 $entity->cover()->associate($image);
87 $this->imageRepo->destroyImage($entity->cover);
88 $entity->image_id = 0;
94 * Update the permissions of an entity.
96 public function updatePermissions(Entity $entity, bool $restricted, Collection $permissions = null)
98 $entity->restricted = $restricted;
99 $entity->permissions()->delete();
101 if (!is_null($permissions)) {
102 $entityPermissionData = $permissions->flatMap(function ($restrictions, $roleId) {
103 return collect($restrictions)->keys()->map(function ($action) use ($roleId) {
105 'role_id' => $roleId,
106 'action' => strtolower($action),
111 $entity->permissions()->createMany($entityPermissionData);
115 $entity->rebuildPermissions();
116 Activity::addForEntity($entity, ActivityType::PERMISSIONS_UPDATE);