]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/BaseRepo.php
Fix typos
[bookstack] / app / Entities / Repos / BaseRepo.php
1 <?php
2
3 namespace BookStack\Entities\Repos;
4
5 use BookStack\Actions\TagRepo;
6 use BookStack\Entities\Models\Entity;
7 use BookStack\Entities\Models\HasCoverImage;
8 use BookStack\Exceptions\ImageUploadException;
9 use BookStack\Uploads\ImageRepo;
10 use Illuminate\Http\UploadedFile;
11
12 class BaseRepo
13 {
14     protected TagRepo $tagRepo;
15     protected ImageRepo $imageRepo;
16
17     public function __construct(TagRepo $tagRepo, ImageRepo $imageRepo)
18     {
19         $this->tagRepo = $tagRepo;
20         $this->imageRepo = $imageRepo;
21     }
22
23     /**
24      * Create a new entity in the system.
25      */
26     public function create(Entity $entity, array $input)
27     {
28         $entity->fill($input);
29         $entity->forceFill([
30             'created_by' => user()->id,
31             'updated_by' => user()->id,
32             'owned_by'   => user()->id,
33         ]);
34         $entity->refreshSlug();
35         $entity->save();
36
37         if (isset($input['tags'])) {
38             $this->tagRepo->saveTagsToEntity($entity, $input['tags']);
39         }
40
41         $entity->refresh();
42         $entity->rebuildPermissions();
43         $entity->indexForSearch();
44     }
45
46     /**
47      * Update the given entity.
48      */
49     public function update(Entity $entity, array $input)
50     {
51         $entity->fill($input);
52         $entity->updated_by = user()->id;
53
54         if ($entity->isDirty('name')) {
55             $entity->refreshSlug();
56         }
57
58         $entity->save();
59
60         if (isset($input['tags'])) {
61             $this->tagRepo->saveTagsToEntity($entity, $input['tags']);
62             $entity->touch();
63         }
64
65         $entity->rebuildPermissions();
66         $entity->indexForSearch();
67     }
68
69     /**
70      * Update the given items' cover image, or clear it.
71      *
72      * @param Entity&HasCoverImage $entity
73      *
74      * @throws ImageUploadException
75      * @throws \Exception
76      */
77     public function updateCoverImage($entity, ?UploadedFile $coverImage, bool $removeImage = false)
78     {
79         if ($coverImage) {
80             $this->imageRepo->destroyImage($entity->cover);
81             $image = $this->imageRepo->saveNew($coverImage, 'cover_book', $entity->id, 512, 512, true);
82             $entity->cover()->associate($image);
83             $entity->save();
84         }
85
86         if ($removeImage) {
87             $this->imageRepo->destroyImage($entity->cover);
88             $entity->image_id = 0;
89             $entity->save();
90         }
91     }
92 }