Passed
Push — develop ( 77372e...161ff9 )
by Andrew
05:18
created

OptimizedImages   F

Complexity

Total Complexity 71

Size/Duplication

Total Lines 462
Duplicated Lines 0 %

Importance

Changes 17
Bugs 0 Features 0
Metric Value
wmc 71
eloc 238
c 17
b 0
f 0
dl 0
loc 462
rs 2.7199

10 Methods

Rating   Name   Duplication   Size   Complexity  
A createOptimizedImages() 0 15 3
C populateOptimizedImageModel() 0 69 15
B generatePlaceholders() 0 29 7
A resaveAsset() 0 21 1
B resaveVolumeAssets() 0 44 6
C getTransformFromVariant() 0 43 12
A resaveAllVolumesAssets() 0 7 3
D updateOptimizedImageFieldData() 0 67 19
A encodeOptimizedSVGDataUri() 0 23 2
A addVariantImageToModel() 0 42 3

How to fix   Complexity   

Complex Class

Complex classes like OptimizedImages often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use OptimizedImages, and based on these observations, apply Extract Interface, too.

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\services;
12
13
use nystudio107\imageoptimize\ImageOptimize;
14
use nystudio107\imageoptimize\fields\OptimizedImages as OptimizedImagesField;
15
use nystudio107\imageoptimize\helpers\Image as ImageHelper;
16
use nystudio107\imageoptimize\models\OptimizedImage;
17
use nystudio107\imageoptimize\jobs\ResaveOptimizedImages;
18
19
use Craft;
20
use craft\base\Component;
21
use craft\base\ElementInterface;
22
use craft\base\Field;
23
use craft\base\Volume;
24
use craft\elements\Asset;
25
use craft\errors\ImageException;
26
use craft\errors\SiteNotFoundException;
27
use craft\helpers\Image;
28
use craft\helpers\Json;
29
use craft\models\AssetTransform;
30
use craft\models\FieldLayout;
31
use yii\base\InvalidConfigException;
32
33
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
34
 * @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 for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
35
 * @package   ImageOptimize
0 ignored issues
show
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
36
 * @since     1.4.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 for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
37
 */
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...
38
class OptimizedImages extends Component
39
{
40
    // Constants
41
    // =========================================================================
42
43
    // Public Properties
44
    // =========================================================================
45
46
    // Public Methods
47
    // =========================================================================
48
49
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
50
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
51
     * @param array $variants
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
52
     *
53
     * @return OptimizedImage|null
54
     */
55
    public function createOptimizedImages(Asset $asset, array $variants = [])
56
    {
57
        Craft::beginProfile('createOptimizedImages', __METHOD__);
58
        if (empty($variants)) {
59
            $settings = ImageOptimize::$plugin->getSettings();
60
            if ($settings) {
0 ignored issues
show
introduced by
$settings is of type nystudio107\imageoptimize\models\Settings, thus it always evaluated to true.
Loading history...
61
                $variants = $settings->defaultVariants;
62
            }
63
        }
64
65
        $model = new OptimizedImage();
66
        $this->populateOptimizedImageModel($asset, $variants, $model);
67
        Craft::endProfile('createOptimizedImages', __METHOD__);
68
69
        return $model;
70
    }
71
72
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
73
     * @param Asset          $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
74
     * @param array          $variants
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
75
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
76
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
77
    public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedImage $model)
