Completed
Push — master ( 23a2a1...1bd7cb )
by David
12s queued 10s
created

Cacher::setOutputFormat()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.9332
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
namespace GNAHotelSolutions\ImageCacher;
4
5
use Exception;
6
7
class Cacher
8
{
9
    /** @var string  */
10
    protected $cachePath;
11
12
    /** @var string  */
13
    protected $cacheRootPath;
14
15
    /** @var string */
16
    protected $imagesRootPath;
17
18
    /** @var string */
19
    protected $outputFormat = null;
20
21
    const SUPPORTED_OUTPUT_FORMATS = ['webp'];
22
23
    public function __construct(
24
        string $cachePath = 'cache/images',
25
        string $cacheRootPath = '',
26
        string $imagesRootPath = '',
27
        ?string $outputFormat = null
28
    ) {
29
        $this->cachePath = $cachePath;
30
        $this->cacheRootPath = rtrim($cacheRootPath, '/');
31
        $this->imagesRootPath = rtrim($imagesRootPath, '/');
32
        $this->outputFormat = $outputFormat;
33
    }
34
35
    public function setOutputFormat(string $format): self
36
    {
37
        if (! in_array($format, self::SUPPORTED_OUTPUT_FORMATS)) {
38
            throw new Exception("Cannot transform files into `{$format}` because is not a supported format.");
39
        }
40
41
        $this->outputFormat = $format;
42
43
        return $this;
44
    }
45
46
    public function resize($image, $width = null, $height = null): Image
47
    {
48
        return $this->manipulate($image, $width, $height, false);
49
    }
50
51
    public function crop($image, $width = null, $height = null): Image
52
    {
53
        return $this->manipulate($image, $width, $height, true);
54
    }
55
56
    protected function manipulate($image, $width = null, $height = null, bool $cropImage = false): Image
57
    {
58
        if (is_string($image)) {
59
            $image = new Image($image, $this->imagesRootPath);
60
        }
61
62
        if ($this->isSmallerThanRequested($image, $width, $height)) {
63
            return $image;
64
        }
65
66
        $resizedWidth = $width ?? round($height * $image->getAspectRatio());
67
        $resizedHeight = $height ?? round($width / $image->getAspectRatio());
68
69
        if ($this->outputFormat !== null && $this->outputFormat !== $image->getOutputFormat()) {
70
            $image->setOutputFormat($this->outputFormat);
71
        }
72
73
        if ($this->isAlreadyCached($image, $resizedWidth, $resizedHeight)) {
74
            return new Image($this->getCachedImagePathName($image, $resizedWidth, $resizedHeight), $this->cacheRootPath);
75
        }
76
77
        $layout = imagecreatetruecolor($resizedWidth, $resizedHeight);
78
79
        if ($this->isAlpha($image)) {
80
            imagealphablending($layout, false);
81
            imagesavealpha($layout, true);
82
        }
83
84
        if ($cropImage) {
85
            [$cutWidth, $cutHeight] = $this->getCutEdges($image, $resizedWidth, $resizedHeight);
0 ignored issues
show
Bug introduced by
The variable $cutWidth seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
Bug introduced by
The variable $cutHeight seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
86
            $cutX = ($image->getWidth() - $cutWidth) / 2;
0 ignored issues
show
Bug introduced by
The variable $cutWidth seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
87
            $cutY = ($image->getHeight() - $cutHeight) / 2;
0 ignored issues
show
Bug introduced by
The variable $cutHeight seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
88
        } else {
89
            $cutWidth = $image->getWidth();
90
            $cutHeight = $image->getHeight();
91
            $cutX = 0;
92
            $cutY = 0;
93
        }
94
95
        imagecopyresampled($layout, $this->getImageResource($image), 0, 0, $cutX, $cutY, $resizedWidth, $resizedHeight, $cutWidth, $cutHeight);
0 ignored issues
show
Bug introduced by
The variable $cutWidth does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $cutHeight does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
96
97
        $this->saveImage($image, $layout, $resizedWidth, $resizedHeight);
98
99
        return new Image($this->getCachedImagePathName($image, $resizedWidth, $resizedHeight), $this->cacheRootPath);
100
    }
101
102
    protected function isSmallerThanRequested(Image $image, $width, $height): bool
103
    {
104
        return (! $width && ! $height) || $image->isSmallerThan($width, $height);
105
    }
106
107
    protected function isAlreadyCached(Image $image, $width, $height): bool
108
    {
109
        return file_exists($this->getCachedImageFullName($image, $width, $height))
110
            && $this->cachedImageIsTheSame($image, $width, $height);
111
    }
112
113
    protected function cachedImageIsTheSame(Image $image, $width, $height): bool
114
    {
115
        $cachedImageUpdatedAt = filemtime($this->getCachedImageFullName($image, $width, $height));
116
        $imageUpdatedAt = filemtime($image->getOriginalFullPath());
117
118
        return $cachedImageUpdatedAt >= $imageUpdatedAt;
119
    }
120
121
    protected function getCachedImageFullName(Image $image, $width, $height): string
122
    {
123
        if ($this->cacheRootPath === '') {
124
            return $this->getCachedImagePathName($image, $width, $height);
125
        }
126
127
        return "{$this->cacheRootPath}/{$this->getCachedImagePathName($image, $width, $height)}";
128
    }
129
130
    protected function getCachedImagePathName(Image $image, $width, $height): string
131
    {
132
        return "{$this->cachePath}/{$this->getCachedImageName($image, $width, $height)}";
133
    }
134
135
    protected function getCachedImageName(Image $image, $width, $height): string
136
    {
137
        return "{$this->getCacheImagePath($image->getPath(), $width, $height)}/{$image->getName()}";
138
    }
139
140
    protected function getCacheImagePath(string $path, $width, $height): string
141
    {
142
        return ltrim("{$path}/{$width}x{$height}", '/');
143
    }
144
145
    protected function isAlpha(Image $image): bool
146
    {
147
        return in_array($image->getType(), ['gif', 'png']);
148
    }
149
150
    protected function getImageResource(Image $image)
151
    {
152
        if ($image->getOutputFormat() === 'jpeg') {
153
            return imagecreatefromjpeg($image->getOriginalFullPath());
154
        }
155
156
        if ($image->getOutputFormat() === 'png') {
157
            return imagecreatefrompng($image->getOriginalFullPath());
158
        }
159
160
        if ($image->getOutputFormat() === 'gif') {
161
            return imagecreatefromgif($image->getOriginalFullPath());
162
        }
163
164
        if ($image->getOutputFormat() === 'webp') {
165
            return imagecreatefromwebp($image->getOriginalFullPath());
166
        }
167
168
        throw new \Exception("Image type [{$image->getOutputFormat()}] not supported.");
169
    }
170
171
    protected function getCutEdges(Image $image, int $width, int $height): array
172
    {
173
        $aspectRatio = $width / $height;
174
175
        $cutEdgeWidth = round($image->getHeight() * $aspectRatio);
176
177
        if ($cutEdgeWidth > $image->getWidth()) {
178
            $cutEdgeWidth = $image->getWidth();
179
        }
180
181
        $cutEdgeHeight = round($cutEdgeWidth / $aspectRatio);
182
183
        return [$cutEdgeWidth, $cutEdgeHeight];
184
    }
185
186
    protected function saveImage(Image $image, $layout, $width, $height): string
187
    {
188
        $this->createCacheDirectoryIfNotExists($image, $width, $height);
189
190
        if ($image->getOutputFormat() === 'jpeg') {
191
            return imagejpeg($layout, $this->getCachedImageFullName($image, $width, $height));
192
        }
193
194
        if ($image->getOutputFormat() === 'png') {
195
            return imagepng($layout, $this->getCachedImageFullName($image, $width, $height));
196
        }
197
198
        if ($image->getOutputFormat() === 'gif') {
199
            return imagegif($layout, $this->getCachedImageFullName($image, $width, $height));
200
        }
201
202
        if ($image->getOutputFormat() === 'webp') {
203
            return imagewebp($layout, $this->getCachedImageFullName($image, $width, $height));
204
        }
205
206
        throw new \Exception("Image type [{$image->getOutputFormat()}] not supported.");
207
    }
208
209
    protected function createCacheDirectoryIfNotExists(Image $image, $width, $height): void
210
    {
211
        $cachePath = "{$this->cacheRootPath}/{$this->cachePath}/{$this->getCacheImagePath($image->getPath(), $width, $height)}";
212
213
        if (! in_array(substr($cachePath, 0, 1), ['', '/'])) {
214
            $cachePath = "/{$cachePath}";
215
        }
216
217
        if (! file_exists($cachePath)) {
218
            mkdir($cachePath, 0777, true);
219
        }
220
    }
221
}
222