Passed
Push — v1 ( 47c11d...06f464 )
by Andrew
18:55 queued 09:51
created

OptimizedImages::resaveVolumeAssets()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 46
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 31
c 1
b 0
f 0
dl 0
loc 46
rs 8.8017
cc 6
nc 6
nop 3
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\console\Application as ConsoleApplication;
25
use craft\elements\Asset;
26
use craft\errors\ImageException;
27
use craft\errors\SiteNotFoundException;
28
use craft\helpers\Image;
29
use craft\helpers\Json;
30
use craft\models\AssetTransform;
31
use craft\models\FieldLayout;
32
33
use yii\base\InvalidConfigException;
34
35
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
36
 * @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...
37
 * @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...
38
 * @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...
39
 */
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...
40
class OptimizedImages extends Component
41
{
42
    // Constants
43
    // =========================================================================
44
45
    // Public Properties
46
    // =========================================================================
47
48
    // Public Methods
49
    // =========================================================================
50
51
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
52
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
53
     * @param array $variants
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
54
     *
55
     * @return OptimizedImage|null
56
     */
57
    public function createOptimizedImages(Asset $asset, array $variants = [])
58
    {
59
        Craft::beginProfile('createOptimizedImages', __METHOD__);
60
        if (empty($variants)) {
61
            $settings = ImageOptimize::$plugin->getSettings();
62
            if ($settings) {
0 ignored issues
show
introduced by
$settings is of type nystudio107\imageoptimize\models\Settings, thus it always evaluated to true.
Loading history...
63
                $variants = $settings->defaultVariants;
64
            }
65
        }
66
67
        $model = new OptimizedImage();
68
        $this->populateOptimizedImageModel($asset, $variants, $model);
69
        Craft::endProfile('createOptimizedImages', __METHOD__);
70
71
        return $model;
72
    }
73
74
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
75
     * @param Asset          $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
76
     * @param array          $variants
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
77
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
78
     * @param boolean        $force
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
79
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
80
    public function populateOptimizedImageModel(Asset $asset, $variants, OptimizedImage $model, $force = false)
81
    {
82
        Craft::beginProfile('populateOptimizedImageModel', __METHOD__);
83
        $settings = ImageOptimize::$plugin->getSettings();
84
        // Empty our the optimized image URLs
85
        $model->optimizedImageUrls = [];
86
        $model->optimizedWebPImageUrls = [];
87
        $model->variantSourceWidths = [];
88
        $model->placeholderWidth = 0;
89
        $model->placeholderHeight = 0;
90
91
        foreach ($variants as $variant) {
92
            $retinaSizes = ['1'];
93
            if (!empty($variant['retinaSizes'])) {
94
                $retinaSizes = $variant['retinaSizes'];
95
            }
96
            foreach ($retinaSizes as $retinaSize) {
97
                $finalFormat = empty($variant['format']) ? $asset->getExtension() : $variant['format'];
98
                // Only try the transform if it's possible
99
                if (Image::canManipulateAsImage($finalFormat)
100
                    && Image::canManipulateAsImage($asset->getExtension())
101
                    && $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...
102
                    // Create the transform based on the variant
103
                    /** @var AssetTransform $transform */
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...
104
                    list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, $retinaSize);
105
                    // If they want to $force it, set `fileExists` = 0 in the transform index, then delete the transformed image
106
                    if ($force) {
107
                        $transforms = Craft::$app->getAssetTransforms();
108
                        try {
109
                            $index = $transforms->getTransformIndex($asset, $transform);
110
                            $index->fileExists = 0;
0 ignored issues
show
Documentation Bug introduced by
The property $fileExists was declared of type boolean, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
111
                            $transforms->storeTransformIndexData($index);
112
                            $volume = $asset->getVolume();
113
                            $transformPath = $asset->folderPath . $transforms->getTransformSubpath($asset, $index);
114
                            try {
115
                                $volume->deleteFile($transformPath);
116
                            } catch (\Throwable $exception) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
117
                            }
118
                        } catch (\Throwable $e) {
119
                            $msg = 'Failed to update transform: '.$e->getMessage();
120
                            Craft::error($msg, __METHOD__);
121
                            if (Craft::$app instanceof ConsoleApplication) {
122
                                echo $msg . PHP_EOL;
123
                            }
124
                        }
125
                    }
126
                    // Only create the image variant if it is not upscaled, or they are okay with it being up-scaled
127
                    if (($asset->width >= $transform->width && $asset->height >= $transform->height)
128
                        || $settings->allowUpScaledImageVariants
129
                    ) {
130
                        $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio);
131
                    }
132
                } else {
133
                    $msg = 'Could not create transform for: '.$asset->title
134
                        .' - Final format: '.$finalFormat
135
                        .' - Element extension: '.$asset->getExtension()
136
                        .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension())
0 ignored issues
show
Coding Style introduced by
Space after closing parenthesis of function call prohibited
Loading history...
137
                        ;
138
                    Craft::error(
139
                        $msg,
140
                        __METHOD__
141
                    );
142
                    if (Craft::$app instanceof ConsoleApplication) {
143
                        echo $msg . PHP_EOL;
144
                    }
145
                }
