OptimizedImages::populateOptimizedImageModel()   F
last analyzed

Complexity

Conditions 23
Paths 1068

Size

Total Lines 116
Code Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 3 Features 0
Metric Value
eloc 79
c 3
b 3
f 0
dl 0
loc 116
rs 0
cc 23
nc 1068
nop 4

How to fix   Long Method    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
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 Craft;
14
use craft\base\Component;
15
use craft\base\ElementInterface;
0 ignored issues
show
Bug introduced by
The type craft\base\ElementInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
16
use craft\base\Field;
17
use craft\console\Application as ConsoleApplication;
18
use craft\elements\Asset;
19
use craft\errors\FsObjectNotFoundException;
20
use craft\errors\InvalidFieldException;
21
use craft\errors\SiteNotFoundException;
22
use craft\helpers\Image;
23
use craft\helpers\ImageTransforms as TransformHelper;
24
use craft\helpers\Json;
25
use craft\imagetransforms\ImageTransformer;
26
use craft\models\FieldLayout;
27
use craft\models\ImageTransform as AssetTransform;
28
use craft\models\Volume;
29
use craft\records\Element_SiteSettings as Element_SiteSettingsRecord;
30
use nystudio107\imageoptimize\fields\OptimizedImages as OptimizedImagesField;
31
use nystudio107\imageoptimize\helpers\Image as ImageHelper;
32
use nystudio107\imageoptimize\ImageOptimize;
33
use nystudio107\imageoptimize\imagetransforms\CraftImageTransform;
34
use nystudio107\imageoptimize\jobs\ResaveOptimizedImages;
35
use nystudio107\imageoptimize\models\OptimizedImage;
36
use nystudio107\imageoptimize\models\Settings;
37
use Throwable;
38
use yii\base\InvalidConfigException;
39
use yii\db\Exception;
40
use function in_array;
41
42
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
43
 * @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...
44
 * @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...
45
 * @since     1.4.0
