Passed
Push — master ( b18bc3...b415dd )
by Robson
01:53
created

Cropper   A

Complexity

Total Complexity 28

Size/Duplication

Total Lines 213
Duplicated Lines 0 %

Importance

Changes 11
Bugs 0 Features 0
Metric Value
eloc 80
c 11
b 0
f 0
dl 0
loc 213
rs 10
wmc 28

8 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 4
A fromJpg() 0 11 1
A name() 0 13 3
A fromPng() 0 14 1
A make() 0 20 5
A flush() 0 11 6
A imageCache() 0 33 5
A imageDestroy() 0 4 3
1
<?php
2
3
namespace CoffeeCode\Cropper;
4
5
/**
6
 * Class CoffeeCode Cropper
7
 *
8
 * @author Robson V. Leite <https://github.com/robsonvleite>
9
 * @package CoffeeCode\Cropper
10
 */
11
class Cropper
12
{
13
    /** @var string */
14
    private $cachePath;
15
16
    /** @var array */
17
    private $cacheSize;
18
19
    /** @var string */
20
    private $imagePath;
21
22
    /** @var string */
23
    private $imageName;
24
25
    /** @var string */
26
    private $imageMime;
27
28
    /** @var string */
29
    private $imageInfo;
30
31
    /**
32
     * Allow jpg and png to thumb and cache generate
33
     *
34
     * @var array allowed media types
35
     */
36
    private static $allowedExt = ['image/jpeg', "image/png"];
37
38
    /**
39
     * Cropper constructor.
40
     *
41
     * @param string $cachePath
42
     * @param int $jpgQuality
43
     * @param int $pngCompressor
44
     * @throws \Exception
45
     */
46
    public function __construct(string $cachePath, int $jpgQuality = 75, int $pngCompressor = 5)
47
    {
48
        $this->cachePath = $cachePath;
49
        $this->cacheSize = [$jpgQuality, $pngCompressor];
50
51
        if (!file_exists($this->cachePath) || !is_dir($this->cachePath)) {
52
            if (!mkdir($this->cachePath, 0755)) {
53
                throw new \Exception("Could not create cache folder");
54
            }
55
        }
56
    }
57
58
    /**
59
     * Make an thumb image
60
     *
61
     * @param string $imagePath
62
     * @param int $width
63
     * @param int|null $height
64
     * @return null|string
65
     */
66
    public function make(string $imagePath, int $width, int $height = null): ?string
67
    {
68
        if (!file_exists($imagePath)) {
69
            return "Image not found";
70
        }
71
72
        $this->imagePath = $imagePath;
73
        $this->imageMime = mime_content_type($this->imagePath);
74
        $this->imageInfo = pathinfo($this->imagePath);
75
76
        if (!in_array($this->imageMime, self::$allowedExt)) {
77
            return "Not a valid JPG or PNG image";
78
        }
79
80
        $this->imageName = $this->name($this->imagePath, $width, $height);
81
        if (file_exists("{$this->cachePath}/{$this->imageName}") && is_file("{$this->cachePath}/{$this->imageName}")) {
82
            return "{$this->cachePath}/{$this->imageName}";
83
        }
84
85
        return $this->imageCache($width, $height);
86
    }
87
88
    /**
89
     * @param string $name
90
     * @return string
91
     */
92
    protected function name(string $name, int $width, int $height = null): string
93
    {
94
        $name = filter_var(mb_strtolower($name), FILTER_SANITIZE_STRIPPED);
95
        $formats = 'ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜüÝÞßàáâãäåæçèéêëìíîïðñòóôõöøùúûýýþÿRr"!@#$%&*()_-+={[}]/?;:.,\\\'<>°ºª';
96
        $replace = 'aaaaaaaceeeeiiiidnoooooouuuuuybsaaaaaaaceeeeiiiidnoooooouuuyybyRr                                 ';
97
        $named = substr($name, 0, strrpos($name, "."));
98
        $name = str_replace(["-----", "----", "---", "--"], "-",
99
            str_replace(" ", "-", trim(strtr(utf8_decode($named), utf8_decode($formats), $replace))));
100
101
        $ext = ($this->imageMime == "image/jpeg" ? ".jpg" : ".png");
102
        $heightName = ($height ? "h{$height}" : "");
103
104
        return "{$name}-w{$width}{$heightName}.{$ext}";
105
    }
106
107
    /**
108
     * Clear cache
109
     *
110
     * @param string|null $imageName
111
     * @example $t->flush("images/image.jpg"); clear image name and variations size
112
     * @example $t->flush(); clear all image cache folder
113
     */
114
    public function flush(string $imageName = null): void
115
    {
116
        $scan = scandir($this->cachePath);
117
        $name = ($imageName ? hash("crc32", pathinfo($imageName)['basename']) : null);
118
119
        foreach ($scan as $file) {
120
            $file = "{$this->cachePath}/{$file}";
121
            if ($imageName && strpos($file, $name)) {
122
                $this->imageDestroy($file);
123
            } elseif (!$imageName) {
124
                $this->imageDestroy($file);
125
            }
126
        }
127
    }
128
129
    /**
130
     * @param int $width
131
     * @param int|null $height
132
     * @return null|string
133
     */
134
    private function imageCache(int $width, int $height = null): ?string
135
    {
136
        list($src_w, $src_h) = getimagesize($this->imagePath);
137
        $height = ($height ?? ($width * $src_h) / $src_w);
138
139
        $src_x = 0;
140
        $src_y = 0;
141
142
        $cmp_x = $src_w / $width;
143
        $cmp_y = $src_h / $height;
144
145
        if ($cmp_x > $cmp_y) {
146
            $src_w = round($src_w / $cmp_x * $cmp_y);
147
            $src_x = round(($src_w - ($src_w / $cmp_x * $cmp_y))); //2
148
        } elseif ($cmp_y > $cmp_x) {
149
            $src_h = round($src_h / $cmp_y * $cmp_x);
150
            $src_y = round(($src_h - ($src_h / $cmp_y * $cmp_x))); //2
151
        }
152
153
        $src_x = (int)$src_x;
154
        $src_h = (int)$src_h;
155
        $src_y = (int)$src_y;
156
        $src_y = (int)$src_y;
157
158
        if ($this->imageMime == "image/jpeg") {
159
            return $this->fromJpg($width, $height, $src_x, $src_y, $src_w, $src_h);
160
        }
161
162
        if ($this->imageMime == "image/png") {
163
            return $this->fromPng($width, $height, $src_x, $src_y, $src_w, $src_h);
164
        }
165
166
        return null;
167
    }
168
169
    /**
170
     * @param string $imagePatch
171
     */
172
    private function imageDestroy(string $imagePatch): void
173
    {
174
        if (file_exists($imagePatch) && is_file($imagePatch)) {
175
            unlink($imagePatch);
176
        }
177
    }
178
179
    /**
180
     * @param int $width
181
     * @param int $height
182
     * @param int $src_x
183
     * @param int $src_y
184
     * @param int $src_w
185
     * @param int $src_h
186
     * @return string
187
     */
188
    private function fromJpg(int $width, int $height, int $src_x, int $src_y, int $src_w, int $src_h): string
189
    {
190
        $thumb = imagecreatetruecolor($width, $height);
191
        $source = imagecreatefromjpeg($this->imagePath);
192
        imagecopyresized($thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
0 ignored issues
show
Bug introduced by
It seems like $thumb can also be of type false; however, parameter $dst_image of imagecopyresized() 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

192
        imagecopyresized(/** @scrutinizer ignore-type */ $thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
Loading history...
Bug introduced by
It seems like $source can also be of type false; however, parameter $src_image of imagecopyresized() 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

192
        imagecopyresized($thumb, /** @scrutinizer ignore-type */ $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
Loading history...
193
        imagejpeg($thumb, "{$this->cachePath}/{$this->imageName}", $this->cacheSize[0]);
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

193
        imagejpeg(/** @scrutinizer ignore-type */ $thumb, "{$this->cachePath}/{$this->imageName}", $this->cacheSize[0]);
Loading history...
194
195
        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

195
        imagedestroy(/** @scrutinizer ignore-type */ $thumb);
Loading history...
196
        imagedestroy($source);
197
198
        return "{$this->cachePath}/{$this->imageName}";
199
    }
200
201
    /**
202
     * @param int $width
203
     * @param int $height
204
     * @param int $src_x
205
     * @param int $src_y
206
     * @param int $src_w
207
     * @param int $src_h
208
     * @return string
209
     */
210
    private function fromPng(int $width, int $height, int $src_x, int $src_y, int $src_w, int $src_h): string
211
    {
212
        $thumb = imagecreatetruecolor($width, $height);
213
        $source = imagecreatefrompng($this->imagePath);
214
215
        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

215
        imagealphablending(/** @scrutinizer ignore-type */ $thumb, false);
Loading history...
216
        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

216
        imagesavealpha(/** @scrutinizer ignore-type */ $thumb, true);
Loading history...
217
        imagecopyresized($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 imagecopyresized() 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
        imagecopyresized($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 imagecopyresized() 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
        imagecopyresized(/** @scrutinizer ignore-type */ $thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
Loading history...
218
        imagepng($thumb, "{$this->cachePath}/{$this->imageName}", $this->cacheSize[1]);
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

218
        imagepng(/** @scrutinizer ignore-type */ $thumb, "{$this->cachePath}/{$this->imageName}", $this->cacheSize[1]);
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
        return "{$this->cachePath}/{$this->imageName}";
224
    }
225
}