]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/BaseRepo.php
Apply fixes from StyleCI
[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;
15     protected $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->rebuildPermissions();
42         $entity->indexForSearch();
43     }
44
45     /**
46      * Update the given entity.
47      */
48     public function update(Entity $entity, array $input)
49     {
50         $entity->fill($input);
51         $entity->updated_by = user()->id;
52
53         if ($entity->isDirty('name')) {
54             $entity->refreshSlug();
55         }
56
57         $entity->save();
58
59         if (isset($input['tags'])) {
60             $this->tagRepo->saveTagsToEntity($entity, $input['tags']);
61         }
62
63         $entity->rebuildPermissions();
64         $entity->indexForSearch();
65     }
66
67     /**
68      * Update the given items' cover image, or clear it.
69      *
70      * @throws ImageUploadException
71      * @throws \Exception
72      */
73     public function updateCoverImage(HasCoverImage $entity, ?UploadedFile $coverImage, bool $removeImage = false)
74     {
75         if ($coverImage) {
76             $this->imageRepo->destroyImage($entity->cover);
77             $image = $this->imageRepo->saveNew($coverImage, 'cover_book', $entity->id, 512, 512, true);
78             $entity->cover()->associate($image);
79             $entity->save();
80         }
81
82         if ($removeImage) {
83             $this->imageRepo->destroyImage($entity->cover);
84             $entity->image_id = 0;
85             $entity->save();
86         }
87     }
88 }