78
    {
79
        Craft::beginProfile('populateOptimizedImageModel', __METHOD__);
80
        $settings = ImageOptimize::$plugin->getSettings();
81
        // Empty our the optimized image URLs
82
        $model->optimizedImageUrls = [];
83
        $model->optimizedWebPImageUrls = [];
84
        $model->variantSourceWidths = [];
85
        $model->placeholderWidth = 0;
86
        $model->placeholderHeight = 0;
87
88
        foreach ($variants as $variant) {
89
            $retinaSizes = ['1'];
90
            if (!empty($variant['retinaSizes'])) {
91
                $retinaSizes = $variant['retinaSizes'];
92
            }
93
            foreach ($retinaSizes as $retinaSize) {
94
                $finalFormat = empty($variant['format']) ? $asset->getExtension() : $variant['format'];
95
                // Only try the transform if it's possible
96
                if (Image::canManipulateAsImage($finalFormat)
97
                    && Image::canManipulateAsImage($asset->getExtension())
98
                    && $asset->height > 0) {
0 ignored issues
show
Coding Style introduced by
Closing parenthesis of a multi-line IF statement must be on a new line
Loading history...
99
                    // Create the transform based on the variant
100
                    list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, $retinaSize);
101
                    // Only create the image variant if it is not upscaled, or they are okay with it being up-scaled
102
                    if (($asset->width >= $transform->width && $asset->height >= $transform->height)
103
                        || $settings->allowUpScaledImageVariants
104
                    ) {
105
                        $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio);
106
                    }
107
                } else {
108
                    Craft::error(
109
                        'Could not create transform for: '.$asset->title
110
                        .' - Final format: '.$finalFormat
111
                        .' - Element extension: '.$asset->getExtension()
112
                        .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension()),
113
                        __METHOD__
114
                    );
115
                }
116
            }
117
        }
118
119
        // If no image variants were created, populate it with the image itself
120
        if (empty($model->optimizedImageUrls)) {
121
            $finalFormat = $asset->getExtension();
122
            if (Image::canManipulateAsImage($finalFormat)
123
                && Image::canManipulateAsImage($finalFormat)
124
                && $asset->height > 0) {
0 ignored issues
show
Coding Style introduced by
Closing parenthesis of a multi-line IF statement must be on a new line
Loading history...
125
                $variant = [
126
                    'width' => $asset->width,
127
                    'useAspectRatio' => false,
128
                    'aspectRatioX' => $asset->width,
129
                    'aspectRatioY' => $asset->height,
130
                    'retinaSizes' => ['1'],
131
                    'quality' => 0,
132
                ];
133
                list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, 1);
134
                $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio);
135
            } else {
136
                Craft::error(
137
                    'Could not create transform for: '.$asset->title
138
                    .' - Final format: '.$finalFormat
139
                    .' - Element extension: '.$asset->getExtension()
140
                    .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension()),
141
                    __METHOD__
142
                );
143
            }
144
        }
145
        Craft::endProfile('populateOptimizedImageModel', __METHOD__);
146
    }
147
148
    // Protected Methods
149
    // =========================================================================
150
151
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
152
     * @param Field            $field
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
153
     * @param ElementInterface $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
154
     *
155
     * @throws \yii\db\Exception
156
     * @throws InvalidConfigException
157
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
158
    public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset)
