Passed
Pull Request — develop (#130)
by Timothy
05:32
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
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
33
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
34
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
35
     *
36
     * @return string|null
37
     * @throws \yii\base\Exception
38
     * @throws \yii\base\InvalidConfigException
39
     */
40
    public static function getTransformUrl(Asset $asset, $transform, array $params = [])
41
    {
42
        return (string)self::getUrlBuilderForTransform($asset, $transform, $params);
43
    }
44
45
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
46
     * @param string              $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
47
     * @param Asset               $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
48
     * @param AssetTransform|null $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
49
     * @param array               $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
50
     *
51
     * @return string
52
     * @throws \yii\base\Exception
53
     * @throws \yii\base\InvalidConfigException
54
     */
55
    public static function getWebPUrl(string $url, Asset $asset, $transform, array $params = []): string
56
    {
57
        $builder = self::getUrlBuilderForTransform($asset, $transform, $params)
58
            ->addFilter('format', 'webp');
59
60
        return (string)$builder;
61
    }
62
63
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
64
     * @param string $url
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
65
     * @param array  $params
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
66
     *
67
     * @return bool
68
     */
69
    public static function purgeUrl(string $url, array $params = []): bool
70
    {
71
        return false;
72
    }
73
74
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
75
     * @return array
76
     */
77
    public static function getTransformParams(): array
78
    {
79
        $settings = ImageOptimize::$plugin->getSettings();
80
        $params = [
81
            'baseUrl' => $settings->thumborBaseUrl,
82
            'securityKey' => $settings->thumborSecurityKey,
83
            'includeBucketPrefix' => $settings->thumborIncludeBucketPrefix,
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
        $includeBucketPrefix = $params['includeBucketPrefix'] ?? false;
101
        $baseUrl = $params['baseUrl'];
102
        $securityKey = $params['securityKey'] ?: null;
103
        $assetUri = self::getThumborAssetUri($asset, $includeBucketPrefix);
104
        $builder = UrlBuilder::construct($baseUrl, $securityKey, $assetUri);
105
        $settings = ImageOptimize::$plugin->getSettings();
106
107
        if ($transform->mode === 'fit') {
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
                // https://thumbor.readthedocs.io/en/latest/focal.html
124
                $builder->addFilter('focal', $focalPoint);
125
            } elseif (preg_match('/(top|center|bottom)-(left|center|right)/', $transform->position, $matches)) {
126
                $v = str_replace('center', 'middle', $matches[1]);
127
                $h = $matches[2];
128
129
                // https://thumbor.readthedocs.io/en/latest/usage.html#horizontal-align
130
                $builder->valign($v)->halign($h);
131
            }
132
        }
133
134
        // https://thumbor.readthedocs.io/en/latest/format.html
135
        if ($format = self::getFormat($transform)) {
136
            $builder->addFilter('format', $format);
137
        }
138
139
        // https://thumbor.readthedocs.io/en/latest/quality.html
140
        if ($quality = self::getQuality($transform)) {
141
            $builder->addFilter('quality', $quality);
142
        }
143
144
        if (property_exists($transform, 'interlace')) {
145
            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__);
146
        }
147
148
        if ($settings->autoSharpenScaledImages) {
149
            // See if the image has been scaled >= 50%
150
            $widthScale = $asset->getWidth() / ($transform->width ?? $asset->getWidth());
151
            $heightScale = $asset->getHeight() / ($transform->height ?? $asset->getHeight());
152
            if (($widthScale >= 2.0) || ($heightScale >= 2.0)) {
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['left'],
181
            'x',
182
            $box['top'],
183
            ':',
184
            $box['right'],
185
            'x',
186
            $box['bottom'],
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('jpg', 'jpeg', $transform->format);
198
199
        return $format ?: null;
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 int
206
     */
207
    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...
208
    {
209
        return $transform->quality ?? Craft::$app->getConfig()->getGeneral()->defaultImageQuality;
210
    }
211
212
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
213
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
214
     * @param bool  $includeBucketPrefix
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
215
     *
216
     * @return mixed
217
     * @throws \yii\base\InvalidConfigException
218
     */
219
    public static function getThumborAssetUri(Asset $asset, bool $includeBucketPrefix = false)
220
    {
221
        $uri = self::getAssetUri($asset);
222
        $volume = $asset->getVolume();
223
224
        if ($includeBucketPrefix && ($volume->bucket ?? null)) {
0 ignored issues
show
Bug introduced by
Accessing bucket on the interface craft\base\VolumeInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
225
            $uri = $volume->bucket . '/' . $uri;
226
        }
227
228
        return $uri;
229
    }
230
}
231