Passed
Push — develop ( b34520...582419 )
by Andrew
06:48
created

OptimizedImages   D

Complexity

Total Complexity 59

Size/Duplication

Total Lines 431
Duplicated Lines 0 %

Importance

Changes 14
Bugs 0 Features 0
Metric Value
wmc 59
eloc 219
c 14
b 0
f 0
dl 0
loc 431
rs 4.08

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) {
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) {
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
__METHOD__);
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected ')' on line 175 at column 10
Loading history...
Coding Style introduced by
Line indented incorrectly; expected at least 36 spaces, found 0
Loading history...
176
                                    if ($asset->getFolder()->uid === $subfolder) {
177
                                        Craft::info('Matched subfolder uid: '.print_r($subfolder, true), __METHOD__);
178
                                        $createVariants = true;
179
                                    }
180
                                }
181
                            }
182
                        }
183
                    }
184
                }
185
            }
186
            // See if we should ignore this type of file
187
            $sourceType = $asset->getMimeType();
188
            if (!empty($field->ignoreFilesOfType) && $sourceType !== null) {
189
                if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) {
190
                    $createVariants = false;
191
                }
192
            }
193
            Craft::info(print_r($sourceType, true), 'image-optimize');
194
            // Create a new OptimizedImage model and populate it
195
            $model = new OptimizedImage();
196
            // Empty our the optimized image URLs
197
            $model->optimizedImageUrls = [];
198
            $model->optimizedWebPImageUrls = [];
199
            $model->variantSourceWidths = [];
200
            $model->placeholderWidth = 0;
201
            $model->placeholderHeight = 0;
202
            if ($asset !== null && $createVariants) {
203
                $this->populateOptimizedImageModel(
204
                    $asset,
205
                    $field->variants,
206
                    $model
207
                );
208
            }
209
            // Save our field data directly into the content table
210
            if ($field->handle !== null) {
211
                $asset->setFieldValue($field->handle, $field->serializeValue($model));
212
                $table = $asset->getContentTable();
213
                $column = $asset->getFieldColumnPrefix().$field->handle;
214
                $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset));
215
                Craft::$app->db->createCommand()
216
                    ->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...
217
                        $column => $data,
218
                    ], [
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...
219
                        'elementId' => $asset->getId(),
220
                    ], [], 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...
221
                    ->execute();
222
            }
223
        }
224
    }
225
226
    /**
227
     * Re-save all of the assets in all of the volumes
228
     *
229
     * @throws \yii\base\InvalidConfigException
230
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
231
    public function resaveAllVolumesAssets()
232
    {
233
        $volumes = Craft::$app->getVolumes()->getAllVolumes();
234
        foreach ($volumes as $volume) {
235
            if (is_subclass_of($volume, Volume::class)) {
236
                /** @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...
237
                $this->resaveVolumeAssets($volume);
238
            }
239
        }
240
    }
241
242
    /**
243
     * Re-save all of the Asset elements in the Volume $volume that have an
244
     * OptimizedImages field in the FieldLayout
245
     *
246
     * @param Volume $volume
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
247
     *
248
     * @throws \yii\base\InvalidConfigException
249
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
250
    public function resaveVolumeAssets(Volume $volume)
251
    {
252
        $needToReSave = false;
253
        /** @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...
254
        $fieldLayout = $volume->getFieldLayout();
255
        // Loop through the fields in the layout to see if there is an OptimizedImages field
256
        if ($fieldLayout) {
257
            $fields = $fieldLayout->getFields();
258
            foreach ($fields as $field) {
259
                if ($field instanceof OptimizedImagesField) {
260
                    $needToReSave = true;
261
                }
262
            }
263
        }
264
        if ($needToReSave) {
265
            try {
266
                $siteId = Craft::$app->getSites()->getPrimarySite()->id;
267
            } catch (SiteNotFoundException $e) {
268
                $siteId = 0;
269
                Craft::error(
270
                    'Failed to get primary site: '.$e->getMessage(),
271
                    __METHOD__
272
                );
273
            }
274
275
            $queue = Craft::$app->getQueue();
276
            $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...
277
                'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]),
278
                'criteria' => [
279
                    'siteId' => $siteId,
280
                    'volumeId' => $volume->id,
281
                    'status' => null,
282
                    'enabledForSite' => false,
283
                ],
284
            ]));
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...
285
            Craft::debug(
286
                Craft::t(
287
                    'image-optimize',
288
                    'Started resaveVolumeAssets queue job id: {jobId}',
289
                    [
290
                        'jobId' => $jobId,
291
                    ]
292
                ),
293
                __METHOD__
294
            );
295
        }
296
    }
297
298
    /**
299
     * Re-save an individual asset
300
     *
301
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
302
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
303
    public function resaveAsset(int $id)
304
    {
305
        $queue = Craft::$app->getQueue();
306
        $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...
307
            'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]),
308
            'criteria' => [
309
                'id' => $id,
310
                'status' => null,
311
                'enabledForSite' => false,
312
            ],
313
        ]));
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...
314
        Craft::debug(
315
            Craft::t(
316
                'image-optimize',
317
                'Started resaveAsset queue job id: {jobId} Element id: {elementId}',
318
                [
319
                    'elementId' => $id,
320
                    'jobId' => $jobId,
321
                ]
322
            ),
323
            __METHOD__
324
        );
325
    }
326
327
    /**
328
     * Create an optimized SVG data uri
329
     * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
330
     *
331
     * @param string $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
332
     *
333
     * @return string
334
     */
335
    public function encodeOptimizedSVGDataUri(string $uri): string