159
    {
160
        /** @var Asset $asset */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
161
        if ($asset instanceof Asset && $field instanceof OptimizedImagesField) {
162
            $createVariants = true;
163
            Craft::info(print_r($field->fieldVolumeSettings, true), __METHOD__);
164
            // See if we're ignoring files in this dir
165
            if (!empty($field->fieldVolumeSettings)) {
166
                foreach ($field->fieldVolumeSettings as $volumeHandle => $subfolders) {
167
                    if ($asset->getVolume()->handle === $volumeHandle) {
0 ignored issues
show
Bug introduced by
Accessing handle on the interface craft\base\VolumeInterface suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
168
                        if (is_string($subfolders) && $subfolders === '*') {
169
                            $createVariants = true;
170
                            Craft::info("Matched '*' wildcard ", __METHOD__);
171
                        } else {
172
                            $createVariants = false;
173
                            if (is_array($subfolders)) {
174
                                foreach ($subfolders as $subfolder) {
175
                                    $folder = $asset->getFolder();
176
                                    while ($folder !== null && !$createVariants) {
177
                                        if ($folder->uid === $subfolder) {
178
                                            Craft::info('Matched subfolder uid: '.print_r($subfolder, true), __METHOD__);
179
                                            $createVariants = true;
180
                                        } else {
181
                                            $folder = $folder->getParent();
182
                                        }
183
                                    }
184
                                }
185
                            }
186
                        }
187
                    }
188
                }
189
            }
190
            // See if we should ignore this type of file
191
            $sourceType = $asset->getMimeType();
192
            if (!empty($field->ignoreFilesOfType) && $sourceType !== null) {
193
                if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) {
194
                    $createVariants = false;
195
                }
196
            }
197
            // Create a new OptimizedImage model and populate it
198
            $model = new OptimizedImage();
199
            // Empty our the optimized image URLs
200
            $model->optimizedImageUrls = [];
201
            $model->optimizedWebPImageUrls = [];
202
            $model->variantSourceWidths = [];
203
            $model->placeholderWidth = 0;
204
            $model->placeholderHeight = 0;
205
            if ($asset !== null && $createVariants) {
206
                $this->populateOptimizedImageModel(
207
                    $asset,
208
                    $field->variants,
209
                    $model
210
                );
211
            }
212
            // Save our field data directly into the content table
213
            if ($field->handle !== null) {
214
                $asset->setFieldValue($field->handle, $field->serializeValue($model));
215
                $table = $asset->getContentTable();
216
                $column = $asset->getFieldColumnPrefix().$field->handle;
217
                $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset));
218
                Craft::$app->db->createCommand()
219
                    ->update($table, [
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...
220
                        $column => $data,
221
                    ], [
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 24 spaces, but found 20.
Loading history...
222
                        'elementId' => $asset->getId(),
223
                    ], [], false)
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...
224
                    ->execute();
225
            }
226
        }
227
    }
228
229
    /**
230
     * Re-save all of the assets in all of the volumes
231
     *
232
     * @throws \yii\base\InvalidConfigException
233
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
234
    public function resaveAllVolumesAssets()
235
    {
236
        $volumes = Craft::$app->getVolumes()->getAllVolumes();
237
        foreach ($volumes as $volume) {
238
            if (is_subclass_of($volume, Volume::class)) {
239
                /** @var Volume $volume */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
240
                $this->resaveVolumeAssets($volume);
241
            }
242
        }
243
    }
244
245
    /**
246
     * Re-save all of the Asset elements in the Volume $volume that have an
247
     * OptimizedImages field in the FieldLayout
248
     *
249
     * @param Volume $volume
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
250
     *
251
     * @throws \yii\base\InvalidConfigException
252
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
253
    public function resaveVolumeAssets(Volume $volume)
254
    {
255
        $needToReSave = false;
256
        /** @var FieldLayout $fieldLayout */
0 ignored issues
show
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
257
        $fieldLayout = $volume->getFieldLayout();
258
        // Loop through the fields in the layout to see if there is an OptimizedImages field
259
        if ($fieldLayout) {
0 ignored issues
show
introduced by
$fieldLayout is of type craft\models\FieldLayout, thus it always evaluated to true.
Loading history...
260
            $fields = $fieldLayout->getFields();
261
            foreach ($fields as $field) {
262
                if ($field instanceof OptimizedImagesField) {
263
                    $needToReSave = true;
264
                }
265
            }
266
        }
267
        if ($needToReSave) {
268
            try {
269
                $siteId = Craft::$app->getSites()->getPrimarySite()->id;
270
            } catch (SiteNotFoundException $e) {
271
                $siteId = 0;
272
                Craft::error(
273
                    'Failed to get primary site: '.$e->getMessage(),
274
                    __METHOD__
275
                );
276
            }
277
278
            $queue = Craft::$app->getQueue();
279
            $jobId = $queue->push(new ResaveOptimizedImages([
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...
280
                'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]),
281
                'criteria' => [
282
                    'siteId' => $siteId,
283
                    'volumeId' => $volume->id,
284
                    'status' => null,
285
                    'enabledForSite' => false,
286
                ],
287
            ]));
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...
288
            Craft::debug(
289
                Craft::t(
290
                    'image-optimize',
291
                    'Started resaveVolumeAssets queue job id: {jobId}',
292
                    [
293
                        'jobId' => $jobId,
294
                    ]
295
                ),
296
                __METHOD__
297
            );
298
        }
