Cacher::getCachedImagePathName()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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 = [Format::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(), [Format::GIF, Format::PNG]);
148
    }
149
150
    protected function getImageResource(Image $image)
151
    {
152
        return Manipulator::create($image->getOutputFormat(), $image->getOriginalFullPath());
153
    }
154
155
    protected function getCutEdges(Image $image, int $width, int $height): array
156
    {
157
        $aspectRatio = $width / $height;
158
159
        $cutEdgeWidth = round($image->getHeight() * $aspectRatio);
160
161
        if ($cutEdgeWidth > $image->getWidth()) {
162
            $cutEdgeWidth = $image->getWidth();
163
        }
164
165
        $cutEdgeHeight = round($cutEdgeWidth / $aspectRatio);
166
167
        return [$cutEdgeWidth, $cutEdgeHeight];
168
    }
169
170
    protected function saveImage(Image $image, $layout, $width, $height): string
171
    {
172
        $this->createCacheDirectoryIfNotExists($image, $width, $height);
173
174
        return Manipulator::save($image->getOutputFormat(), $layout, $this->getCachedImageFullName($image, $width, $height));
175
    }
176
177
    protected function createCacheDirectoryIfNotExists(Image $image, $width, $height): void
178
    {
179
        $cachePath = "{$this->cacheRootPath}/{$this->cachePath}/{$this->getCacheImagePath($image->getPath(), $width, $height)}";
180
181
        if (! in_array(substr($cachePath, 0, 1), ['', '/'])) {
182
            $cachePath = "/{$cachePath}";
183
        }
184
185
        if (! file_exists($cachePath)) {
186
            mkdir($cachePath, 0777, true);
187
        }
188
    }
189
}
190