]> BookStack Code Mirror - bookstack/blob - app/Entities/Repos/BaseRepo.php
Replaced embeds with images in exports
[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->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             $entity->touch();
62         }
63
64         $entity->rebuildPermissions();
65         $entity->indexForSearch();
66     }
67
68     /**
69      * Update the given items' cover image, or clear it.
70      *
71      * @param Entity&HasCoverImage $entity
72      *
73      * @throws ImageUploadException
74      * @throws \Exception
75      */
76     public function updateCoverImage($entity, ?UploadedFile $coverImage, bool $removeImage = false)
77     {
78         if ($coverImage) {
79             $this->imageRepo->destroyImage($entity->cover);
80             $image = $this->imageRepo->saveNew($coverImage, 'cover_book', $entity->id, 512, 512, true);
81             $entity->cover()->associate($image);
82             $entity->save();
83         }
84
85         if ($removeImage) {
86             $this->imageRepo->destroyImage($entity->cover);
87             $entity->image_id = 0;
88             $entity->save();
89         }
90     }
91 }