Passed
Branch master (2bf626)
by Robson
01:44
created

Cropper::toWebP()   A

Complexity

Conditions 2
Paths 4

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 7
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
namespace CoffeeCode\Cropper;
4
5
use Exception;
6
use WebPConvert\Convert\Exceptions\ConversionFailedException;
7
use WebPConvert\WebPConvert;
8
9
/**
10
 * Class CoffeeCode Cropper
11
 *
12
 * @author Robson V. Leite <https://github.com/robsonvleite>
13
 * @package CoffeeCode\Cropper
14
 */
15
class Cropper
16
{
17
    /** @var string */
18
    private $cachePath;
19
20
    /** @var string */
21
    private $imagePath;
22
23
    /** @var string */
24
    private $imageName;
25
26
    /** @var string */
27
    private $imageMime;
28
29
    /** @var int */
30
    private $quality;
31
32
    /** @var int */
33
    private $compressor;
34
35
    /**@var bool */
36
    private $webP;
37
38
    /**
39
     * Allow jpg and png to thumb and cache generate
40
     * @var array allowed media types
41
     */
42
    private static $allowedExt = ['image/jpeg', "image/png"];
43
44
    /**
45
     * Cropper constructor.
46
     *
47
     * @param string $cachePath
48
     * @param int $quality
49
     * @param int $compressor
50
     * @param bool $webP
51
     * @throws Exception
52
     */
53
    public function __construct(string $cachePath, int $quality = 75, int $compressor = 5, bool $webP = true)
54
    {
55
        $this->cachePath = $cachePath;
56
        $this->quality = $quality;
57
        $this->compressor = $compressor;
58
        $this->webP = $webP;
59
60
        if (!file_exists($this->cachePath) || !is_dir($this->cachePath)) {
61
            if (!mkdir($this->cachePath, 0755, true)) {
62
                throw new Exception("Could not create cache folder");
63
            }
64
        }
65
    }
66
67
    /**
68
     * Make an thumb image
69
     *
70
     * @param string $imagePath
71
     * @param int $width
72
     * @param int|null $height
73
     * @return null|string
74
     */
75
    public function make(string $imagePath, int $width, int $height = null): ?string
76
    {
77
        if (!file_exists($imagePath)) {
78
            return "Image not found";
79
        }
80
81
        $this->imagePath = $imagePath;
82
        $this->imageName = $this->name($this->imagePath, $width, $height);
83
        $this->imageMime = mime_content_type($this->imagePath);
84
        $this->imageInfo = pathinfo($this->imagePath);
0 ignored issues
show
Bug Best Practice introduced by
The property imageInfo does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
85
86
        if (!in_array($this->imageMime, self::$allowedExt)) {
87
            return "Not a valid JPG or PNG image";
88
        }
89
90
        $imageWebP = "{$this->cachePath}/{$this->imageName}.webp";
91
        $imageExt = "{$this->cachePath}/{$this->imageName}.{$this->imageInfo['extension']}";
92
93
        if ($this->webP && file_exists($imageWebP) && is_file($imageWebP)) {
94
            return $imageWebP;
95
        }
96
97
        if (file_exists($imageExt) && is_file($imageExt)) {
98
            return $imageExt;
99
        }
100
101
        return $this->imageCache($width, $height);
102
    }
103
104
    /**
105
     * @param string $name
106
     * @param int $width
107
     * @param int $height
108
     * @return string
109
     */
110
    protected function name(string $name, int $width = null, int $height = null): string
111
    {
112
        $filterName = filter_var(mb_strtolower(pathinfo($name)["filename"]), FILTER_SANITIZE_STRIPPED);
113
        $formats = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜüÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿRr"!@#$%&*()_-+={[}]/?;:.,\\\'<>°ºª';
114
        $replace = 'aaaaaaaceeeeiiiidnoooooouuuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr                                 ';
115
        $trimName = trim(strtr(utf8_decode($filterName), utf8_decode($formats), $replace));
116
        $name = str_replace(["-----", "----", "---", "--"], "-", str_replace(" ", "-", $trimName));
117
118
        $hash = $this->hash($this->imagePath);
119
        $widthName = ($width ? "-{$width}" : "");
120
        $heightName = ($height ? "x{$height}" : "");
121
122
        return "{$name}{$widthName}{$heightName}-{$hash}";
123
    }
124
125
    /**
126
     * @param string $path
127
     * @return string
128
     */
129
    protected function hash(string $path): string
130
    {
131
        return hash("crc32", pathinfo($path)['basename']);
132
    }
133
134
    /**
135
     * Clear cache
136
     *
137
     * @param string|null $imagePath
138
     * @example $t->flush("images/image.jpg"); clear image name and variations size
139
     * @example $t->flush(); clear all image cache folder
140
     */
141
    public function flush(string $imagePath = null): void
142
    {
143
        foreach (scandir($this->cachePath) as $file) {
144
            $file = "{$this->cachePath}/{$file}";
145
            if ($imagePath && strpos($file, $this->hash($imagePath))) {
146
                $this->imageDestroy($file);
147
            } elseif (!$imagePath) {
148
                $this->imageDestroy($file);
149
            }
150
        }
151
    }
152
153
    /**
154
     * @param int $width
155
     * @param int|null $height
156
     * @return null|string
157
     */
158
    private function imageCache(int $width, int $height = null): ?string
159
    {
160
        list($src_w, $src_h) = getimagesize($this->imagePath);
161
        $height = ($height ?? ($width * $src_h) / $src_w);
162
163
        $src_x = 0;
164
        $src_y = 0;
165
166
        $cmp_x = $src_w / $width;
167
        $cmp_y = $src_h / $height;
168
169
        if ($cmp_x > $cmp_y) {
170
            $src_w = round($src_w / $cmp_x * $cmp_y);
171
            $src_x = round(($src_w - ($src_w / $cmp_x * $cmp_y))); //2
172
        } elseif ($cmp_y > $cmp_x) {
173
            $src_h = round($src_h / $cmp_y * $cmp_x);
174
            $src_y = round(($src_h - ($src_h / $cmp_y * $cmp_x))); //2
175
        }
176
177
        $src_x = (int)$src_x;
178
        $src_h = (int)$src_h;
179
        $src_y = (int)$src_y;
180
        $src_y = (int)$src_y;
181
182
        if ($this->imageMime == "image/jpeg") {
183
            return $this->fromJpg($width, $height, $src_x, $src_y, $src_w, $src_h);
184
        }
185
186
        if ($this->imageMime == "image/png") {
187
            return $this->fromPng($width, $height, $src_x, $src_y, $src_w, $src_h);
188
        }
189
190
        return null;
191
    }
192
193
    /**
194
     * @param string $imagePatch
195
     */
196
    private function imageDestroy(string $imagePatch): void
197
    {
198
        if (file_exists($imagePatch) && is_file($imagePatch)) {
199
            unlink($imagePatch);
200
        }
201
    }
202
203
    /**
204
     * @param int $width
205
     * @param int $height
206
     * @param int $src_x
207
     * @param int $src_y
208
     * @param int $src_w
209
     * @param int $src_h
210
     * @return string
211
     */
212
    private function fromJpg(int $width, int $height, int $src_x, int $src_y, int $src_w, int $src_h): string
213
    {
214
        $thumb = imagecreatetruecolor($width, $height);
215
        $source = imagecreatefromjpeg($this->imagePath);
216
217
        imagecopyresampled($thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
0 ignored issues
show
Bug introduced by
It seems like $source can also be of type false; however, parameter $src_image of imagecopyresampled() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

217
        imagecopyresampled($thumb, /** @scrutinizer ignore-type */ $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
Loading history...
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $dst_image of imagecopyresampled() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

217
        imagecopyresampled(/** @scrutinizer ignore-type */ $thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
Loading history...
218
        imagejpeg($thumb, "{$this->cachePath}/{$this->imageName}.jpg", $this->quality);
0 ignored issues
show
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $image of imagejpeg() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

218
        imagejpeg(/** @scrutinizer ignore-type */ $thumb, "{$this->cachePath}/{$this->imageName}.jpg", $this->quality);
Loading history...
219
220
        imagedestroy($thumb);
0 ignored issues
show
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $image of imagedestroy() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

220
        imagedestroy(/** @scrutinizer ignore-type */ $thumb);
Loading history...
221
        imagedestroy($source);
222
223
        if ($this->webP) {
224
            return $this->toWebP("{$this->cachePath}/{$this->imageName}.jpg");
225
        }
226
227
        return "{$this->cachePath}/{$this->imageName}.jpg";
228
    }
229
230
    /**
231
     * @param int $width
232
     * @param int $height
233
     * @param int $src_x
234
     * @param int $src_y
235
     * @param int $src_w
236
     * @param int $src_h
237
     * @return string
238
     */
239
    private function fromPng(int $width, int $height, int $src_x, int $src_y, int $src_w, int $src_h): string
240
    {
241
        $thumb = imagecreatetruecolor($width, $height);
242
        $source = imagecreatefrompng($this->imagePath);
243
244
        imagealphablending($thumb, false);
0 ignored issues
show
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $image of imagealphablending() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

244
        imagealphablending(/** @scrutinizer ignore-type */ $thumb, false);
Loading history...
245
        imagesavealpha($thumb, true);
0 ignored issues
show
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $image of imagesavealpha() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

245
        imagesavealpha(/** @scrutinizer ignore-type */ $thumb, true);
Loading history...
246
        imagecopyresampled($thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
0 ignored issues
show
Bug introduced by
It seems like $source can also be of type false; however, parameter $src_image of imagecopyresampled() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

246
        imagecopyresampled($thumb, /** @scrutinizer ignore-type */ $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
Loading history...
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $dst_image of imagecopyresampled() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

246
        imagecopyresampled(/** @scrutinizer ignore-type */ $thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
Loading history...
247
        imagepng($thumb, "{$this->cachePath}/{$this->imageName}.png", $this->compressor);
0 ignored issues
show
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $image of imagepng() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

247
        imagepng(/** @scrutinizer ignore-type */ $thumb, "{$this->cachePath}/{$this->imageName}.png", $this->compressor);
Loading history...
248
249
        imagedestroy($thumb);
0 ignored issues
show
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $image of imagedestroy() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

249
        imagedestroy(/** @scrutinizer ignore-type */ $thumb);
Loading history...
250
        imagedestroy($source);
251
252
        if ($this->webP) {
253
            return $this->toWebP("{$this->cachePath}/{$this->imageName}.png");
254
        }
255
256
        return "{$this->cachePath}/{$this->imageName}.png";
257
    }
258
259
    public function toWebP($image): string
260
    {
261
        try {
262
            $webPConverted = pathinfo($image)["dirname"] . "/" . pathinfo($image)["filename"] . ".webp";
263
            WebPConvert::convert($image, $webPConverted, ["default-quality" => $this->quality]);
264
            unlink($image);
265
            return $webPConverted;
266
        } catch (ConversionFailedException $exception) {
267
            return $image;
268
        }
269
    }
270
}
271