336
    {
337
        // First, uri encode everything
338
        $uri = rawurlencode($uri);
339
        $replacements = [
340
            // remove newlines
341
            '/%0A/' => '',
342
            // put spaces back in
343
            '/%20/' => ' ',
344
            // put equals signs back in
345
            '/%3D/' => '=',
346
            // put colons back in
347
            '/%3A/' => ':',
348
            // put slashes back in
349
            '/%2F/' => '/',
350
            // replace quotes with apostrophes (may break certain SVGs)
351
            '/%22/' => "'",
352
        ];
353
        foreach ($replacements as $pattern => $replacement) {
354
            $uri = preg_replace($pattern, $replacement, $uri);
355
        }
356
357
        return $uri;
358
    }
359
360
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
361
     * @param Asset          $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
362
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
363
     * @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...
364
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
365
    protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio)
366
    {
367
        Craft::beginProfile('generatePlaceholders', __METHOD__);
368
        $settings = ImageOptimize::$plugin->getSettings();
369
        if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) {
370
            $placeholder = ImageOptimize::$plugin->placeholder;
371
            if ($element->focalPoint) {
372
                $position = $element->getFocalPoint();
373
            } else {
374
                $position = 'center-center';
375
            }
376
            $tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position);
377
            if (!empty($tempPath)) {
378
                // Generate our placeholder image
379
                $model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position);
380
                // Generate the color palette for the image
381
                if ($settings->createColorPalette) {
382
                    $model->colorPalette = $placeholder->generateColorPalette($tempPath);
383
                    $model->lightness = $placeholder->calculateLightness($model->colorPalette);
384
                }
385
                // Generate the Potrace SVG
386
                if ($settings->createPlaceholderSilhouettes) {
387
                    $model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath);
388
                }
389
                // Get rid of our placeholder image
390
                @unlink($tempPath);
391
            }
392
        }
393
        Craft::endProfile('generatePlaceholders', __METHOD__);
394
    }
395
396
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
397
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
398
     * @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...
399
     * @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...
400
     *
401
     * @return array
402
     */
403
    protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array
404
    {
405
        $settings = ImageOptimize::$plugin->getSettings();
406
        $transform = new AssetTransform();
407
        $transform->format = $variant['format'] ?? null;
408
        // Handle animate .gif images by never changing the format
409
        $images = Craft::$app->getImages();
410
        if ($asset->extension === 'gif' && !$images->getIsGd()) {
411
            $imageSource = $asset->getTransformSource();
412
            try {
413
                if (ImageHelper::getIsAnimatedGif($imageSource)) {
414
                    $transform->format = null;
415
                }
416
            } catch (ImageException $e) {
417
                Craft::error($e->getMessage(), __METHOD__);
418
            } catch (InvalidConfigException $e) {
419
                Craft::error($e->getMessage(), __METHOD__);
420
            }
421
        }
422
        $useAspectRatio = $variant['useAspectRatio'] ?? true;
423
        if ($useAspectRatio) {
424
            $aspectRatio = $variant['aspectRatioX'] / $variant['aspectRatioY'];
425
        } else {
426
            $aspectRatio = $asset->width / $asset->height;
427
        }
428
        $width = $variant['width'] * $retinaSize;
429
        $transform->width = $width;
430
        $transform->height = (int)($width / $aspectRatio);
431
        // Image quality
432
        $quality = $variant['quality'] ?? null;
433
        if ($settings->lowerQualityRetinaImageVariants && $retinaSize != '1') {
434
            $quality = (int)($quality * (1.5 / (int)$retinaSize));
435
        }
436
        $transform->quality = $quality;
437
        // Interlaced (progressive JPEGs or interlaced PNGs)
438
        if (property_exists($transform, 'interlace')) {
439
            $transform->interlace = 'line';
440
        }
441
442
        return [$transform, $aspectRatio];
443
    }
444
445
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
446
     * @param Asset          $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
447
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
448
     * @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...
449
     * @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...
450
     * @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...
451
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
452
    protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio)
453
    {
454
        Craft::beginProfile('addVariantImageToModel', __METHOD__);
455
        // Generate an image transform url
456
        $url = ImageOptimize::$plugin->transformMethod->getTransformUrl(
457
            $asset,
458
            $transform
459
        );
460
        Craft::info(
461
            'URL created: '.print_r($url, true),
462
            __METHOD__
463
        );
464
        // Update the model
465
        if (!empty($url)) {
466
            $model->variantSourceWidths[] = $variant['width'];
467
            $model->variantHeights[$transform->width] = $asset->getHeight($transform);
468
            // Store & prefetch image at the image URL
469
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($url);
470
            $model->optimizedImageUrls[$transform->width] = $url;
471
            // Store & prefetch image at the webp URL
472
            $webPUrl = ImageOptimize::$plugin->transformMethod->getWebPUrl(
473
                $url,
474
                $asset,
475
                $transform
476
            );
477
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($webPUrl);
478
            $model->optimizedWebPImageUrls[$transform->width] = $webPUrl;
479
            $model->focalPoint = $asset->focalPoint;
480
            $model->originalImageWidth = $asset->width;
481
            $model->originalImageHeight = $asset->height;
482
            // Make our placeholder image once, from the first variant
483
            if (!$model->placeholderWidth) {
484
                $model->placeholderWidth = $transform->width;
485
                $model->placeholderHeight = $transform->height;
486
                $this->generatePlaceholders($asset, $model, $aspectRatio);
487
            }
488
            Craft::info(
489
                'Created transforms for variant: '.print_r($variant, true),
490
                __METHOD__
491
            );
492
        }
493
        Craft::endProfile('addVariantImageToModel', __METHOD__);
494
    }
495
}
496