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

ThumborImageTransform::getQuality()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
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\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...
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): string
54
    {
55
        // TODO: waiting for @khalwat :)
56
        return $url;
57
58
        $builder = self::getUrlBuilderForTransform($asset, $transform, $params)
0 ignored issues
show
Unused Code introduced by
$builder = self::getUrlB...ilter('format', 'webp') is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
59
            ->addFilter('format', 'webp');
60
61
        return (string) $builder;
62
    }
63
64
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
65
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
66
     * @param array  $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
67
     *
68
     * @return bool
69
     */
70
    public static function purgeUrl(string $url, array $params = []): bool
71
    {
72
        return false;
73
    }
74
75
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
76
     * @return array
77
     */
78
    public static function getTransformParams(): array
79
    {
80
        $settings = ImageOptimize::$plugin->getSettings();
81
        $params = [
82
            'baseUrl' => $settings->thumborBaseUrl,
83
            'securityKey' => $settings->thumborSecurityKey,
84
        ];
85
86
        return $params;
87
    }
88
89
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
90
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
91
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
92
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
93
     *
94
     * @return UrlBuilder
95
     * @throws \yii\base\Exception
96
     * @throws \yii\base\InvalidConfigException
97
     */
98
    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...
99
    {
100
        $assetUri = self::getAssetUri($asset);
101
        $baseUrl = $params['baseUrl'];
102
        $securityKey = $params['securityKey'] ?: null;
103
        $builder = UrlBuilder::construct($baseUrl, $securityKey, $assetUri);
104
        $settings = ImageOptimize::$plugin->getSettings();
105
106
        if ($transform->mode === 'fit') {
107
108
            // https://thumbor.readthedocs.io/en/latest/usage.html#fit-in
109
            $builder->fitIn($transform->width, $transform->height);
110
        } elseif ($transform->mode === 'stretch') {
111
            $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

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

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