299
    }
300
301
    /**
302
     * Re-save an individual asset
303
     *
304
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
305
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
306
    public function resaveAsset(int $id)
307
    {
308
        $queue = Craft::$app->getQueue();
309
        $jobId = $queue->push(new ResaveOptimizedImages([
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...
310
            'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]),
311
            'criteria' => [
312
                'id' => $id,
313
                'status' => null,
314
                'enabledForSite' => false,
315
            ],
316
        ]));
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...
317
        Craft::debug(
318
            Craft::t(
319
                'image-optimize',
320
                'Started resaveAsset queue job id: {jobId} Element id: {elementId}',
321
                [
322
                    'elementId' => $id,
323
                    'jobId' => $jobId,
324
                ]
325
            ),
326
            __METHOD__
327
        );
328
    }
329
330
    /**
331
     * Create an optimized SVG data uri
332
     * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
333
     *
334
     * @param string $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
335
     *
336
     * @return string
337
     */
338
    public function encodeOptimizedSVGDataUri(string $uri): string
339
    {
340
        // First, uri encode everything
341
        $uri = rawurlencode($uri);
342
        $replacements = [
343
            // remove newlines
344
            '/%0A/' => '',
345
            // put spaces back in
346
            '/%20/' => ' ',
347
            // put equals signs back in
348
            '/%3D/' => '=',
349
            // put colons back in
350
            '/%3A/' => ':',
351
            // put slashes back in
352
            '/%2F/' => '/',
353
            // replace quotes with apostrophes (may break certain SVGs)
354
            '/%22/' => "'",
355
        ];
356
        foreach ($replacements as $pattern => $replacement) {
357
            $uri = preg_replace($pattern, $replacement, $uri);
358
        }
359
360
        return $uri;
361
    }
362
363
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
364
     * @param Asset          $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
365
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
366
     * @param                $aspectRatio
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 16
Loading history...
367
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
368
    protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio)
369
    {
370
        Craft::beginProfile('generatePlaceholders', __METHOD__);
371
        $settings = ImageOptimize::$plugin->getSettings();
372
        if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) {
373
            $placeholder = ImageOptimize::$plugin->placeholder;
374
            if ($element->focalPoint) {
375
                $position = $element->getFocalPoint();
376
            } else {
377
                $position = 'center-center';
378
            }
379
            $tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position);
380
            if (!empty($tempPath)) {
381
                // Generate our placeholder image
382
                $model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position);
383
                // Generate the color palette for the image
384
                if ($settings->createColorPalette) {
385
                    $model->colorPalette = $placeholder->generateColorPalette($tempPath);
386
                    $model->lightness = $placeholder->calculateLightness($model->colorPalette);
387
                }
388
                // Generate the Potrace SVG
389
                if ($settings->createPlaceholderSilhouettes) {
390
                    $model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath);
391
                }
392
                // Get rid of our placeholder image
393
                @unlink($tempPath);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for unlink(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unhandled  annotation

393
                /** @scrutinizer ignore-unhandled */ @unlink($tempPath);

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
394
            }
395
        }
396
        Craft::endProfile('generatePlaceholders', __METHOD__);
397
    }
398
399
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
400
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
401
     * @param       $variant
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 7
Loading history...
402
     * @param       $retinaSize
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 7
Loading history...
403
     *
404
     * @return array
405
     */
406
    protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array
