Passed
Push — v1 ( 7859d5...83eaa9 )
by Andrew
22:02 queued 12:22
created

OptimizedImages   F

Complexity

Total Complexity 72

Size/Duplication

Total Lines 475
Duplicated Lines 0 %

Importance

Changes 18
Bugs 0 Features 0
Metric Value
wmc 72
eloc 240
c 18
b 0
f 0
dl 0
loc 475
rs 2.64

11 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
C shouldCreateVariants() 0 38 14
B resaveVolumeAssets() 0 44 6
C getTransformFromVariant() 0 43 12
A resaveAllVolumesAssets() 0 7 3
B updateOptimizedImageFieldData() 0 33 6
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
    /**
149
     * Should variants be created for the given OptimizedImages field and the Asset?
150
     *
151
     * @param $field
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 2 spaces but found 1
Loading history...
152
     * @param $asset
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 2 spaces but found 1
Loading history...
153
     * @return bool
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
154
     */
155
    public function shouldCreateVariants($field, $asset): bool
156
    {
157
        $createVariants = true;
158
        Craft::info(print_r($field->fieldVolumeSettings, true), __METHOD__);
159
        // See if we're ignoring files in this dir
160
        if (!empty($field->fieldVolumeSettings)) {
161
            foreach ($field->fieldVolumeSettings as $volumeHandle => $subfolders) {
162
                if ($asset->getVolume()->handle === $volumeHandle) {
163
                    if (is_string($subfolders) && $subfolders === '*') {
164
                        $createVariants = true;
165
                        Craft::info("Matched '*' wildcard ", __METHOD__);
166
                    } else {
167
                        $createVariants = false;
168
                        if (is_array($subfolders)) {
169
                            foreach ($subfolders as $subfolder) {
170
                                $folder = $asset->getFolder();
171
                                while ($folder !== null && !$createVariants) {
172
                                    if ($folder->uid === $subfolder) {
173
                                        Craft::info('Matched subfolder uid: ' . print_r($subfolder, true), __METHOD__);
174
                                        $createVariants = true;
175
                                    } else {
176
                                        $folder = $folder->getParent();
177
                                    }
178
                                }
179
                            }
180
                        }
181
                    }
182
                }
183
            }
184
        }
185
        // See if we should ignore this type of file
186
        $sourceType = $asset->getMimeType();
187
        if (!empty($field->ignoreFilesOfType) && $sourceType !== null) {
188
            if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) {
189
                $createVariants = false;
190
            }
191
        }
192
        return $createVariants;
193
    }
194
195
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
196
     * @param Field            $field
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
197
     * @param ElementInterface $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
198
     *
199
     * @throws \yii\db\Exception
200
     * @throws InvalidConfigException
201
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
202
    public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset)
