Passed
Push — master ( 9f4f64...753522 )
by Robson
01:42
created

Cropper::imageCache()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 33
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 21
nc 9
nop 2
dl 0
loc 33
rs 9.2728
c 0
b 0
f 0
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
        $this->imageName = hash("crc32", $this->imageInfo['basename']) . hash("crc32",
76
                "{$width}{$height}") . ($this->imageMime == "image/jpeg" ? ".jpg" : ".png");
77
78
        if (!in_array($this->imageMime, self::$allowedExt)) {
79
            return "Not a valid JPG or PNG image";
80
        }
81
82
        if (file_exists("{$this->cachePath}/{$this->imageName}") && is_file("{$this->cachePath}/{$this->imageName}")) {
83
            return "{$this->cachePath}/{$this->imageName}";
84
        }
85
86
        return $this->imageCache($width, $height);
87
    }
88
89
    /**
90
     * Clear cache
91
     *
92
     * @param string|null $imageName
93
     * @example $t->flush("images/image.jpg"); clear image name and variations size
94
     * @example $t->flush(); clear all image cache folder
95
     */
96
    public function flush(string $imageName = null): void
97
    {
98
        $scan = scandir($this->cachePath);
99
        $name = ($imageName ? hash("crc32", pathinfo($imageName)['basename']) : null);
100
101
        foreach ($scan as $file) {
102
            $file = "{$this->cachePath}/{$file}";
103
            if ($imageName && strpos($file, $name) && is_file($file)) {
104
                unlink($file);
105
            }
106
107
            if (!$name && is_file($file)) {
108
                unlink($file);
109
            }
110
        }
111
    }
112
113
    /**
114
     * @param int $width
115
     * @param int|null $height
116
     * @return null|string
117
     */
118
    private function imageCache(int $width, int $height = null): ?string
119
    {
120
        list($src_w, $src_h) = getimagesize($this->imagePath);
121
        $height = ($height ?? ($width * $src_h) / $src_w);
122
123
        $src_x = 0;
124
        $src_y = 0;
125
126
        $cmp_x = $src_w / $width;
127
        $cmp_y = $src_h / $height;
128
129
        if ($cmp_x > $cmp_y) {
130
            $src_w = round($src_w / $cmp_x * $cmp_y);
131
            $src_x = round(($src_w - ($src_w / $cmp_x * $cmp_y))); //2
132
        } elseif ($cmp_y > $cmp_x) {
133
            $src_h = round($src_h / $cmp_y * $cmp_x);
134
            $src_y = round(($src_h - ($src_h / $cmp_y * $cmp_x))); //2
135
        }
136
137
        $src_x = (int)$src_x;
138
        $src_h = (int)$src_h;
139
        $src_y = (int)$src_y;
140
        $src_y = (int)$src_y;
141
142
        if ($this->imageMime == "image/jpeg") {
143
            return $this->fromJpg($width, $height, $src_x, $src_y, $src_w, $src_h);
144
        }
145
146
        if ($this->imageMime == "image/png") {
147
            return $this->fromPng($width, $height, $src_x, $src_y, $src_w, $src_h);
148
        }
149
150
        return null;
151
    }
152
153
    /**
154
     * @param int $width
155
     * @param int $height
156
     * @param int $src_x
157
     * @param int $src_y
158
     * @param int $src_w
159
     * @param int $src_h
160
     * @return string
161
     */
162
    private function fromJpg(int $width, int $height, int $src_x, int $src_y, int $src_w, int $src_h): string
163
    {
164
        $thumb = imagecreatetruecolor($width, $height);
165
        $source = imagecreatefromjpeg($this->imagePath);
166
        imagecopyresized($thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
167
        imagejpeg($thumb, "{$this->cachePath}/{$this->imageName}", $this->cacheSize[0]);
168
169
        imagedestroy($thumb);
170
        imagedestroy($source);
171
172
        return "{$this->cachePath}/{$this->imageName}";
173
    }
174
175
    /**
176
     * @param int $width
177
     * @param int $height
178
     * @param int $src_x
179
     * @param int $src_y
180
     * @param int $src_w
181
     * @param int $src_h
182
     * @return string
183
     */
184
    private function fromPng(int $width, int $height, int $src_x, int $src_y, int $src_w, int $src_h): string
185
    {
186
        $thumb = imagecreatetruecolor($width, $height);
187
        $source = imagecreatefrompng($this->imagePath);
188
189
        imagealphablending($thumb, false);
190
        imagesavealpha($thumb, true);
191
        imagecopyresized($thumb, $source, 0, 0, $src_x, $src_y, $width, $height, $src_w, $src_h);
192
        imagepng($thumb, "{$this->cachePath}/{$this->imageName}", $this->cacheSize[1]);
193
194
        imagedestroy($thumb);
195
        imagedestroy($source);
196
197
        return "{$this->cachePath}/{$this->imageName}";
198
    }
199
}