1 | <?php |
||
2 | |||
3 | namespace FaithGen\SDK\Traits; |
||
4 | |||
5 | use FaithGen\SDK\Traits\Relationships\Morphs\ImageableTrait; |
||
6 | use Intervention\Image\ImageManager; |
||
7 | use InvalidArgumentException; |
||
8 | |||
9 | trait UploadsImages |
||
10 | { |
||
11 | private bool $isNew = true; |
||
12 | |||
13 | /** |
||
14 | * Saves the uploaded images. |
||
15 | * |
||
16 | * @param $model |
||
17 | * @param array $images |
||
18 | * @param ImageManager $imageManager |
||
19 | * @param string|null $fileName |
||
20 | */ |
||
21 | protected function uploadImages($model, array $images, ImageManager $imageManager, string $fileName = null) |
||
22 | { |
||
23 | if (! in_array(StorageTrait::class, class_uses($model))) { |
||
24 | throw new InvalidArgumentException('The model you used does not use the Storage trait'); |
||
25 | } |
||
26 | |||
27 | if (! in_array(ImageableTrait::class, class_uses($model))) { |
||
28 | throw new InvalidArgumentException('The model you used does not use the Imageable trait'); |
||
29 | } |
||
30 | |||
31 | foreach ($images as $imageData) { |
||
32 | if (! $fileName) { |
||
33 | $fileName = str_shuffle($model->id.time().time()).'.png'; |
||
34 | } else { |
||
35 | $this->isNew = false; |
||
36 | } |
||
37 | |||
38 | $ogSave = storage_path('app/public/'.$model->filesDir().'/original/').$fileName; |
||
39 | |||
40 | try { |
||
41 | $imageManager->make($imageData)->save($ogSave); |
||
42 | |||
43 | if ($this->isNew) { |
||
44 | $this->createImage($model, $fileName); |
||
45 | } else { |
||
46 | $this->updateImage($model, $fileName); |
||
47 | } |
||
48 | } catch (\Exception $e) { |
||
0 ignored issues
–
show
Coding Style
Comprehensibility
introduced
by
![]() |
|||
49 | } |
||
50 | } |
||
51 | } |
||
52 | |||
53 | /** |
||
54 | * Creates a new image. |
||
55 | * |
||
56 | * @param $model |
||
57 | * @param $fileName |
||
58 | */ |
||
59 | private function createImage($model, $fileName) |
||
60 | { |
||
61 | $model->images() |
||
62 | ->create([ |
||
63 | 'imageable_id' => $model->id, |
||
64 | 'name' => $fileName, |
||
65 | ]); |
||
66 | } |
||
67 | |||
68 | /** |
||
69 | * Updates pre-existing image. |
||
70 | * |
||
71 | * @param $model |
||
72 | * @param $fileName |
||
73 | */ |
||
74 | private function updateImage($model, $fileName) |
||
75 | { |
||
76 | $model->images() |
||
77 | ->update([ |
||
78 | 'name' => $fileName, |
||
79 | ]); |
||
80 | } |
||
81 | } |
||
82 |