0 ignored issues
show
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
46
 */
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...
47
class OptimizedImages extends Component
48
{
49
    // Constants
50
    // =========================================================================
51
52
    // Public Properties
53
    // =========================================================================
54
55
    // Public Methods
56
    // =========================================================================
57
58
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
59
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
60
     * @param array $variants
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
61
     *
62
     * @return OptimizedImage
63
     * @throws InvalidConfigException
64
     */
65
    public function createOptimizedImages(Asset $asset, array $variants = []): OptimizedImage
66
    {
67
        Craft::beginProfile('createOptimizedImages', __METHOD__);
68
        if (empty($variants)) {
69
            /** @var ?Settings $settings */
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...
70
            $settings = ImageOptimize::$plugin->getSettings();
0 ignored issues
show
Bug introduced by
The method getSettings() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

70
            /** @scrutinizer ignore-call */ 
71
            $settings = ImageOptimize::$plugin->getSettings();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
71
            if ($settings) {
0 ignored issues
show
introduced by
$settings is of type nystudio107\imageoptimize\models\Settings, thus it always evaluated to true.
Loading history...
72
                $variants = $settings->defaultVariants;
73
            }
74
        }
75
76
        $model = new OptimizedImage();
77
        $this->populateOptimizedImageModel($asset, $variants, $model);
78
        Craft::endProfile('createOptimizedImages', __METHOD__);
79
80
        return $model;
81
    }
82
83
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
84
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Coding Style introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
85
     * @param array $variants
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
Coding Style introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
86
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
87
     * @param bool $force
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 11 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
88
     * @throws InvalidConfigException
0 ignored issues
show
Coding Style introduced by
Tag @throws cannot be grouped with parameter tags in a doc comment
Loading history...
89
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
90
    public function populateOptimizedImageModel(Asset $asset, array $variants, OptimizedImage $model, bool $force = false): void
91
    {
92
        Craft::beginProfile('populateOptimizedImageModel', __METHOD__);
93
        /** @var Settings $settings */
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...
94
        $settings = ImageOptimize::$plugin->getSettings();
95
        // Empty our the optimized image URLs
96
        $model->optimizedImageUrls = [];
97
        $model->optimizedWebPImageUrls = [];
98
        $model->variantSourceWidths = [];
99
        $model->placeholderWidth = 0;
100
        $model->placeholderHeight = 0;
101
        $model->stickyErrors = [];
102
103
        foreach ($variants as $variant) {
104
            $retinaSizes = ['1'];
105
            if (!empty($variant['retinaSizes'])) {
106
                $retinaSizes = $variant['retinaSizes'];
107
            }
108
            foreach ($retinaSizes as $retinaSize) {
109
                $finalFormat = empty($variant['format']) ? $asset->getExtension() : $variant['format'];
110
                $variantFormat = $finalFormat;
111
                if (!ImageOptimize::$plugin->transformMethod instanceof CraftImageTransform) {
112
                    $variantFormat = empty($variant['format']) ? null : $variant['format'];
113
                }
114
                $variant['format'] = $variantFormat;
115
                // Only try the transform if it's possible
116
                if ((int)$asset->height > 0
117
                    && Image::canManipulateAsImage($finalFormat)
118
                    && Image::canManipulateAsImage($asset->getExtension())
119
                ) {
120
                    // Create the transform based on the variant
121
                    /** @var AssetTransform $transform */
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
122
                    [$transform, $aspectRatio] = $this->getTransformFromVariant($asset, $variant, $retinaSize);
123
                    // If they want to $force it, set `fileExists` = 0 in the transform index, then delete the transformed image
124
                    if ($force) {
125
                        $transformer = Craft::createObject(ImageTransformer::class);
126
127
                        try {
128
                            $index = $transformer->getTransformIndex($asset, $transform);
129
                            $index->fileExists = false;
130
                            $transformer->storeTransformIndexData($index);
131
                            try {
132
                                $transformer->deleteImageTransformFile($asset, $index);
133
                            } catch (Throwable $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
134
                            }
135
                        } catch (Throwable $e) {
136
                            $msg = 'Failed to update transform: ' . $e->getMessage();
137
                            Craft::error($msg, __METHOD__);
138
                            if (Craft::$app instanceof ConsoleApplication) {
139
                                echo $msg . PHP_EOL;
140
                            }
141
                            // Add the error message to the stickyErrors for the model
142
                            $model->stickyErrors[] = $msg;
143
                        }
144
                    }
145
                    // Only create the image variant if it is not upscaled, or they are okay with it being up-scaled
146
                    if (($asset->width >= $transform->width && $asset->height >= $transform->height)
147
                        || $settings->allowUpScaledImageVariants
148
                    ) {
149
                        $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio);
150
                    }
151
                } else {
152
                    $canManipulate = Image::canManipulateAsImage($asset->getExtension());
153
                    $msg = 'Could not create transform for: ' . $asset->title
154
                        . ' - Final format: ' . $finalFormat
155
                        . ' - Element extension: ' . $asset->getExtension()
156
                        . ' - canManipulateAsImage: ' . $canManipulate;
157
                    Craft::error(
158
                        $msg,
159
                        __METHOD__
160
                    );
161
                    if (Craft::$app instanceof ConsoleApplication) {
162
                        echo $msg . PHP_EOL;
163
                    }
164
                    if ($canManipulate) {
165
                        // Add the error message to the stickyErrors for the model
166
                        $model->stickyErrors[] = $msg;
167
                    }
168
                }
169
            }
170
        }
171
172
        // If no image variants were created, populate it with the image itself
173
        if (empty($model->optimizedImageUrls)) {
174
            $finalFormat = $asset->getExtension();
175
            if ((int)$asset->height > 0
176
                && Image::canManipulateAsImage($finalFormat)
177
            ) {
178
                $variant = [
179
                    'width' => $asset->width,
180
                    'useAspectRatio' => false,
181
                    'aspectRatioX' => $asset->width,
182
                    'aspectRatioY' => $asset->height,
183
                    'retinaSizes' => ['1'],
184
                    'quality' => 0,
185
                    'format' => $finalFormat,
186
                ];
187
                [$transform, $aspectRatio] = $this->getTransformFromVariant($asset, $variant, 1);
188
                $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio);
189
            } else {
190
                $canManipulate = Image::canManipulateAsImage($asset->getExtension());
191
                $msg = 'Could not create transform for: ' . $asset->title
192
                    . ' - Final format: ' . $finalFormat
193
                    . ' - Element extension: ' . $asset->getExtension()
194
                    . ' - canManipulateAsImage: ' . $canManipulate;
195
                Craft::error(
196
                    $msg,
197
                    __METHOD__
198
                );
199
                if ($canManipulate) {
200
                    // Add the error message to the stickyErrors for the model
201
                    $model->stickyErrors[] = $msg;
202
                }
203
            }
204
        }
205
        Craft::endProfile('populateOptimizedImageModel', __METHOD__);
206
    }
207
208
    /**
209
     * Should variants be created for the given OptimizedImages field and the Asset?
210
     *
211
     * @param $field
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
212
     * @param $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
213
     * @return bool
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
214
     */
