Passed
Pull Request — develop (#115)
by Timothy
04:41
created

ThumborImageTransform::getWebPUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 3
dl 0
loc 6
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 4
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\helpers\ArrayHelper;
17
use craft\helpers\UrlHelper;
18
use craft\models\AssetTransform;
19
use Thumbor\Url\Builder as UrlBuilder;
20
use Psr\Http\Message\ResponseInterface;
21
22
use Craft;
23
24
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
25
 * @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...
26
 * @package   ImageOptimize
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
27
 * @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...
28
 */
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...
29
class ThumborImageTransform extends ImageTransform implements ImageTransformInterface
30
{
31
    // Static Methods
32
    // =========================================================================
33
34
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
35
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
36
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
37
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
38
     *
39
     * @return string|null
40
     * @throws \yii\base\Exception
41
     * @throws \yii\base\InvalidConfigException
42
     */
43
    public static function getTransformUrl(Asset $asset, $transform, array $params = [])
44
    {
45
        return (string) self::getUrlBuilderForTransform($asset, $transform, $params);
46
    }
47
48
    /**
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...
Coding Style introduced by
Parameter $transform should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $params should have a doc-comment as per coding-style.
Loading history...
49
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
50
     *
51
     * @return string
52
     */
53
     public static function getWebPUrl(string $url, Asset $asset, $transform, array $params = []): string
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 4 spaces, found 5
Loading history...
54
    {
0 ignored issues
show
Coding Style introduced by
Opening brace indented incorrectly; expected 5 spaces, found 4
Loading history...
55
        $builder = self::getUrlBuilderForTransform($asset, $transform, $params)
56
            ->addFilter('format', 'webp');
57
58
        return (string) $builder;
59
    }
0 ignored issues
show
Coding Style introduced by
Closing brace indented incorrectly; expected 5 spaces, found 4
Loading history...
60
61
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
62
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
63
     * @param array  $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
64
     *
65
     * @return bool
66
     */
67
    public static function purgeUrl(string $url, array $params = []): bool
68
    {
69
        return false;
70
    }
71
72
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
73
     * @return array
74
     */
75
    public static function getTransformParams(): array
76
    {
77
        $settings = ImageOptimize::$plugin->getSettings();
78
        $params = [
79
            'baseUrl' => $settings->thumborBaseUrl,
80
            'securityKey' => $settings->thumborSecurityKey,
81
        ];
82
83
        return $params;
84
    }
85
86
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
87
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
88
     * @param AssetTransform|null $transform
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 UrlBuilder
92
     * @throws \yii\base\Exception
93
     * @throws \yii\base\InvalidConfigException
94
     */
95
    private static 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...
96
    {
97
        $assetUri = self::getAssetUri($asset);
98
        $baseUrl = $params['baseUrl'];
99
        $securityKey = $params['securityKey'] ?: null;
100
        $builder = UrlBuilder::construct($baseUrl, $securityKey, $assetUri);
101
        $settings = ImageOptimize::$plugin->getSettings();
102
103
        if ($transform->mode === 'fit') {
104
105
            // https://thumbor.readthedocs.io/en/latest/usage.html#fit-in
106
            $builder->fitIn($transform->width, $transform->height);
107
        } elseif ($transform->mode === 'stretch') {
108
            $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

108
                ->/** @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...
109
                ->resize($transform->width, $transform->height)
110
                ->addFilter('upscale');
111
112
            // https://github.com/thumbor/thumbor/issues/1123
113
            Craft::warning('Thumbor has no equivalent to the "stretch" transform mode. The resulting image will be resized and cropped, but not stretched.', __METHOD__);
114
        } else {
115
116
            // https://thumbor.readthedocs.io/en/latest/usage.html#image-size
117
            $builder->resize($transform->width, $transform->height);
118
119
            if ($focalPoint = self::getFocalPoint($asset)) {
120
121
                // https://thumbor.readthedocs.io/en/latest/focal.html
122
                $builder->addFilter('focal', $focalPoint);
123
            } elseif (preg_match('/(top|center|bottom)-(left|center|right)/', $transform->position, $matches)) {
124
                $v = str_replace('center', 'middle', $matches[1]);
125
                $h = $matches[2];
126
127
                // https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align
128
                $builder->valign($v)->halign($h);
129
            }
130
        }
131
132
        // https://thumbor.readthedocs.io/en/latest/format.html
133
        if ($format = self::getFormat($transform)) {
134
            $builder->addFilter('format', $format);
135
        }
136
137
        // https://thumbor.readthedocs.io/en/latest/quality.html
138
        if ($quality = self::getQuality($transform)) {
139
            $builder->addFilter('quality', $quality);
140
        }
141
142
        if (property_exists($transform, 'interlace')) {
143
            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__);
144
        }
145
146
        if ($settings->autoSharpenScaledImages) {
147
148
            // See if the image has been scaled >= 50%
149
            $widthScale = $asset->getWidth() / ($transform->width ?? $asset->getWidth());
150
            $heightScale = $asset->getHeight() / ($transform->height ?? $asset->getHeight());
151
            if (($widthScale >= 2.0) || ($heightScale >= 2.0)) {
152
153
                // https://thumbor.readthedocs.io/en/latest/sharpen.html
154
                $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

154
                $builder->/** @scrutinizer ignore-call */ 
155
                          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...
155
            }
156
        }
157
158
        return $builder;
159
    }
160
161
    /**
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...
162
     * @return string|null
163
     */
164
    private static 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...
165
    {
166
        $focalPoint = $asset->getFocalPoint();
167
168
        if (!$focalPoint) {
169
            return null;
170
        }
171
172
        $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...
173
            'top' => $focalPoint['y'] * $asset->height - 1,
174
            'left' => $focalPoint['x'] * $asset->width - 1,
175
            'bottom' => $focalPoint['y'] * $asset->height + 1,
176
            'right' => $focalPoint['x'] * $asset->width + 1,
177
        ]);
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...
178
179
        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...
180
            $box['top'],
181
            'x',
182
            $box['left'],
183
            ':',
184
            $box['bottom'],
185
            'x',
186
            $box['right'],
187
        ]);
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...
188
    }
189
190
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
191
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
192
     *
193
     * @return string|null
194
     */
195
    private static function getFormat($transform)
0 ignored issues
show
Coding Style introduced by
Private method name "ThumborImageTransform::getFormat" must be prefixed with an underscore
Loading history...
196
    {
197
        $format = str_replace(
198
            ['Auto', 'jpg'],
199
            ['', 'jpeg'],
200
            $transform->format
201
        );
202
203
        return $format ?: null;
204
    }
205
206
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
207
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
208
     *
209
     * @return int
210
     */
211
    private static function getQuality($transform)
0 ignored issues
show
Coding Style introduced by
Private method name "ThumborImageTransform::getQuality" must be prefixed with an underscore
Loading history...
212
    {
213
        return $transform->quality ?? Craft::$app->getConfig()->getGeneral()->defaultImageQuality;
214
    }
215
}
216