Passed
Pull Request — develop (#115)
by Timothy
05:03
created

ThumborImageTransform::getUrlBuilderForTransform()   C

Complexity

Conditions 12
Paths 120

Size

Total Lines 64
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 30
dl 0
loc 64
rs 6.8
c 0
b 0
f 0
cc 12
nc 120
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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
    // Constants
32
    // =========================================================================
33
34
    // Static Methods
35
    // =========================================================================
36
37
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
38
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
39
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
40
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
41
     *
42
     * @return string|null
43
     * @throws \yii\base\Exception
44
     * @throws \yii\base\InvalidConfigException
45
     */
46
    public static function getTransformUrl(Asset $asset, $transform, array $params = [])
47
    {
48
        return (string) self::getUrlBuilderForTransform($asset, $transform, $params);
49
    }
50
51
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
52
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
53
     *
54
     * @return string
55
     */
56
    public static function getWebPUrl(string $url): string
57
    {
58
        // TODO: waiting for @khalwat :)
59
        return $url;
60
61
        $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...
62
            ->addFilter('format', 'webp');
63
64
        return (string) $builder;
65
    }
66
67
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
68
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
69
     * @param array  $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
70
     *
71
     * @return bool
72
     */
73
    public static function purgeUrl(string $url, array $params = []): bool
74
    {
75
        return false;
76
    }
77
78
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
79
     * @return array
80
     */
81
    public static function getTransformParams(): array
82
    {
83
        $settings = ImageOptimize::$plugin->getSettings();
84
        $params = [
85
            'baseUrl' => $settings->thumborBaseUrl,
86
            'securityKey' => $settings->thumborSecurityKey,
87
        ];
88
89
        return $params;
90
    }
91
92
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
93
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
94
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
95
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
96
     *
97
     * @return UrlBuilder
98
     * @throws \yii\base\Exception
99
     * @throws \yii\base\InvalidConfigException
100
     */
101
    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...
102
    {
103
        $assetUri = self::getAssetUri($asset);
104
        $baseUrl = $params['baseUrl'];
105
        $securityKey = $params['securityKey'] ?: null;
106
        $builder = UrlBuilder::construct($baseUrl, $securityKey, $assetUri);
107
        $settings = ImageOptimize::$plugin->getSettings();
108
109
        if ($transform->mode === 'fit') {
110
111
            // https://thumbor.readthedocs.io/en/latest/usage.html#fit-in
112
            $builder->fitIn($transform->width, $transform->height);
113
        } elseif ($transform->mode === 'stretch') {
114
115
            // AFAIK, this isn't possible with Thumbor…throw exception?
116
            // https://github.com/thumbor/thumbor/issues/1123
117
            $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

117
                ->/** @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...
118
                ->resize($transform->width, $transform->height)
119
                ->addFilter('upscale');
120
        } else {
121
122
            // https://thumbor.readthedocs.io/en/latest/usage.html#image-size
123
            $builder->resize($transform->width, $transform->height);
124
125
            if ($focalPoint = self::getFocalPoint($asset)) {
126
127
                // https://thumbor.readthedocs.io/en/latest/focal.html
128
                $builder->addFilter('focal', $focalPoint);
129
            } elseif (preg_match('/(top|center|bottom)-(left|center|right)/', $transform->position, $matches)) {
130
                $v = str_replace('center', 'middle', $matches[1]);
131
                $h = $matches[2];
132
133
                // https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align
134
                $builder->valign($v)->halign($h);
135
            }
136
        }
137
138
        // https://thumbor.readthedocs.io/en/latest/format.html
139
        if ($format = self::getFormat($transform)) {
140
            $builder->addFilter('format', $format);
141
        }
142
143
        // https://thumbor.readthedocs.io/en/latest/quality.html
144
        if ($quality = self::getQuality($transform)) {
145
            $builder->addFilter('quality', $quality);
146
        }
147
148
        if (property_exists($transform, 'interlace')) {
149
            // Progressive JPEGs are configured on the server level,
150
            // not as an option: https://thumbor.readthedocs.io/en/latest/jpegtran.html
151
        }
152
153
        if ($settings->autoSharpenScaledImages) {
154
            // See if the image has been scaled >= 50%
155
            $widthScale = $asset->getWidth() / ($transform->width ?? $asset->getWidth());
156
            $heightScale = $asset->getHeight() / ($transform->height ?? $asset->getHeight());
157
            if (($widthScale >= 2.0) || ($heightScale >= 2.0)) {
158
159
                // https://thumbor.readthedocs.io/en/latest/sharpen.html
160
                $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

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