215
    public function shouldCreateVariants($field, $asset): bool
216
    {
217
        $createVariants = true;
218
        Craft::info(print_r($field->fieldVolumeSettings, true), __METHOD__);
0 ignored issues
show
Bug introduced by
It seems like print_r($field->fieldVolumeSettings, true) can also be of type true; however, parameter $message of yii\BaseYii::info() does only seem to accept array|string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

218
        Craft::info(/** @scrutinizer ignore-type */ print_r($field->fieldVolumeSettings, true), __METHOD__);
Loading history...
219
        // See if we're ignoring files in this dir
220
        if (!empty($field->fieldVolumeSettings)) {
221
            foreach ($field->fieldVolumeSettings as $volumeHandle => $subfolders) {
222
                if ($asset->getVolume()->handle === $volumeHandle) {
223
                    if (is_string($subfolders) && $subfolders === '*') {
224
                        $createVariants = true;
225
                        Craft::info("Matched '*' wildcard ", __METHOD__);
226
                    } else {
227
                        $createVariants = false;
228
                        if (is_array($subfolders)) {
229
                            foreach ($subfolders as $subfolder) {
230
                                $folder = $asset->getFolder();
231
                                while ($folder !== null && !$createVariants) {
232
                                    if ($folder->uid === $subfolder || $folder->name === $subfolder) {
233
                                        Craft::info('Matched subfolder uid: ' . print_r($subfolder, true), __METHOD__);
0 ignored issues
show
Bug introduced by
Are you sure print_r($subfolder, true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

233
                                        Craft::info('Matched subfolder uid: ' . /** @scrutinizer ignore-type */ print_r($subfolder, true), __METHOD__);
Loading history...
234
                                        $createVariants = true;
235
                                    } else {
236
                                        $folder = $folder->getParent();
237
                                    }
238
                                }
239
                            }
240
                        }
241
                    }
242
                }
243
            }
244
        }
245
        // See if we should ignore this type of file
246
        $sourceType = $asset->getMimeType();
247
        if (!empty($field->ignoreFilesOfType) && $sourceType !== null) {
248
            $ignoreTypes = array_values($field->ignoreFilesOfType);
249
            // If `image/svg` is being ignored, add `image/svg+xml` to the mime types to ignore as well
250
            if (in_array('image/svg', $ignoreTypes, false)) {
251
                $ignoreTypes[] = 'image/svg+xml';
252
            }
253
            if (in_array($sourceType, $ignoreTypes, false)) {
254
                $createVariants = false;
255
            }
256
        }
257
        return $createVariants;
258
    }
259
260
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
261
     * @param Field $field
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 12 spaces after parameter type; 1 found
Loading history...
262
     * @param ElementInterface $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
263
     * @param bool $force
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 13 spaces after parameter type; 1 found
Loading history...
264
     *
265
     * @throws Exception
266
     * @throws InvalidConfigException
267
     * @throws InvalidFieldException
268
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
269
    public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset, bool $force = false): void
270
    {
271
        /** @var Asset $asset */
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
The open comment tag must be the only content on the line
Loading history...
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
272
        if ($asset instanceof Asset && $field instanceof OptimizedImagesField) {
273
            $createVariants = $this->shouldCreateVariants($field, $asset);
274
            // Create a new OptimizedImage model and populate it
275
            $model = new OptimizedImage();
276
            // Empty our the optimized image URLs
277
            $model->optimizedImageUrls = [];
278
            $model->optimizedWebPImageUrls = [];
279
            $model->variantSourceWidths = [];
280
            $model->placeholderWidth = 0;
281
            $model->placeholderHeight = 0;
282
            if ($createVariants) {
283
                $this->populateOptimizedImageModel(
284
                    $asset,
285
                    $field->variants,
286
                    $model,
287
                    $force
288
                );
289
            }
290
            // Save the changed data directly into the elements_sites.content table
291
            if ($field->handle !== null) {
292
                $asset->setFieldValue($field->handle, $field->serializeValue($model, $asset));
293
                $fieldLayout = $asset->getFieldLayout();
294
                $siteSettingsRecords = Element_SiteSettingsRecord::findAll([
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...
295
                    'elementId' => $asset->id,
296
                ]);
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...
297
                // Update it for all of the sites
298
                foreach ($siteSettingsRecords as $siteSettingsRecord) {
299
                    // Set the field values
300
                    if ($fieldLayout) {
301
                        $content = Json::decodeIfJson($siteSettingsRecord->content);
302
                        if (!is_array($content)) {
303
                            $content = [];
304
                        }
305
                        $content[$field->layoutElement->uid] = $field->serializeValue($asset->getFieldValue($field->handle), $asset);
306
                        $siteSettingsRecord->content = $content;
307
                        // Save the site settings record
308
                        if (!$siteSettingsRecord->save(false)) {
309
                            Craft::error('Couldn’t save elements’ site settings record.', __METHOD__);
310
                        }
311
                    }
312
                }
313
            }
314
        }
315
    }
