Completed
Push — master ( 1c5194...810b06 )
by David
01:13
created

Cacher   A

Complexity

Total Complexity 34

Size/Duplication

Total Lines 182
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 34
lcom 1
cbo 1
dl 0
loc 182
rs 9.68
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A resize() 0 4 1
A crop() 0 4 1
B manipulate() 0 41 6
A isSmallerThanRequested() 0 4 3
A isAlreadyCached() 0 5 2
A cachedImageIsTheSame() 0 7 1
A getCachedImageFullName() 0 8 2
A getCachedImagePathName() 0 4 1
A getCachedImageName() 0 4 1
A getCacheImagePath() 0 4 1
A isAlpha() 0 4 1
A getImageResource() 0 16 4
A getCutEdges() 0 14 2
A saveImage() 0 18 4
A createCacheDirectoryIfNotExists() 0 12 3
1
<?php
2
3
namespace GNAHotelSolutions\ImageCacher;
4
5
class Cacher
6
{
7
    /** @var string  */
8
    protected $cachePath;
9
    
10
    /** @var string  */
11
    protected $cacheRootPath;
12
13
    /** @var string */
14
    protected $imagesRootPath;
15
16
    public function __construct(string $cachePath = 'cache/images', string $cacheRootPath = '', string $imagesRootPath = '')
17
    {
18
        $this->cachePath = $cachePath;
19
        $this->cacheRootPath = rtrim($cacheRootPath, '/');
20
        $this->imagesRootPath = rtrim($imagesRootPath, '/');
21
    }
22
23
    public function resize($image, $width = null, $height = null): Image
24
    {
25
        return $this->manipulate($image, $width, $height, false);
26
    }
27
28
    public function crop($image, $width = null, $height = null): Image
29
    {
30
        return $this->manipulate($image, $width, $height, true);
31
    }
32
33
    protected function manipulate($image, $width = null, $height = null, bool $cropImage = false): Image
34
    {
35
        if (is_string($image)) {
36
            $image = new Image($image, $this->imagesRootPath);
37
        }
38
39
        if ($this->isSmallerThanRequested($image, $width, $height)) {
40
            return $image;
41
        }
42
43
        $resizedWidth = $width ?? round($height * $image->getAspectRatio());
44
        $resizedHeight = $height ?? round($width / $image->getAspectRatio());
45
46
        if ($this->isAlreadyCached($image, $resizedWidth, $resizedHeight)) {
47
            return new Image($this->getCachedImagePathName($image, $resizedWidth, $resizedHeight), $this->cacheRootPath);
48
        }
49
50
        $layout = imagecreatetruecolor($resizedWidth, $resizedHeight);
51
52
        if ($this->isAlpha($image)) {
53
            imagealphablending($layout, false);
54
            imagesavealpha($layout, true);
55
        }
56
57
        if ($cropImage) {
58
            [$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...
59
            $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...
60
            $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...
61
        } else {
62
            $cutWidth = $image->getWidth();
63
            $cutHeight = $image->getHeight();
64
            $cutX = 0;
65
            $cutY = 0;
66
        }
67
68
        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...
69
70
        $this->saveImage($image, $layout, $resizedWidth, $resizedHeight);
71
72
        return new Image($this->getCachedImagePathName($image, $resizedWidth, $resizedHeight), $this->cacheRootPath);
73
    }
74
75
    protected function isSmallerThanRequested(Image $image, $width, $height): bool
76
    {
77
        return (! $width && ! $height) || $image->isSmallerThan($width, $height);
78
    }
79
80
    protected function isAlreadyCached(Image $image, $width, $height): bool
81
    {
82
        return file_exists($this->getCachedImageFullName($image, $width, $height)) 
83
            && $this->cachedImageIsTheSame($image, $width, $height);
84
    }
85
86
    protected function cachedImageIsTheSame(Image $image, $width, $height): bool
87
    {
88
        $cachedImageUpdatedAt = filemtime($this->getCachedImageFullName($image, $width, $height));
89
        $imageUpdatedAt = filemtime($image->getOriginalFullPath());
90
        
91
        return $cachedImageUpdatedAt >= $imageUpdatedAt;
92
    }
93
94
    protected function getCachedImageFullName(Image $image, $width, $height): string
95
    {
96
        if ($this->cacheRootPath === '') {
97
            return $this->getCachedImagePathName($image, $width, $height);
98
        }
99
100
        return "{$this->cacheRootPath}/{$this->getCachedImagePathName($image, $width, $height)}";
101
    }
102
103
    protected function getCachedImagePathName(Image $image, $width, $height): string
104
    {
105
        return "{$this->cachePath}/{$this->getCachedImageName($image, $width, $height)}";
106
    }
107
108
    protected function getCachedImageName(Image $image, $width, $height): string
109
    {
110
        return "{$this->getCacheImagePath($image->getPath(), $width, $height)}/{$image->getName()}";
111
    }
112
113
    protected function getCacheImagePath(string $path, $width, $height): string
114
    {
115
        return ltrim("{$path}/{$width}x{$height}", '/');
116
    }
117
118
    protected function isAlpha(Image $image): bool
119
    {
120
        return in_array($image->getType(), ['gif', 'png']);
121
    }
122
123
    protected function getImageResource(Image $image)
124
    {
125
        if ($image->getType() === 'jpeg') {
126
            return imagecreatefromjpeg($image->getOriginalFullPath());
127
        }
128
129
        if ($image->getType() === 'png') {
130
            return imagecreatefrompng($image->getOriginalFullPath());
131
        }
132
133
        if ($image->getType() === 'gif') {
134
            return imagecreatefromgif($image->getOriginalFullPath());
135
        }
136
137
        throw new \Exception("Image type [{$image->getType()}] not supported.");
138
    }
139
140
    protected function getCutEdges(Image $image, int $width, int $height): array
141
    {
142
        $aspectRatio = $width / $height;
143
144
        $cutEdgeWidth = round($image->getHeight() * $aspectRatio);
145
146
        if ($cutEdgeWidth > $image->getWidth()) {
147
            $cutEdgeWidth = $image->getWidth();
148
        }
149
150
        $cutEdgeHeight = round($cutEdgeWidth / $aspectRatio);
151
152
        return [$cutEdgeWidth, $cutEdgeHeight];
153
    }
154
155
    protected function saveImage(Image $image, $layout, $width, $height): string
156
    {
157
        $this->createCacheDirectoryIfNotExists($image, $width, $height);
158
159
        if ($image->getType() === 'jpeg') {
160
            return imagejpeg($layout, $this->getCachedImageFullName($image, $width, $height));
161
        }
162
163
        if ($image->getType() === 'png') {
164
            return imagepng($layout, $this->getCachedImageFullName($image, $width, $height));
165
        }
166
167
        if ($image->getType() === 'gif') {
168
            return imagegif($layout, $this->getCachedImageFullName($image, $width, $height));
169
        }
170
171
        throw new \Exception("Image type [{$image->getType()}] not supported.");
172
    }
173
174
    protected function createCacheDirectoryIfNotExists(Image $image, $width, $height): void
175
    {
176
        $cachePath = "{$this->cacheRootPath}/{$this->cachePath}/{$this->getCacheImagePath($image->getPath(), $width, $height)}";
177
178
        if (substr($cachePath, 0, 1) !== '') {
179
            $cachePath = "/{$cachePath}";
180
        }
181
182
        if (! file_exists($cachePath)) {
183
            mkdir($cachePath, 0777, true);
184
        }
185
    }
186
}
187