Passed
Push — develop ( a3b096...881135 )
by Andrew
03:46
created

ThumborImageTransform::displayName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * ImageOptimize plugin for Craft CMS 3.x
4
 *
5
 * Automatically optimize images after they've been transformed
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2017 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\imageoptimize\imagetransforms;
12
13
use nystudio107\imageoptimize\ImageOptimize;
14
15
use craft\elements\Asset;
16
use craft\models\AssetTransform;
17
use Thumbor\Url\Builder as UrlBuilder;
18
19
use Craft;
20
21
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
22
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 2 spaces but found 4
Loading history...
23
 * @package   ImageOptimize
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
24
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 3 spaces but found 5
Loading history...
25
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
26
class ThumborImageTransform extends ImageTransform
27
{
28
    // Static Methods
29
    // =========================================================================
30
31
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
32
     * @inheritdoc
33
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
34
    public static function displayName(): string
35
    {
36
        return Craft::t('image-optimize', 'Thumbor');
37
    }
38
39
    // Public Methods
40
    // =========================================================================
41
42
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
43
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
44
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
45
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
46
     *
47
     * @return string|null
48
     * @throws \yii\base\Exception
49
     * @throws \yii\base\InvalidConfigException
50
     */
51
    public function getTransformUrl(Asset $asset, $transform, array $params = [])
52
    {
53
        return (string)$this->getUrlBuilderForTransform($asset, $transform, $params);
54
    }
55
56
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
57
     * @param string              $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
58
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
59
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
60
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
61
     *
62
     * @return string
63
     * @throws \yii\base\Exception
64
     * @throws \yii\base\InvalidConfigException
65
     */
66
    public function getWebPUrl(string $url, Asset $asset, $transform, array $params = []): string
67
    {
68
        $builder = $this->getUrlBuilderForTransform($asset, $transform, $params)
69
            ->addFilter('format', 'webp');
70
71
        return (string)$builder;
72
    }
73
74
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
75
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
76
     * @param array  $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
77
     *
78
     * @return bool
79
     */
80
    public function purgeUrl(string $url, array $params = []): bool
81
    {
82
        return false;
83
    }
84
85
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
86
     * @return array
87
     */
88
    public function getTransformParams(): array
89
    {
90
        $settings = ImageOptimize::$plugin->getSettings();
91
        $params = [
92
            'baseUrl' => $settings->thumborBaseUrl,
0 ignored issues
show
Bug Best Practice introduced by
The property thumborBaseUrl does not exist on nystudio107\imageoptimize\models\Settings. Since you implemented __get, consider adding a @property annotation.
Loading history...
93
            'securityKey' => $settings->thumborSecurityKey,
0 ignored issues
show
Bug Best Practice introduced by
The property thumborSecurityKey does not exist on nystudio107\imageoptimize\models\Settings. Since you implemented __get, consider adding a @property annotation.
Loading history...
94
        ];
95
96
        return $params;
97
    }
98
99
    // Private Methods
100
    // =========================================================================
101
102
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
103
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
104
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
105
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
106
     *
107
     * @return UrlBuilder
108
     * @throws \yii\base\Exception
109
     * @throws \yii\base\InvalidConfigException
110
     */
111
    private function getUrlBuilderForTransform(Asset $asset, $transform, array $params = []): UrlBuilder
0 ignored issues
show
Coding Style introduced by
Private method name "ThumborImageTransform::getUrlBuilderForTransform" must be prefixed with an underscore
Loading history...
112
    {
113
        $assetUri = $this->getAssetUri($asset);
114
        $baseUrl = $params['baseUrl'];
115
        $securityKey = $params['securityKey'] ?: null;
116
        $builder = UrlBuilder::construct($baseUrl, $securityKey, $assetUri);
117
        $settings = ImageOptimize::$plugin->getSettings();
118
119
        if ($transform->mode === 'fit') {
120
            // https://thumbor.readthedocs.io/en/latest/usage.html#fit-in
121
            $builder->fitIn($transform->width, $transform->height);
122
        } elseif ($transform->mode === 'stretch') {
123
            $builder
0 ignored issues
show
Bug introduced by
The call to Thumbor\Url\Builder::addFilter() has too few arguments starting with args. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

123
                ->/** @scrutinizer ignore-call */ addFilter('upscale');

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
124
                ->resize($transform->width, $transform->height)
125
                ->addFilter('upscale');
126
127
            // https://github.com/thumbor/thumbor/issues/1123
128
            Craft::warning('Thumbor has no equivalent to the "stretch" transform mode. The resulting image will be resized and cropped, but not stretched.', __METHOD__);
129
        } else {
130
131
            // https://thumbor.readthedocs.io/en/latest/usage.html#image-size
132
            $builder->resize($transform->width, $transform->height);
133
134
            if ($focalPoint = $this->getFocalPoint($asset)) {
135
                // https://thumbor.readthedocs.io/en/latest/focal.html
136
                $builder->addFilter('focal', $focalPoint);
137
            } elseif (preg_match('/(top|center|bottom)-(left|center|right)/', $transform->position, $matches)) {
138
                $v = str_replace('center', 'middle', $matches[1]);
139
                $h = $matches[2];
140
141
                // https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align
142
                $builder->valign($v)->halign($h);
143
            }
144
        }
145
146
        // https://thumbor.readthedocs.io/en/latest/format.html
147
        if ($format = $this->getFormat($transform)) {
148
            $builder->addFilter('format', $format);
149
        }
150
151
        // https://thumbor.readthedocs.io/en/latest/quality.html
152
        if ($quality = $this->getQuality($transform)) {
153
            $builder->addFilter('quality', $quality);
154
        }
155
156
        if (property_exists($transform, 'interlace')) {
157
            Craft::warning('Thumbor enables progressive JPEGs on the server-level, not as a request option. See https://thumbor.readthedocs.io/en/latest/jpegtran.html', __METHOD__);
158
        }
159
160
        if ($settings->autoSharpenScaledImages) {
161
            // See if the image has been scaled >= 50%
162
            $widthScale = $asset->getWidth() / ($transform->width ?? $asset->getWidth());
163
            $heightScale = $asset->getHeight() / ($transform->height ?? $asset->getHeight());
164
            if (($widthScale >= 2.0) || ($heightScale >= 2.0)) {
165
                // https://thumbor.readthedocs.io/en/latest/sharpen.html
166
                $builder->addFilter('sharpen', .5, .5, 'true');
0 ignored issues
show
Unused Code introduced by
The call to Thumbor\Url\Builder::addFilter() has too many arguments starting with 'true'. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

166
                $builder->/** @scrutinizer ignore-call */ 
167
                          addFilter('sharpen', .5, .5, 'true');

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
167
            }
168
        }
169
170
        return $builder;
171
    }
172
173
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $asset should have a doc-comment as per coding-style.
Loading history...
174
     * @return string|null
175
     */
176
    private function getFocalPoint(Asset $asset)
0 ignored issues
show
Coding Style introduced by
Private method name "ThumborImageTransform::getFocalPoint" must be prefixed with an underscore
Loading history...
177
    {
178
        $focalPoint = $asset->getFocalPoint();
179
180
        if (!$focalPoint) {
181
            return null;
182
        }
183
184
        $box = array_map('intval', [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
185
            'top' => $focalPoint['y'] * $asset->height - 1,
186
            'left' => $focalPoint['x'] * $asset->width - 1,
187
            'bottom' => $focalPoint['y'] * $asset->height + 1,
188
            'right' => $focalPoint['x'] * $asset->width + 1,
189
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
190
191
        return implode('', [
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
192
            $box['left'],
193
            'x',
194
            $box['top'],
195
            ':',
196
            $box['right'],
197
            'x',
198
            $box['bottom'],
199
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
200
    }
201
202
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
203
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
204
     *
205
     * @return string|null
206
     */
207
    private function getFormat($transform)
0 ignored issues
show
Coding Style introduced by
Private method name "ThumborImageTransform::getFormat" must be prefixed with an underscore
Loading history...
208
    {
209
        $format = str_replace('jpg', 'jpeg', $transform->format);
210
211
        return $format ?: null;
212
    }
213
214
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
215
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
216
     *
217
     * @return int
218
     */
219
    private function getQuality($transform)
0 ignored issues
show
Coding Style introduced by
Private method name "ThumborImageTransform::getQuality" must be prefixed with an underscore
Loading history...
220
    {
221
        return $transform->quality ?? Craft::$app->getConfig()->getGeneral()->defaultImageQuality;
222
    }
223
}
224