316
317
    /**
318
     * Re-save all the assets in all the volumes
319
     *
320
     * @param ?int $fieldId only for this specific id
321
     * @param bool $force Should image variants be forced to be recreated?
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
322
     *
323
     * @throws InvalidConfigException
324
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
325
    public function resaveAllVolumesAssets(?int $fieldId = null, bool $force = false): void
326
    {
327
        $volumes = Craft::$app->getVolumes()->getAllVolumes();
328
        foreach ($volumes as $volume) {
329
            $this->resaveVolumeAssets($volume, $fieldId, $force);
330
        }
331
    }
332
333
    /**
334
     * Re-save all the Asset elements in the Volume $volume that have an
335
     * OptimizedImages field in the FieldLayout
336
     *
337
     * @param Volume $volume for this volume
0 ignored issues
show
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
338
     * @param ?int $fieldId only for this specific id
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
339
     * @param bool $force Should image variants be forced to be recreated?
0 ignored issues
show
Coding Style introduced by
Expected 3 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Expected 3 spaces after parameter name; 1 found
Loading history...
340
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
341
    public function resaveVolumeAssets(Volume $volume, ?int $fieldId = null, bool $force = false): void
342
    {
343
        $needToReSave = false;
344
        /** @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...
345
        $fieldLayout = $volume->getFieldLayout();
346
        // Loop through the fields in the layout to see if there is an OptimizedImages field
347
        if ($fieldLayout) {
348
            $fields = $fieldLayout->getCustomFields();
349
            foreach ($fields as $field) {
350
                if ($field instanceof OptimizedImagesField) {
351
                    $needToReSave = true;
352
                }
353
            }
354
        }
355
        if ($needToReSave) {
356
            try {
357
                $siteId = Craft::$app->getSites()->getPrimarySite()->id;
358
            } catch (SiteNotFoundException $e) {
359
                $siteId = 0;
360
                Craft::error(
361
                    'Failed to get primary site: ' . $e->getMessage(),
362
                    __METHOD__
363
                );
364
            }
365
366
            $queue = Craft::$app->getQueue();
367
            $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...
368
                'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]),
369
                'criteria' => [
370
                    'siteId' => $siteId,
371
                    'volumeId' => $volume->id,
372
                    'status' => null,
373
                ],
374
                'fieldId' => $fieldId,
375
                'force' => $force,
376
            ]));
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...
377
            Craft::debug(
378
                Craft::t(
379
                    'image-optimize',
380
                    'Started resaveVolumeAssets queue job id: {jobId}',
381
                    [
382
                        'jobId' => $jobId,
383
                    ]
384
                ),
385
                __METHOD__
386
            );
387
        }
388
    }
389
390
    /**
391
     * Re-save an individual asset
392
     *
393
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter type; 1 found
Loading history...
394
     * @param bool $force Should image variants be forced to be recreated?
395
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
396
    public function resaveAsset(int $id, bool $force = false): void
397
    {
398
        $queue = Craft::$app->getQueue();
399
        $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...
400
            'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]),
401
            'criteria' => [
402
                'id' => $id,
403
                'status' => null,
404
            ],
405
            'force' => $force,
406
        ]));
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...
407
        Craft::debug(
408
            Craft::t(
409
                'image-optimize',
410
                'Started resaveAsset queue job id: {jobId} Element id: {elementId}',
411
                [
412
                    'elementId' => $id,
413
                    'jobId' => $jobId,
414
                ]
415
            ),
416
            __METHOD__
417
        );
418
    }
419
420
    /**
421
     * Create an optimized SVG data uri
422
     * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
423
     *
424
     * @param string $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
425
     *
426
     * @return string
427
     */
428
    public function encodeOptimizedSVGDataUri(string $uri): string
