Passed
Push — develop ( 44c484...e0acd2 )
by Andrew
04:36
created

OptimizedImages::updateOptimizedImageFieldData()   B

Complexity

Conditions 9
Paths 13

Size

Total Lines 40
Code Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

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

362
                /** @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...
363
            }
364
        }
365
        Craft::endProfile('generatePlaceholders', __METHOD__);
366
    }
367
368
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $variant should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $retinaSize should have a doc-comment as per coding-style.
Loading history...
369
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
370
     * @param       $variant
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 7
Loading history...
371
     * @param       $retinaSize
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 7
Loading history...
372
     *
373
     * @return array
374
     */
375
    protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array
376
    {
377
        $settings = ImageOptimize::$plugin->getSettings();
378
        $transform = new AssetTransform();
379
        $transform->format = $variant['format'];
380
        $useAspectRatio = $variant['useAspectRatio'] ?? true;
381
        if ($useAspectRatio) {
382
            $aspectRatio = $variant['aspectRatioX'] / $variant['aspectRatioY'];
383
        } else {
384
            $aspectRatio = $asset->width / $asset->height;
385
        }
386
        $width = $variant['width'] * $retinaSize;
387
        $transform->width = $width;
388
        $transform->height = (int)($width / $aspectRatio);
389
        // Image quality
390
        $quality = $variant['quality'];
391
        if ($settings->lowerQualityRetinaImageVariants && $retinaSize != '1') {
392
            $quality = (int)($quality * (1.5 / (int)$retinaSize));
393
        }
394
        $transform->quality = $quality;
395
        // Interlaced (progressive JPEGs or interlaced PNGs)
396
        if (property_exists($transform, 'interlace')) {
397
            $transform->interlace = 'line';
398
        }
399
400
        return [$transform, $aspectRatio];
401
    }
402
403
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $transform should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $variant should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $aspectRatio should have a doc-comment as per coding-style.
Loading history...
404
     * @param Asset          $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
405
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
406
     * @param                $transform
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 16
Loading history...
407
     * @param                $variant
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 16
Loading history...
408
     * @param                $aspectRatio
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 16
Loading history...
409
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
410
    protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio)
411
    {
412
        Craft::beginProfile('addVariantImageToModel', __METHOD__);
413
        // Generate an image transform url
414
        $url = ImageOptimize::$transformClass::getTransformUrl(
415
            $asset,
416
            $transform,
417
            ImageOptimize::$transformParams
418
        );
419
        Craft::info(
420
            'URL created: '.print_r($url, true),
421
            __METHOD__
422
        );
423
        // Update the model
424
        if (!empty($url)) {
425
            $model->variantSourceWidths[] = $variant['width'];
426
            $model->variantHeights[$transform->width] = $asset->getHeight($transform);
427
            // Store & prefetch image at the image URL
428
            //ImageOptimize::$transformClass::prefetchRemoteFile($url);
429
            $model->optimizedImageUrls[$transform->width] = $url;
430
            // Store & prefetch image at the webp URL
431
            $webPUrl = ImageOptimize::$transformClass::getWebPUrl(
432
                $url,
433
                $asset,
434
                $transform,
435
                ImageOptimize::$transformParams
436
            );
437
            //ImageOptimize::$transformClass::prefetchRemoteFile($webPUrl);
438
            $model->optimizedWebPImageUrls[$transform->width] = $webPUrl;
439
            $model->focalPoint = $asset->focalPoint;
440
            $model->originalImageWidth = $asset->width;
441
            $model->originalImageHeight = $asset->height;
442
            // Make our placeholder image once, from the first variant
443
            if (!$model->placeholderWidth) {
444
                $model->placeholderWidth = $transform->width;
445
                $model->placeholderHeight = $transform->height;
446
                $this->generatePlaceholders($asset, $model, $aspectRatio);
447
            }
448
            Craft::info(
449
                'Created transforms for variant: '.print_r($variant, true),
450
                __METHOD__
451
            );
452
        }
453
        Craft::endProfile('addVariantImageToModel', __METHOD__);
454
    }
455
}
456