203
    {
204
        /** @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...
205
        if ($asset instanceof Asset && $field instanceof OptimizedImagesField) {
206
            $createVariants = $this->shouldCreateVariants($field, $asset);
207
            // Create a new OptimizedImage model and populate it
208
            $model = new OptimizedImage();
209
            // Empty our the optimized image URLs
210
            $model->optimizedImageUrls = [];
211
            $model->optimizedWebPImageUrls = [];
212
            $model->variantSourceWidths = [];
213
            $model->placeholderWidth = 0;
214
            $model->placeholderHeight = 0;
215
            if ($asset !== null && $createVariants) {
216
                $this->populateOptimizedImageModel(
217
                    $asset,
218
                    $field->variants,
219
                    $model
220
                );
221
            }
222
            // Save our field data directly into the content table
223
            if ($field->handle !== null) {
224
                $asset->setFieldValue($field->handle, $field->serializeValue($model));
225
                $table = $asset->getContentTable();
226
                $column = $asset->getFieldColumnPrefix().$field->handle;
227
                $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset));
228
                Craft::$app->db->createCommand()
229
                    ->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...
230
                        $column => $data,
231
                    ], [
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...
232
                        'elementId' => $asset->getId(),
233
                    ], [], 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...
234
                    ->execute();
235
            }
236
        }
237
    }
238
239
    /**
240
     * Re-save all of the assets in all of the volumes
241
     *
242
     * @throws \yii\base\InvalidConfigException
243
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
244
    public function resaveAllVolumesAssets()
245
    {
246
        $volumes = Craft::$app->getVolumes()->getAllVolumes();
247
        foreach ($volumes as $volume) {
248
            if (is_subclass_of($volume, Volume::class)) {
249
                /** @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...
250
                $this->resaveVolumeAssets($volume);
251
            }
252
        }
253
    }
254
255
    /**
256
     * Re-save all of the Asset elements in the Volume $volume that have an
257
     * OptimizedImages field in the FieldLayout
258
     *
259
     * @param Volume $volume
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
260
     *
261
     * @throws \yii\base\InvalidConfigException
262
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
263
    public function resaveVolumeAssets(Volume $volume)
264
    {
265
        $needToReSave = false;
266
        /** @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...
267
        $fieldLayout = $volume->getFieldLayout();
268
        // Loop through the fields in the layout to see if there is an OptimizedImages field
269
        if ($fieldLayout) {
0 ignored issues
show
introduced by
$fieldLayout is of type craft\models\FieldLayout, thus it always evaluated to true.
Loading history...
270
            $fields = $fieldLayout->getFields();
271
            foreach ($fields as $field) {
272
                if ($field instanceof OptimizedImagesField) {
273
                    $needToReSave = true;
274
                }
275
            }
276
        }
277
        if ($needToReSave) {
278
            try {
279
                $siteId = Craft::$app->getSites()->getPrimarySite()->id;
280
            } catch (SiteNotFoundException $e) {
281
                $siteId = 0;
282
                Craft::error(
283
                    'Failed to get primary site: '.$e->getMessage(),
284
                    __METHOD__
285
                );
286
            }
287
288
            $queue = Craft::$app->getQueue();
289
            $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...
290
                'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]),
291
                'criteria' => [
292
                    'siteId' => $siteId,
293
                    'volumeId' => $volume->id,
294
                    'status' => null,
295
                    'enabledForSite' => false,
296
                ],
297
            ]));
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...
298
            Craft::debug(
299
                Craft::t(
300
                    'image-optimize',
301
                    'Started resaveVolumeAssets queue job id: {jobId}',
302
                    [
303
                        'jobId' => $jobId,
304
                    ]
305
                ),
306
                __METHOD__
307
            );
308
        }
309
    }
310
311
    /**
312
     * Re-save an individual asset
313
     *
314
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
315
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
316
    public function resaveAsset(int $id)
317
    {
318
        $queue = Craft::$app->getQueue();
319
        $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...
320
            'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]),
321
            'criteria' => [
322
                'id' => $id,
323
                'status' => null,
324
                'enabledForSite' => false,
325
            ],
326
        ]));
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...
327
        Craft::debug(
328
            Craft::t(
329
                'image-optimize',
330
                'Started resaveAsset queue job id: {jobId} Element id: {elementId}',
331
                [
332
                    'elementId' => $id,
333
                    'jobId' => $jobId,
334
                ]
335
            ),
336
            __METHOD__
337
        );
338
    }
339
340
    /**
341
     * Create an optimized SVG data uri
342
     * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
343
     *
344
     * @param string $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
345
     *
346
     * @return string
347
     */
348
    public function encodeOptimizedSVGDataUri(string $uri): string
349
    {
350
        // First, uri encode everything
351
        $uri = rawurlencode($uri);
352
        $replacements = [
353
            // remove newlines
354
            '/%0A/' => '',
355
            // put spaces back in
356
            '/%20/' => ' ',
357
            // put equals signs back in
358
            '/%3D/' => '=',
359
            // put colons back in
360
            '/%3A/' => ':',
361
            // put slashes back in
362
            '/%2F/' => '/',
363
            // replace quotes with apostrophes (may break certain SVGs)
364
            '/%22/' => "'",
365
        ];
366
        foreach ($replacements as $pattern => $replacement) {
367
            $uri = preg_replace($pattern, $replacement, $uri);
368
        }
369
370
        return $uri;
371
    }
372
373
    // Protected Methods
374
    // =========================================================================
375
376
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
377
     * @param Asset          $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
378
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
379
     * @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...
380
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
381
    protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio)
382
    {
383
        Craft::beginProfile('generatePlaceholders', __METHOD__);
384
        $settings = ImageOptimize::$plugin->getSettings();
385
        if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) {
386
            $placeholder = ImageOptimize::$plugin->placeholder;
387
            if ($element->focalPoint) {
388
                $position = $element->getFocalPoint();
389
            } else {
390
                $position = 'center-center';
391
            }
392
            $tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position);
393
            if (!empty($tempPath)) {
394
                // Generate our placeholder image
395
                $model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position);