429
    {
430
        // First, uri encode everything
431
        $uri = rawurlencode($uri);
432
        $replacements = [
433
            // remove newlines
434
            '/%0A/' => '',
435
            // put equals signs back in
436
            '/%3D/' => '=',
437
            // put colons back in
438
            '/%3A/' => ':',
439
            // put slashes back in
440
            '/%2F/' => '/',
441
            // replace quotes with apostrophes (may break certain SVGs)
442
            '/%22/' => "'",
443
        ];
444
        foreach ($replacements as $pattern => $replacement) {
445
            $uri = preg_replace($pattern, $replacement, $uri);
446
        }
447
448
        return $uri;
449
    }
450
451
    // Protected Methods
452
    // =========================================================================
453
454
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
455
     * @param Asset $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 10 spaces after parameter type; 1 found
Loading history...
456
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
457
     * @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...
458
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
459
    protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio): void
460
    {
461
        Craft::beginProfile('generatePlaceholders', __METHOD__);
462
        Craft::info(
463
            'generatePlaceholders for: ' . print_r($model, true),
0 ignored issues
show
Bug introduced by
Are you sure print_r($model, true) of type string|true can be used in concatenation? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

463
            'generatePlaceholders for: ' . /** @scrutinizer ignore-type */ print_r($model, true),
Loading history...
464
            __METHOD__
465
        );
466
        /** @var Settings $settings */
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...
467
        $settings = ImageOptimize::$plugin->getSettings();
468
        if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) {
469
            $placeholder = ImageOptimize::$plugin->placeholder;
470
            if ($element->focalPoint) {
471
                $position = $element->getFocalPoint();
472
            } else {
473
                $position = 'center-center';
474
            }
475
            $tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position);
476
            if (!empty($tempPath)) {
477
                // Generate our placeholder image
478
                $model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position);
479
                // Generate the color palette for the image
480
                if ($settings->createColorPalette) {
481
                    $model->colorPalette = $placeholder->generateColorPalette($tempPath);
482
                    $model->lightness = $placeholder->calculateLightness($model->colorPalette);
0 ignored issues
show
Bug introduced by
It seems like $model->colorPalette can also be of type null; however, parameter $colors of nystudio107\imageoptimiz...r::calculateLightness() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

482
                    $model->lightness = $placeholder->calculateLightness(/** @scrutinizer ignore-type */ $model->colorPalette);
Loading history...
483
                }
484
                // Generate the Potrace SVG
485
                if ($settings->createPlaceholderSilhouettes) {
486
                    $model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath);
487
                }
488
                // Get rid of our placeholder image
489
                @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

489
                /** @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...
490
            }
491
        }
492
        Craft::endProfile('generatePlaceholders', __METHOD__);
493
    }
494
495
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
496
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
497
     * @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...
498
     * @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...
499
     *
500
     * @return array
501
     * @throws FsObjectNotFoundException
502
     */
503
    protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array
504
    {
505
        /** @var Settings $settings */
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...
506
        $settings = ImageOptimize::$plugin->getSettings();
507
        $transform = new AssetTransform();
508
        $transform->format = $variant['format'] ?? null;
509
        // Handle animate .gif images by never changing the format
510
        $images = Craft::$app->getImages();
511
        if ($asset->extension === 'gif' && !$images->getIsGd()) {
512
            $imageSource = TransformHelper::getLocalImageSource($asset);
513
            try {
514
                if (ImageHelper::getIsAnimatedGif($imageSource)) {
515
                    $transform->format = null;
516
                }
517
            } catch (\Exception $e) {
518
                Craft::error($e->getMessage(), __METHOD__);
519
            }
520
        }
521
        $useAspectRatio = $variant['useAspectRatio'] ?? false;
522
        if ($useAspectRatio) {
523
            $aspectRatio = (float)$variant['aspectRatioX'] / (float)$variant['aspectRatioY'];
524
        } else {
525
            $aspectRatio = (float)$asset->width / (float)$asset->height;
526
        }
527
        $width = (int)$variant['width'] * (int)$retinaSize;
528
        $transform->width = $width;
529
        $transform->height = (int)($width / $aspectRatio);
530
        // Image quality
531
        $quality = (int)($variant['quality'] ?? null);
532
        if (empty($quality)) {
533
            $quality = null;
534
        }
535
        if ($quality !== null && $settings->lowerQualityRetinaImageVariants && $retinaSize != '1') {
536
            $quality = (int)($quality * (1.5 / (int)$retinaSize));
537
        }
538
        $transform->quality = $quality;
539
        // Interlaced (progressive JPEGs or interlaced PNGs)
540
        if (property_exists($transform, 'interlace')) {
541
            $transform->interlace = 'line';
542
        }
543
544
        return [$transform, $aspectRatio];
545
    }
546
547
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
548
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by