146
            }
147
        }
148
149
        // If no image variants were created, populate it with the image itself
150
        if (empty($model->optimizedImageUrls)) {
151
            $finalFormat = $asset->getExtension();
152
            if (Image::canManipulateAsImage($finalFormat)
153
                && Image::canManipulateAsImage($finalFormat)
154
                && $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...
155
                $variant = [
156
                    'width' => $asset->width,
157
                    'useAspectRatio' => false,
158
                    'aspectRatioX' => $asset->width,
159
                    'aspectRatioY' => $asset->height,
160
                    'retinaSizes' => ['1'],
161
                    'quality' => 0,
162
                ];
163
                list($transform, $aspectRatio) = $this->getTransformFromVariant($asset, $variant, 1);
164
                $this->addVariantImageToModel($asset, $model, $transform, $variant, $aspectRatio);
165
            } else {
166
                Craft::error(
167
                    'Could not create transform for: '.$asset->title
168
                    .' - Final format: '.$finalFormat
169
                    .' - Element extension: '.$asset->getExtension()
170
                    .' - canManipulateAsImage: '.Image::canManipulateAsImage($asset->getExtension()),
171
                    __METHOD__
172
                );
173
            }
174
        }
175
        Craft::endProfile('populateOptimizedImageModel', __METHOD__);
176
    }
177
178
    /**
179
     * Should variants be created for the given OptimizedImages field and the Asset?
180
     *
181
     * @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...
182
     * @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...
183
     * @return bool
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
184
     */
185
    public function shouldCreateVariants($field, $asset): bool
186
    {
187
        $createVariants = true;
188
        Craft::info(print_r($field->fieldVolumeSettings, true), __METHOD__);
189
        // See if we're ignoring files in this dir
190
        if (!empty($field->fieldVolumeSettings)) {
191
            foreach ($field->fieldVolumeSettings as $volumeHandle => $subfolders) {
192
                if ($asset->getVolume()->handle === $volumeHandle) {
193
                    if (is_string($subfolders) && $subfolders === '*') {
194
                        $createVariants = true;
195
                        Craft::info("Matched '*' wildcard ", __METHOD__);
196
                    } else {
197
                        $createVariants = false;
198
                        if (is_array($subfolders)) {
199
                            foreach ($subfolders as $subfolder) {
200
                                $folder = $asset->getFolder();
201
                                while ($folder !== null && !$createVariants) {
202
                                    if ($folder->uid === $subfolder) {
203
                                        Craft::info('Matched subfolder uid: ' . print_r($subfolder, true), __METHOD__);
204
                                        $createVariants = true;
205
                                    } else {
206
                                        $folder = $folder->getParent();
207
                                    }
208
                                }
209
                            }
210
                        }
211
                    }
212
                }
213
            }
214
        }
215
        // See if we should ignore this type of file
216
        $sourceType = $asset->getMimeType();
217
        if (!empty($field->ignoreFilesOfType) && $sourceType !== null) {
218
            if (\in_array($sourceType, array_values($field->ignoreFilesOfType), false)) {
219
                $createVariants = false;
220
            }
221
        }
222
        return $createVariants;
223
    }
224
225
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
226
     * @param Field            $field
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
227
     * @param ElementInterface $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
228
     * @param boolean          $force
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
229
     *
230
     * @throws \yii\db\Exception
231
     * @throws InvalidConfigException
232
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
233
    public function updateOptimizedImageFieldData(Field $field, ElementInterface $asset, $force = false)
