Passed
Push — develop ( 582419...920dd6 )
by Andrew
06:06
created

OptimizedImages::getTransformFromVariant()   B

Complexity

Conditions 10
Paths 40

Size

Total Lines 40
Code Lines 28

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 28
c 4
b 0
f 0
dl 0
loc 40
rs 7.6666
cc 10
nc 40
nop 3

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

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