Passed
Push — master ( eab33a...93cd42 )
by Innocent
04:10
created

UploadsImages::updateImage()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 5
rs 10
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
                $this->isNew = false;
35
            }
36
            $ogSave = storage_path('app/public/'.$model->filesDir().'/original/').$fileName;
37
            try {
38
                $imageManager->make($imageData)->save($ogSave);
39
40
                if ($this->isNew) {
41
                    $this->createImage($model, $fileName);
42
                } else {
43
                    $this->updateImage($model, $fileName);
44
                }
45
            } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
46
            }
47
        }
48
    }
49
50
    /**
51
     * Creates a new image.
52
     *
53
     * @param $model
54
     * @param $fileName
55
     */
56
    private function createImage($model, $fileName)
57
    {
58
        $model->images()->create([
59
            'imageable_id' => $model->id,
60
            'name'         => $fileName,
61
        ]);
62
    }
63
64
    /**
65
     * Updates pre-existing image.
66
     *
67
     * @param $model
68
     * @param $fileName
69
     */
70
    private function updateImage($model, $fileName)
71
    {
72
        $model->images()
73
            ->update([
74
                'name' => $fileName,
75
            ]);
76
    }
77
}
78