396
                // Generate the color palette for the image
397
                if ($settings->createColorPalette) {
398
                    $model->colorPalette = $placeholder->generateColorPalette($tempPath);
399
                    $model->lightness = $placeholder->calculateLightness($model->colorPalette);
400
                }
401
                // Generate the Potrace SVG
402
                if ($settings->createPlaceholderSilhouettes) {
403
                    $model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath);
404
                }
405
                // Get rid of our placeholder image
406
                @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

406
                /** @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...
407
            }
408
        }
409
        Craft::endProfile('generatePlaceholders', __METHOD__);
410
    }
411
412
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
413
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
414
     * @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...
415
     * @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...
416
     *
417
     * @return array
418
     */
419
    protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array
420
    {
421
        $settings = ImageOptimize::$plugin->getSettings();
422
        $transform = new AssetTransform();
423
        $transform->format = $variant['format'] ?? null;
424
        // Handle animate .gif images by never changing the format
425
        $images = Craft::$app->getImages();
426
        if ($asset->extension === 'gif' && !$images->getIsGd()) {
427
            $imageSource = $asset->getTransformSource();
428
            try {
429
                if (ImageHelper::getIsAnimatedGif($imageSource)) {
430
                    $transform->format = null;
431
                }
432
            } catch (ImageException $e) {
433
                Craft::error($e->getMessage(), __METHOD__);
434
            } catch (InvalidConfigException $e) {
435
                Craft::error($e->getMessage(), __METHOD__);
436
            }
437
        }
438
        $useAspectRatio = $variant['useAspectRatio'] ?? true;
439
        if ($useAspectRatio) {
440
            $aspectRatio = $variant['aspectRatioX'] / $variant['aspectRatioY'];
441
        } else {
442
            $aspectRatio = $asset->width / $asset->height;
443
        }
444
        $width = $variant['width'] * $retinaSize;
445
        $transform->width = $width;
446
        $transform->height = (int)($width / $aspectRatio);
447
        // Image quality
448
        $quality = (int)($variant['quality'] ?? null);
449
        if (empty($quality)) {
450
            $quality = null;
451
        }
452
        if ($quality !== null && $settings->lowerQualityRetinaImageVariants && $retinaSize != '1') {
453
            $quality = (int)($quality * (1.5 / (int)$retinaSize));
454
        }
455
        $transform->quality = $quality;
456
        // Interlaced (progressive JPEGs or interlaced PNGs)
457
        if (property_exists($transform, 'interlace')) {
458
            $transform->interlace = 'line';
459
        }
460
461
        return [$transform, $aspectRatio];
462
    }
463
464
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
465
     * @param Asset          $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
466
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
467
     * @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...
468
     * @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...
469
     * @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...
470
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
471
    protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio)
472
    {
473
        Craft::beginProfile('addVariantImageToModel', __METHOD__);
474
        // Generate an image transform url
475
        $url = ImageOptimize::$plugin->transformMethod->getTransformUrl(
476
            $asset,
477
            $transform
478
        );
479
        Craft::info(
480
            'URL created: '.print_r($url, true),
481
            __METHOD__
482
        );
483
        // Update the model
484
        if (!empty($url)) {
485
            $model->variantSourceWidths[] = $variant['width'];
486
            $model->variantHeights[$transform->width] = $asset->getHeight($transform);
487
            // Store & prefetch image at the image URL
488
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($url);
489
            $model->optimizedImageUrls[$transform->width] = $url;
490
            // Store & prefetch image at the webp URL
491
            $webPUrl = ImageOptimize::$plugin->transformMethod->getWebPUrl(
492
                $url,
493
                $asset,
494
                $transform
495
            );
496
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($webPUrl);
497
            $model->optimizedWebPImageUrls[$transform->width] = $webPUrl;
498
            $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...
499
            $model->originalImageWidth = $asset->width;
500
            $model->originalImageHeight = $asset->height;
501
            // Make our placeholder image once, from the first variant
502
            if (!$model->placeholderWidth) {
503
                $model->placeholderWidth = $transform->width;
504
                $model->placeholderHeight = $transform->height;
505
                $this->generatePlaceholders($asset, $model, $aspectRatio);
506
            }
507
            Craft::info(
508
                'Created transforms for variant: '.print_r($variant, true),
509
                __METHOD__
510
            );
511
        }
512
        Craft::endProfile('addVariantImageToModel', __METHOD__);
513
    }
514
}
515