Passed
Push — v1 ( c358bf...fc3fe5 )
by Andrew
11:41 queued 04:25
created

ThumborImageTransform::getFormat()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 2
nc 1
nop 1
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 Properties
40
    // =========================================================================
41
42
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
43
     * @var string
44
     */
45
    public $baseUrl;
46
47
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
48
     * @var string
49
     */
50
    public $securityKey;
51
52
    // Public Methods
53
    // =========================================================================
54
55
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
56
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
57
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
58
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
59
     *
60
     * @return string|null
61
     * @throws \yii\base\Exception
62
     * @throws \yii\base\InvalidConfigException
63
     */
64
    public function getTransformUrl(Asset $asset, $transform, array $params = [])
65
    {
66
        return (string)$this->getUrlBuilderForTransform($asset, $transform, $params);
67
    }
68
69
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
70
     * @param string              $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
71
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
72
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
73
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
74
     *
75
     * @return string
76
     * @throws \yii\base\Exception
77
     * @throws \yii\base\InvalidConfigException
78
     */
79
    public function getWebPUrl(string $url, Asset $asset, $transform, array $params = []): string
80
    {
81
        $builder = $this->getUrlBuilderForTransform($asset, $transform, $params)
82
            ->addFilter('format', 'webp');
83
84
        return (string)$builder;
85
    }
86
87
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
88
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
89
     * @param array  $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
90
     *
91
     * @return bool
92
     */
93
    public function purgeUrl(string $url, array $params = []): bool
94
    {
95
        return false;
96
    }
97
98
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
99
     * @return array
100
     */
101
    public function getTransformParams(): array
102
    {
103
        $params = [
104
            'baseUrl' => $this->baseUrl,
105
            'securityKey' => $this->securityKey,
106
        ];
107
108
        return $params;
109
    }
110
111
    // Private Methods
112
    // =========================================================================
113
114
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
115
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
116
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
117
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
118
     *
119
     * @return UrlBuilder
120
     * @throws \yii\base\Exception
121
     * @throws \yii\base\InvalidConfigException
122
     */
123
    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...
124
    {
125
        $assetUri = $this->getAssetUri($asset);
126
        $baseUrl = $params['baseUrl'];
127
        $securityKey = $params['securityKey'] ?: null;
128
        $builder = UrlBuilder::construct($baseUrl, $securityKey, $assetUri);
129
        $settings = ImageOptimize::$plugin->getSettings();
130
131
        if ($transform->mode === 'fit') {
132
            // https://thumbor.readthedocs.io/en/latest/usage.html#fit-in
133
            $builder->fitIn($transform->width, $transform->height);
134
        } elseif ($transform->mode === 'stretch') {
135
            $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

135
                ->/** @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...
136
                ->resize($transform->width, $transform->height)
137
                ->addFilter('upscale');
138
139
            // https://github.com/thumbor/thumbor/issues/1123
140
            Craft::warning('Thumbor has no equivalent to the "stretch" transform mode. The resulting image will be resized and cropped, but not stretched.', __METHOD__);
141
        } else {
142
143
            // https://thumbor.readthedocs.io/en/latest/usage.html#image-size
144
            $builder->resize($transform->width, $transform->height);
145
146
            if ($focalPoint = $this->getFocalPoint($asset)) {
147
                // https://thumbor.readthedocs.io/en/latest/focal.html
148
                $builder->addFilter('focal', $focalPoint);
149
            } elseif (preg_match('/(top|center|bottom)-(left|center|right)/', $transform->position, $matches)) {
150
                $v = str_replace('center', 'middle', $matches[1]);
151
                $h = $matches[2];
152
153
                // https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align
154
                $builder->valign($v)->halign($h);
155
            }
156
        }
157
158
        // https://thumbor.readthedocs.io/en/latest/format.html
159
        if ($format = $this->getFormat($transform)) {
160
            $builder->addFilter('format', $format);
161
        }
162
163
        // https://thumbor.readthedocs.io/en/latest/quality.html
164
        if ($quality = $this->getQuality($transform)) {
165
            $builder->addFilter('quality', $quality);
166
        }
167
168
        if (property_exists($transform, 'interlace')) {
169
            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__);
170
        }
171
172
        if ($settings->autoSharpenScaledImages) {
173
            // See if the image has been scaled >= 50%
174
            $widthScale = $asset->getWidth() / ($transform->width ?? $asset->getWidth());
175
            $heightScale = $asset->getHeight() / ($transform->height ?? $asset->getHeight());
176
            if (($widthScale >= 2.0) || ($heightScale >= 2.0)) {
177
                // https://thumbor.readthedocs.io/en/latest/sharpen.html
178
                $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

178
                $builder->/** @scrutinizer ignore-call */ 
179
                          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...
179
            }
180
        }
181
182
        return $builder;
183
    }
184
185
    /**
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...
186
     * @return string|null
187
     */
188
    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...
189
    {
190
        $focalPoint = $asset->getFocalPoint();
191
192
        if (!$focalPoint) {
193
            return null;
194
        }
195
196
        $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...
197
            'top' => $focalPoint['y'] * $asset->height - 1,
198
            'left' => $focalPoint['x'] * $asset->width - 1,
199
            'bottom' => $focalPoint['y'] * $asset->height + 1,
200
            'right' => $focalPoint['x'] * $asset->width + 1,
201
        ]);
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...
202
203
        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...
204
            $box['left'],
205
            'x',
206
            $box['top'],
207
            ':',
208
            $box['right'],
209
            'x',
210
            $box['bottom'],
211
        ]);
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...
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 string|null
218
     */
219
    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...
220
    {
221
        $format = str_replace('jpg', 'jpeg', $transform->format);
222
223
        return $format ?: null;
224
    }
225
226
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
227
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
228
     *
229
     * @return int
230
     */
231
    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...
232
    {
233
        return $transform->quality ?? Craft::$app->getConfig()->getGeneral()->defaultImageQuality;
234
    }
235
236
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
237
     * @inheritdoc
238
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
239
    public function getSettingsHtml()
240
    {
241
        return Craft::$app->getView()->renderTemplate('image-optimize/settings/image-transforms/thumbor.twig', [
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...
242
            'imageTransform' => $this,
243
        ]);
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...
244
    }
245
246
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
247
     * @inheritdoc
248
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
249
    public function rules()
250
    {
251
        $rules = parent::rules();
252
        $rules = array_merge($rules, [
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...
253
            [['baseUrl', 'securityKey'], 'default', 'value' => ''],
254
            [['baseUrl', 'securityKey'], 'string'],
255
        ]);
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...
256
257
        return $rules;
258
    }
259
}
260