Passed
Push — develop ( 875640...705a72 )
by Andrew
06:19
created

OptimizedImages::resaveAsset()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 21
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 14
dl 0
loc 21
rs 9.7998
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
/**
3
 * ImageOptimize plugin for Craft CMS 3.x
4
 *
5
 * Automatically optimize images after they've been transformed
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @copyright Copyright (c) 2017 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
10
11
namespace nystudio107\imageoptimize\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
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
157
    public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset)
158
    {
159
        /** @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...
160
        if ($asset instanceof Asset && $field instanceof OptimizedImagesField) {
161
            $createVariants = true;
162
            $sourceType = $asset->getMimeType();
163
            if (!empty($field->ignoreFilesOfType) && $sourceType !== null) {
164
                if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) {
165
                    $createVariants = false;
166
                }
167
            }
168
            Craft::info(print_r($sourceType, true), 'image-optimize');
169
            // Create a new OptimizedImage model and populate it
170
            $model = new OptimizedImage();
171
            // Empty our the optimized image URLs
172
            $model->optimizedImageUrls = [];
173
            $model->optimizedWebPImageUrls = [];
174
            $model->variantSourceWidths = [];
175
            $model->placeholderWidth = 0;
176
            $model->placeholderHeight = 0;
177
            if ($asset !== null && $createVariants) {
178
                $this->populateOptimizedImageModel(
179
                    $asset,
180
                    $field->variants,
181
                    $model
182
                );
183
            }
184
            // Save our field data directly into the content table
185
            if ($field->handle !== null) {
186
                $asset->setFieldValue($field->handle, $field->serializeValue($model));
187
                $table = $asset->getContentTable();
188
                $column = $asset->getFieldColumnPrefix().$field->handle;
189
                $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset));
190
                Craft::$app->db->createCommand()
191
                    ->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...
192
                        $column => $data,
193
                    ], [
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...
194
                        'elementId' => $asset->getId(),
195
                    ], [], 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...
196
                    ->execute();
197
            }
198
        }
199
    }
200
201
    /**
202
     * Re-save all of the assets in all of the volumes
203
     *
204
     * @throws \yii\base\InvalidConfigException
205
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
206
    public function resaveAllVolumesAssets()
207
    {
208
        $volumes = Craft::$app->getVolumes()->getAllVolumes();
209
        foreach ($volumes as $volume) {
210
            if (is_subclass_of($volume, Volume::class)) {
211
                /** @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...
212
                $this->resaveVolumeAssets($volume);
213
            }
214
        }
215
    }
216
217
    /**
218
     * Re-save all of the Asset elements in the Volume $volume that have an
219
     * OptimizedImages field in the FieldLayout
220
     *
221
     * @param Volume $volume
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
222
     *
223
     * @throws \yii\base\InvalidConfigException
224
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
225
    public function resaveVolumeAssets(Volume $volume)
226
    {
227
        $needToReSave = false;
228
        /** @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...
229
        $fieldLayout = $volume->getFieldLayout();
230
        // Loop through the fields in the layout to see if there is an OptimizedImages field
231
        if ($fieldLayout) {
0 ignored issues
show
introduced by
$fieldLayout is of type craft\models\FieldLayout, thus it always evaluated to true.
Loading history...
232
            $fields = $fieldLayout->getFields();
233
            foreach ($fields as $field) {
234
                if ($field instanceof OptimizedImagesField) {
235
                    $needToReSave = true;
236
                }
237
            }
238
        }
239
        if ($needToReSave) {
240
            try {
241
                $siteId = Craft::$app->getSites()->getPrimarySite()->id;
242
            } catch (SiteNotFoundException $e) {
243
                $siteId = 0;
244
                Craft::error(
245
                    'Failed to get primary site: '.$e->getMessage(),
246
                    __METHOD__
247
                );
248
            }
249
250
            $queue = Craft::$app->getQueue();
251
            $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...
252
                'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]),
253
                'criteria' => [
254
                    'siteId' => $siteId,
255
                    'volumeId' => $volume->id,
256
                    'status' => null,
257
                    'enabledForSite' => false,
258
                ],
259
            ]));
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...
260
            Craft::debug(
261
                Craft::t(
262
                    'image-optimize',
263
                    'Started resaveVolumeAssets queue job id: {jobId}',
264
                    [
265
                        'jobId' => $jobId,
266
                    ]
267
                ),
268
                __METHOD__
269
            );
270
        }
271
    }
272
273
    /**
274
     * Re-save an individual asset
275
     *
276
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
277
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
278
    public function resaveAsset(int $id)
279
    {
280
        $queue = Craft::$app->getQueue();
281
        $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...
282
            'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]),
283
            'criteria' => [
284
                'id' => $id,
285
                'status' => null,
286
                'enabledForSite' => false,
287
            ],
288
        ]));
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...
289
        Craft::debug(
290
            Craft::t(
291
                'image-optimize',
292
                'Started resaveAsset queue job id: {jobId} Element id: {elementId}',
293
                [
294
                    'elementId' => $id,
295
                    'jobId' => $jobId,
296
                ]
297
            ),
298
            __METHOD__
299
        );
300
    }
301
302
    /**
303
     * Create an optimized SVG data uri
304
     * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
305
     *
306
     * @param string $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
307
     *
308
     * @return string
309
     */
310
    public function encodeOptimizedSVGDataUri(string $uri): string
311
    {
312
        // First, uri encode everything
313
        $uri = rawurlencode($uri);
314
        $replacements = [
315
            // remove newlines
316
            '/%0A/' => '',
317
            // put spaces back in
318
            '/%20/' => ' ',
319
            // put equals signs back in
320
            '/%3D/' => '=',
321
            // put colons back in
322
            '/%3A/' => ':',
323
            // put slashes back in
324
            '/%2F/' => '/',
325
            // replace quotes with apostrophes (may break certain SVGs)
326
            '/%22/' => "'",
327
        ];
328
        foreach ($replacements as $pattern => $replacement) {
329
            $uri = preg_replace($pattern, $replacement, $uri);
330
        }
331
332
        return $uri;
333
    }
334
335
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
336
     * @param Asset          $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
337
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
338
     * @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...
339
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
340
    protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio)
341
    {
342
        Craft::beginProfile('generatePlaceholders', __METHOD__);
343
        $settings = ImageOptimize::$plugin->getSettings();
344
        if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) {
345
            $placeholder = ImageOptimize::$plugin->placeholder;
346
            if ($element->focalPoint) {
347
                $position = $element->getFocalPoint();
348
            } else {
349
                $position = 'center-center';
350
            }
351
            $tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position);
352
            if (!empty($tempPath)) {
353
                // Generate our placeholder image
354
                $model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position);
355
                // Generate the color palette for the image
356
                if ($settings->createColorPalette) {
357
                    $model->colorPalette = $placeholder->generateColorPalette($tempPath);
358
                    $model->lightness = $placeholder->calculateLightness($model->colorPalette);
359
                }
360
                // Generate the Potrace SVG
361
                if ($settings->createPlaceholderSilhouettes) {
362
                    $model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath);
363
                }
364
                // Get rid of our placeholder image
365
                @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

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