234
    {
235
        /** @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...
236
        if ($asset instanceof Asset && $field instanceof OptimizedImagesField) {
237
            $createVariants = $this->shouldCreateVariants($field, $asset);
238
            // Create a new OptimizedImage model and populate it
239
            $model = new OptimizedImage();
240
            // Empty our the optimized image URLs
241
            $model->optimizedImageUrls = [];
242
            $model->optimizedWebPImageUrls = [];
243
            $model->variantSourceWidths = [];
244
            $model->placeholderWidth = 0;
245
            $model->placeholderHeight = 0;
246
            if ($asset !== null && $createVariants) {
247
                $this->populateOptimizedImageModel(
248
                    $asset,
249
                    $field->variants,
250
                    $model,
251
                    $force
252
                );
253
            }
254
            // Save our field data directly into the content table
255
            if ($field->handle !== null) {
256
                $asset->setFieldValue($field->handle, $field->serializeValue($model));
257
                $table = $asset->getContentTable();
258
                $column = $asset->getFieldColumnPrefix().$field->handle;
259
                $data = Json::encode($field->serializeValue($asset->getFieldValue($field->handle), $asset));
260
                Craft::$app->db->createCommand()
261
                    ->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...
262
                        $column => $data,
263
                    ], [
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...
264
                        'elementId' => $asset->getId(),
265
                    ], [], 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...
266
                    ->execute();
267
            }
268
        }
269
    }
270
271
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $force should have a doc-comment as per coding-style.
Loading history...
272
     * Re-save all of the assets in all of the volumes
273
     *
274
     * @param int|null $fieldId only for this specific id
0 ignored issues
show
Coding Style introduced by
Expected 49 spaces after parameter type; 1 found
Loading history...
275
     * @param boolean Should image variants be forced to be recreated?
0 ignored issues
show
Bug introduced by
The type nystudio107\imageoptimize\services\Should 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...
Coding Style Documentation introduced by
Missing parameter name
Loading history...
276
     *
277
     * @throws \yii\base\InvalidConfigException
278
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
279
    public function resaveAllVolumesAssets($fieldId = null, $force = false)
280
    {
281
        $volumes = Craft::$app->getVolumes()->getAllVolumes();
282
        foreach ($volumes as $volume) {
283
            if (is_subclass_of($volume, Volume::class)) {
284
                /** @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...
285
                $this->resaveVolumeAssets($volume, $fieldId, $force);
286
            }
287
        }
288
    }
289
290
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $force should have a doc-comment as per coding-style.
Loading history...
291
     * Re-save all of the Asset elements in the Volume $volume that have an
292
     * OptimizedImages field in the FieldLayout
293
     *
294
     * @param Volume $volume for this volume
0 ignored issues
show
Coding Style introduced by
Expected 51 spaces after parameter type; 1 found
Loading history...
Coding Style introduced by
Expected 2 spaces after parameter name; 1 found
Loading history...
295
     * @param int|null $fieldId only for this specific id
0 ignored issues
show
Coding Style introduced by
Expected 49 spaces after parameter type; 1 found
Loading history...
296
     * @param boolean Should image variants be forced to be recreated?
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
297
     *
298
     * @throws InvalidConfigException
299
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
300
    public function resaveVolumeAssets(Volume $volume, $fieldId = null, $force = false)
301
    {
302
        $needToReSave = false;
303
        /** @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...
304
        $fieldLayout = $volume->getFieldLayout();
305
        // Loop through the fields in the layout to see if there is an OptimizedImages field
306
        if ($fieldLayout) {
0 ignored issues
show
introduced by
$fieldLayout is of type craft\models\FieldLayout, thus it always evaluated to true.
Loading history...
307
            $fields = $fieldLayout->getFields();
308
            foreach ($fields as $field) {
309
                if ($field instanceof OptimizedImagesField) {
310
                    $needToReSave = true;
311
                }
312
            }
313
        }
314
        if ($needToReSave) {
315
            try {
316
                $siteId = Craft::$app->getSites()->getPrimarySite()->id;
317
            } catch (SiteNotFoundException $e) {
318
                $siteId = 0;
319
                Craft::error(
320
                    'Failed to get primary site: '.$e->getMessage(),
321
                    __METHOD__
322
                );
323
            }
324
325
            $queue = Craft::$app->getQueue();
326
            $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...
327
                'description' => Craft::t('image-optimize', 'Optimizing images in {name}', ['name' => $volume->name]),
328
                'criteria' => [
329
                    'siteId' => $siteId,
330
                    'volumeId' => $volume->id,
331
                    'status' => null,
332
                    'enabledForSite' => false,
333
                ],
334
                'fieldId' => $fieldId,
335
                'force' => $force,
336
            ]));
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...
337
            Craft::debug(
338
                Craft::t(
339
                    'image-optimize',
340
                    'Started resaveVolumeAssets queue job id: {jobId}',
341
                    [
342
                        'jobId' => $jobId,
343
                    ]
344
                ),
345
                __METHOD__
346
            );
347
        }
348
    }
349
350
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $force should have a doc-comment as per coding-style.
Loading history...
351
     * Re-save an individual asset
352
     *
353
     * @param int $id
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Expected 54 spaces after parameter type; 1 found
Loading history...
354
     * @param boolean Should image variants be forced to be recreated?
0 ignored issues
show
Coding Style Documentation introduced by
Missing parameter name
Loading history...
355
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
356
    public function resaveAsset(int $id, $force = false)
357
    {
358
        $queue = Craft::$app->getQueue();
359
        $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...
360
            'description' => Craft::t('image-optimize', 'Optimizing image id {id}', ['id' => $id]),
361
            'criteria' => [
362
                'id' => $id,
363
                'status' => null,
364
                'enabledForSite' => false,
365
            ],
366
            'force' => $force,
367
        ]));
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...
368
        Craft::debug(
369
            Craft::t(
370
                'image-optimize',
371
                'Started resaveAsset queue job id: {jobId} Element id: {elementId}',
372
                [
373
                    'elementId' => $id,
374
                    'jobId' => $jobId,
375
                ]
376
            ),
377
            __METHOD__
378
        );
379
    }
380
381
    /**
382
     * Create an optimized SVG data uri
383
     * See: https://codepen.io/tigt/post/optimizing-svgs-in-data-uris
384
     *
385
     * @param string $uri
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
386
     *
387
     * @return string
388
     */
389
    public function encodeOptimizedSVGDataUri(string $uri): string
390
    {
391
        // First, uri encode everything
392
        $uri = rawurlencode($uri);
393
        $replacements = [
394
            // remove newlines
395
            '/%0A/' => '',
396
            // put spaces back in
397
            '/%20/' => ' ',
398
            // put equals signs back in
399
            '/%3D/' => '=',
400
            // put colons back in
401
            '/%3A/' => ':',
402
            // put slashes back in
403
            '/%2F/' => '/',
404
            // replace quotes with apostrophes (may break certain SVGs)
405
            '/%22/' => "'",
406
        ];
407
        foreach ($replacements as $pattern => $replacement) {
408
            $uri = preg_replace($pattern, $replacement, $uri);
409
        }
410
411
        return $uri;
412
    }
413
414
    // Protected Methods
415
    // =========================================================================
416
417
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
418
     * @param Asset          $element
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
419
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
420
     * @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...
421
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
422
    protected function generatePlaceholders(Asset $element, OptimizedImage $model, $aspectRatio)
423
    {
424
        Craft::beginProfile('generatePlaceholders', __METHOD__);
425
        $settings = ImageOptimize::$plugin->getSettings();
426
        if ($settings->generatePlaceholders && ImageOptimize::$generatePlaceholders) {
427
            $placeholder = ImageOptimize::$plugin->placeholder;
428
            if ($element->focalPoint) {
429
                $position = $element->getFocalPoint();
430
            } else {
431
                $position = 'center-center';
432
            }
433
            $tempPath = $placeholder->createTempPlaceholderImage($element, $aspectRatio, $position);
434
            if (!empty($tempPath)) {
435
                // Generate our placeholder image
436
                $model->placeholder = $placeholder->generatePlaceholderImage($tempPath, $aspectRatio, $position);
437
                // Generate the color palette for the image
438
                if ($settings->createColorPalette) {
439
                    $model->colorPalette = $placeholder->generateColorPalette($tempPath);
440
                    $model->lightness = $placeholder->calculateLightness($model->colorPalette);
441
                }
442
                // Generate the Potrace SVG
443
                if ($settings->createPlaceholderSilhouettes) {
444
                    $model->placeholderSvg = $placeholder->generatePlaceholderSvg($tempPath);
445
                }
446
                // Get rid of our placeholder image
447
                @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

447
                /** @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...
448
            }
449
        }
450
        Craft::endProfile('generatePlaceholders', __METHOD__);
451
    }
452
453
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
454
     * @param Asset $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
455
     * @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...
456
     * @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...
457
     *
458
     * @return array
459
     */
460
    protected function getTransformFromVariant(Asset $asset, $variant, $retinaSize): array
461
    {
462
        $settings = ImageOptimize::$plugin->getSettings();
463
        $transform = new AssetTransform();
464
        $transform->format = $variant['format'] ?? null;
465
        // Handle animate .gif images by never changing the format
466
        $images = Craft::$app->getImages();
467
        if ($asset->extension === 'gif' && !$images->getIsGd()) {
468
            $imageSource = $asset->getTransformSource();
469
            try {
470
                if (ImageHelper::getIsAnimatedGif($imageSource)) {
471
                    $transform->format = null;
472
                }
473
            } catch (ImageException $e) {
474
                Craft::error($e->getMessage(), __METHOD__);
475
            } catch (InvalidConfigException $e) {
476
                Craft::error($e->getMessage(), __METHOD__);
477
            }
478
        }
479
        $useAspectRatio = $variant['useAspectRatio'] ?? false;
480
        if ($useAspectRatio) {
481
            $aspectRatio = (int)$variant['aspectRatioX'] / (int)$variant['aspectRatioY'];
482
        } else {
483
            $aspectRatio = (int)$asset->width / (int)$asset->height;
484
        }
485
        $width = (int)$variant['width'] * (int)$retinaSize;
486
        $transform->width = $width;
487
        $transform->height = (int)($width / $aspectRatio);
488
        // Image quality
489
        $quality = (int)($variant['quality'] ?? null);
490
        if (empty($quality)) {
491
            $quality = null;
492
        }
493
        if ($quality !== null && $settings->lowerQualityRetinaImageVariants && $retinaSize != '1') {
494
            $quality = (int)($quality * (1.5 / (int)$retinaSize));
495
        }
496
        $transform->quality = $quality;
497
        // Interlaced (progressive JPEGs or interlaced PNGs)
498
        if (property_exists($transform, 'interlace')) {
499
            $transform->interlace = 'line';
500
        }
501
502
        return [$transform, $aspectRatio];
503
    }
504
505
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
506
     * @param Asset          $asset
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
507
     * @param OptimizedImage $model
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
508
     * @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...
509
     * @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...
510
     * @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...
511
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
512
    protected function addVariantImageToModel(Asset $asset, OptimizedImage $model, $transform, $variant, $aspectRatio)
513
    {
514
        Craft::beginProfile('addVariantImageToModel', __METHOD__);
515
        // Generate an image transform url
516
        $url = ImageOptimize::$plugin->transformMethod->getTransformUrl(
517
            $asset,
518
            $transform
519
        );
520
        Craft::info(
521
            'URL created: '.print_r($url, true),
522
            __METHOD__
523
        );
524
        // Update the model
525
        if (!empty($url)) {
526
            $model->variantSourceWidths[] = $variant['width'];
527
            $model->variantHeights[$transform->width] = $asset->getHeight($transform);
528
            // Store & prefetch image at the image URL
529
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($url);
530
            $model->optimizedImageUrls[$transform->width] = $url;
531
            // Store & prefetch image at the webp URL
532
            $webPUrl = ImageOptimize::$plugin->transformMethod->getWebPUrl(
533
                $url,
534
                $asset,
535
                $transform
536
            );
537
            //ImageOptimize::$plugin->transformMethod->prefetchRemoteFile($webPUrl);
538
            $model->optimizedWebPImageUrls[$transform->width] = $webPUrl;
539
            $model->focalPoint = $asset->focalPoint;
0 ignored issues
show
Documentation Bug introduced by
It seems like $asset->focalPoint can also be of type string. However, the property $focalPoint is declared as type array<mixed,double>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
540
            $model->originalImageWidth = $asset->width;
541
            $model->originalImageHeight = $asset->height;
542
            // Make our placeholder image once, from the first variant
543
            if (!$model->placeholderWidth) {
544
                $model->placeholderWidth = $transform->width;
545
                $model->placeholderHeight = $transform->height;
546
                $this->generatePlaceholders($asset, $model, $aspectRatio);
547
            }
548
            Craft::info(
549
                'Created transforms for variant: '.print_r($variant, true),
550
                __METHOD__
551
            );
552
        }
553
        Craft::endProfile('addVariantImageToModel', __METHOD__);
554
    }
555
}
556