407
    {
408
        $settings = ImageOptimize::$plugin->getSettings();
409
        $transform = new AssetTransform();
410
        $transform->format = $variant['format'] ?? null;
411
        // Handle animate .gif images by never changing the format
412
        $images = Craft::$app->getImages();
413
        if ($asset->extension === 'gif' && !$images->getIsGd()) {
414
            $imageSource = $asset->getTransformSource();
415
            try {
416
                if (ImageHelper::getIsAnimatedGif($imageSource)) {
417
                    $transform->format = null;
418
                }
419
            } catch (ImageException $e) {
420
                Craft::error($e->getMessage(), __METHOD__);
421
            } catch (InvalidConfigException $e) {
422
                Craft::error($e->getMessage(), __METHOD__);
423
            }
424
        }
425
        $useAspectRatio = $variant['useAspectRatio'] ?? true;
426
        if ($useAspectRatio) {
427
            $aspectRatio = $variant['aspectRatioX'] / $variant['aspectRatioY'];
428
        } else {
429
            $aspectRatio = $asset->width / $asset->height;
430
        }
431
        $width = $variant['width'] * $retinaSize;
432
        $transform->width = $width;
433
        $transform->height = (int)($width / $aspectRatio);
434
        // Image quality
435
        $quality = (int)($variant['quality'] ?? null);
436
        if (empty($quality)) {
437
            $quality = null;
438
        }
439
        if ($quality !== null && $settings->lowerQualityRetinaImageVariants && $retinaSize != '1') {
440
            $quality = (int)($quality * (1.5 / (int)$retinaSize));
441
        }
442
        $transform->quality = $quality;
443
        // Interlaced (progressive JPEGs or interlaced PNGs)
444
        if (property_exists($transform, 'interlace')) {
445
            $transform->interlace = 'line';
446
        }
447
448
        return [$transform, $aspectRatio];
449
    }
450
451
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
452
     * @param Asset          $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
453
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
454
     * @param                $transform
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 16
Loading history...
455
     * @param                $variant
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 16
Loading history...
456
     * @param                $aspectRatio
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 1 spaces but found 16
Loading history...
457
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
458
    protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio)
459
    {
460
        Craft::beginProfile('addVariantImageToModel', __METHOD__);
461
        // Generate an image transform url
462
        $url = ImageOptimize::$plugin->transformMethod->getTransformUrl(
463
            $asset,
464
            $transform
465
        );
466
        Craft::info(
467
            'URL created: '.print_r($url, true),
468
            __METHOD__
469
        );
470
        // Update the model
471
        if (!empty($url)) {
472
            $model->variantSourceWidths[] = $variant['width'];
473
            $model->variantHeights[$transform->width] = $asset->getHeight($transform);
474
            // Store & prefetch image at the image URL
475
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($url);
476
            $model->optimizedImageUrls[$transform->width] = $url;
477
            // Store & prefetch image at the webp URL
478
            $webPUrl = ImageOptimize::$plugin->transformMethod->getWebPUrl(
479
                $url,
480
                $asset,
481
                $transform
482
            );
483
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($webPUrl);
484
            $model->optimizedWebPImageUrls[$transform->width] = $webPUrl;
485
            $model->focalPoint = $asset->focalPoint;
0 ignored issues
show
Documentation Bug introduced by
It seems like $asset->focalPoint can also be of type string. However, the property $focalPoint is declared as type array<mixed,double>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
486
            $model->originalImageWidth = $asset->width;
487
            $model->originalImageHeight = $asset->height;
488
            // Make our placeholder image once, from the first variant
489
            if (!$model->placeholderWidth) {
490
                $model->placeholderWidth = $transform->width;
491
                $model->placeholderHeight = $transform->height;
492
                $this->generatePlaceholders($asset, $model, $aspectRatio);
493
            }
494
            Craft::info(
495
                'Created transforms for variant: '.print_r($variant, true),
496
                __METHOD__
497
            );
498
        }
499
        Craft::endProfile('addVariantImageToModel', __METHOD__);
500
    }
501
}
502