AbstractImageManager::oldImage()
last analyzed

Size

Total Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1
c 0
b 0
f 0
nc 1
1
<?php
2
3
namespace Gcsc\LaravelMultisizeImage\ImageManagers;
4
5
use Illuminate\Http\UploadedFile;
6
use Intervention\Image\Constraint;
7
use Intervention\Image\Facades\Image;
8
use Illuminate\Support\Facades\Storage;
9
use Gcsc\LaravelMultisizeImage\SavedImageData;
10
use Gcsc\LaravelMultisizeImage\ImageSizes\ImageSizeInterface;
11
use Gcsc\LaravelMultisizeImage\Exceptions\NotValidImageSizeException;
12
13
abstract class AbstractImageManager
14
{
15
    protected static function defaultImageSize()
16
    {
17
        $sizes = static::imageSizes();
18
        $size = end($sizes);
19
        reset($sizes);
20
21
        return $size;
22
    }
23
24
    /**
25
     * @return string
26
     */
27
    abstract protected function oldImage();
28
29
    /**
30
     * @return  array
31
     */
32
    abstract public static function imageSizes();
33
34
    public static function getPathPrefix()
35
    {
36
        return '';
37
    }
38
39
    /**
40
     * @param ImageSizeInterface $image_size
41
     * @param $name
42
     * @return string
43
     */
44
    public static function getPathForImageSize(ImageSizeInterface $image_size, $name)
45
    {
46
        return static::getPathPrefix().'/'.$image_size->getSlug().'/'.$name;
47
    }
48
49
    /**
50
     * @param UploadedFile|string $image
51
     * @param $name
52
     * @return SavedImageData
53
     * @throws NotValidImageSizeException
54
     */
55
    public function save($image, $name = null)
56
    {
57
        if (is_string($image)) {
58
            @[$type, $image] = explode(';', $image);
0 ignored issues
show
Bug introduced by
The variable $type does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
59
            @[, $image] = explode(',', $image);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
60
            if (! $name) {
61
                $name = md5(uniqid(mt_rand(), true)).'.'.\Illuminate\Http\Testing\MimeType::search($type);
62
            }
63
        }
64
65
        if (! $name) {
66
            $name = md5(uniqid(mt_rand(), true)).'.'.$image->getClientOriginalExtension();
0 ignored issues
show
Bug introduced by
It seems like $image is not always an object, but can also be of type string. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
67
        }
68
69
        $imageData = new SavedImageData($name);
70
        foreach ($this->imageSizes() as $image_size_class) {
71
            $image_size = new $image_size_class();
72
            if (! ($image_size instanceof ImageSizeInterface)) {
73
                throw new NotValidImageSizeException('image size except implement ImageSizeInterface');
74
            }
75
76
            /** @var \Intervention\Image\Image $img */
77
            $img = Image::make($image);
78
79
            $img->resize(
80
                $image_size->getWidth(),
81
                $image_size->getHeight(),
82
                function (Constraint $constraint) use ($image_size) {
83
                    if (! $image_size->getForceCrop()) {
84
                        $constraint->aspectRatio();
85
                    }
86
                    $constraint->upsize();
87
                }
88
            );
89
90
            $is_saved = Storage::disk($image_size->getDisk())->put($this->getPathForImageSize($image_size, $name), (string) $img->encode());
91
92
            if ($is_saved) {
93
                $imageData->addSize(
94
                    $image_size::getSlug(),
95
                    [
96
                        'size' => $img->width().'/'.$img->height(),
97
                        'width' => $img->width(),
98
                        'height' => $img->height(),
99
                    ]
100
                );
101
            } else {
102
                $imageData->addError(
103
                    $image_size::getSlug()
104
                );
105
            }
106
        }
107
108
        return $imageData;
109
    }
110
111
    /**
112
     * @param null $name
113
     * @return bool
114
     * @throws NotValidImageSizeException
115
     */
116
    public function delete($name = null)
117
    {
118
        if (is_null($name)) {
119
            $name = $this->oldImage();
120
        }
121
122
        if ($name) {
123
            return static::destroy($name);
124
        }
125
126
        return false;
127
    }
128
129
    /**
130
     * @param $name
131
     * @return bool
132
     * @throws NotValidImageSizeException
133
     */
134
    public static function destroy($name)
135
    {
136
        $is_deleted_statuses = [];
137
        foreach (static::imageSizes() as $image_size_class) {
138
            $image_size = new $image_size_class();
139
            if (! ($image_size instanceof ImageSizeInterface)) {
140
                throw new NotValidImageSizeException('image size except implement ImageSizeInterface');
141
            }
142
            $is_deleted = Storage::disk($image_size->getDisk())->delete(static::getPathForImageSize($image_size, $name));
143
            if ($is_deleted) {
144
                $is_deleted_statuses[] = $image_size_class;
145
            }
146
        }
147
148
        if (count($is_deleted_statuses) === count(static::imageSizes())) {
149
            return true;
150
        }
151
152
        //TODO:: send notification to admin;
153
154
        return false;
155
    }
156
157
    /**
158
     * @param UploadedFile|string $image
159
     * @param $old_name
160
     * @param $new_name
161
     * @return array|null
162
     * @throws NotValidImageSizeException
163
     */
164
    public function replace($image, $old_name, $new_name = null)
165
    {
166
        $this->delete($old_name);
167
168
        return $this->save($image, $new_name);
169
    }
170
171
    /**
172
     * @param UploadedFile|string $image
173
     * @param $new_name
174
     * @return array|null
175
     * @throws NotValidImageSizeException
176
     */
177
    public function replaceOrSave($image, $new_name = null)
178
    {
179
        if ($this->oldImage()) {
180
            return $this->replace($image, $this->oldImage(), $new_name);
181
        }
182
183
        return $this->save($image, $new_name);
184
    }
185
186
    public static function urls($name)
187
    {
188
        $urls = [];
189
        foreach (static::imageSizes() as $image_size_class) {
190
            $image_size = new $image_size_class();
191
            if (! ($image_size instanceof ImageSizeInterface)) {
192
                throw new NotValidImageSizeException('image size except implement ImageSizeInterface');
193
            }
194
195
            $urls[$image_size->getSlug()] = (string) Storage::disk($image_size->getDisk())->url(static::getPathForImageSize($image_size, $name));
196
        }
197
198
        return $urls;
199
    }
200
201
    public static function url($name)
202
    {
203
        $size = static::defaultImageSize();
204
        $image_size = new $size();
205
        if (! ($image_size instanceof ImageSizeInterface)) {
206
            throw new NotValidImageSizeException('image size except implement ImageSizeInterface');
207
        }
208
209
        return (string) Storage::disk($image_size->getDisk())->url(self::getPathForImageSize($image_size, $name));
210
    }
211
}
212