Passed
Push — develop ( ad1149...471caf )
by Andrew
08:50 queued 03:44
created

OptimizedImages::afterElementSave()   B

Complexity

Conditions 11
Paths 5

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 2 Features 0
Metric Value
eloc 18
c 9
b 2
f 0
dl 0
loc 34
rs 7.3166
cc 11
nc 5
nop 2

How to fix   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
 * Image Optimize 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\fields;
12
13
use Craft;
14
use craft\base\ElementInterface;
15
use craft\base\Field;
16
use craft\base\Volume;
17
use craft\elements\Asset;
18
use craft\fields\Matrix;
19
use craft\helpers\Html;
20
use craft\helpers\Json;
21
use craft\models\FieldLayout;
22
use craft\validators\ArrayValidator;
23
use nystudio107\imageoptimize\assetbundles\imageoptimize\ImageOptimizeAsset;
24
use nystudio107\imageoptimize\fields\OptimizedImages as OptimizedImagesField;
25
use nystudio107\imageoptimize\gql\types\generators\OptimizedImagesGenerator;
26
use nystudio107\imageoptimize\ImageOptimize;
27
use nystudio107\imageoptimize\models\OptimizedImage;
28
use ReflectionClass;
29
use ReflectionException;
30
use Twig\Error\LoaderError;
31
use verbb\supertable\fields\SuperTableField;
0 ignored issues
show
Bug introduced by
The type verbb\supertable\fields\SuperTableField 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...
32
use yii\base\InvalidConfigException;
33
use yii\db\Exception;
34
use yii\db\Schema;
35
use function is_array;
36
use function is_string;
37
38
/** @noinspection MissingPropertyAnnotationsInspection */
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...
39
40
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
41
 * @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...
42
 * @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...
43
 * @since     1.2.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...
44
 */
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...
45
class OptimizedImages extends Field
46
{
47
    // Constants
48
    // =========================================================================
49
50
    const DEFAULT_ASPECT_RATIOS = [
51
        ['x' => 16, 'y' => 9],
52
    ];
53
    const DEFAULT_IMAGE_VARIANTS = [
54
        [
55
            'width' => 1200,
56
            'useAspectRatio' => true,
57
            'aspectRatioX' => 16.0,
58
            'aspectRatioY' => 9.0,
59
            'retinaSizes' => ['1'],
60
            'quality' => 82,
61
            'format' => 'jpg',
62
        ],
63
    ];
64
65
    const MAX_VOLUME_SUBFOLDERS = 30;
66
67
    // Public Properties
68
    // =========================================================================
69
70
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
71
     * @var array
72
     */
73
    public $fieldVolumeSettings = [];
74
75
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
76
     * @var array
77
     */
78
    public $ignoreFilesOfType = [];
79
80
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
81
     * @var bool
82
     */
83
    public $displayOptimizedImageVariants = true;
84
85
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
86
     * @var bool
87
     */
88
    public $displayDominantColorPalette = true;
89
90
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
91
     * @var bool
92
     */
93
    public $displayLazyLoadPlaceholderImages = true;
94
95
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
96
     * @var array
97
     */
98
    public $variants = [];
99
100
    // Private Properties
101
    // =========================================================================
102
103
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
104
     * @var array
105
     */
106
    private $aspectRatios = [];
0 ignored issues
show
Coding Style introduced by
Private member variable "aspectRatios" must be prefixed with an underscore
Loading history...
107
108
    // Static Methods
109
    // =========================================================================
110
111
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $config should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Missing short description in doc comment
Loading history...
112
     * @inheritdoc
113
     */
114
    public function __construct(array $config = [])
115
    {
116
        // Unset any deprecated properties
117
        if (!empty($config)) {
118
            unset($config['transformMethod'], $config['imgixDomain']);
119
        }
120
        parent::__construct($config);
121
    }
122
123
    // Public Methods
124
    // =========================================================================
125
126
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
127
     * @inheritdoc
128
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
129
    public static function displayName(): string
130
    {
131
        return 'OptimizedImages';
132
    }
133
134
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
135
     * @inheritdoc
136
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
137
    public function init()
138
    {
139
        parent::init();
140
141
        // Handle cases where the plugin has been uninstalled
142
        if (ImageOptimize::$plugin !== null) {
143
            $settings = ImageOptimize::$plugin->getSettings();
144
            if ($settings) {
145
                if (empty($this->variants)) {
146
                    $this->variants = $settings->defaultVariants;
147
                }
148
                $this->aspectRatios = $settings->defaultAspectRatios;
149
            }
150
        }
151
        // If the user has deleted all default aspect ratios, provide a fallback
152
        if (empty($this->aspectRatios)) {
153
            $this->aspectRatios = self::DEFAULT_ASPECT_RATIOS;
154
        }
155
        // If the user has deleted all default variants, provide a fallback
156
        if (empty($this->variants)) {
157
            $this->variants = self::DEFAULT_IMAGE_VARIANTS;
158
        }
159
    }
160
161
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
162
     * @inheritdoc
163
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
164
    public function rules()
165
    {
166
        $rules = parent::rules();
167
        $rules = array_merge($rules, [
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...
168
            [
169
                [
170
                    'displayOptimizedImageVariants',
171
                    'displayDominantColorPalette',
172
                    'displayLazyLoadPlaceholderImages',
173
                ],
174
                'boolean',
175
            ],
176
            [
177
                [
178
                    'ignoreFilesOfType',
179
                    'variants',
180
                ],
181
                ArrayValidator::class
182
            ],
183
        ]);
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...
184
185
        return $rules;
186
    }
187
188
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
189
     * @inheritdoc
190
     * @since 1.6.2
0 ignored issues
show
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 6 spaces but found 1
Loading history...
191
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
192
    public function getContentGqlType()
193
    {
194
        $typeArray = OptimizedImagesGenerator::generateTypes($this);
195
196
        return [
197
            'name' => $this->handle,
198
            'description' => 'Optimized Images field',
199
            'type' => array_shift($typeArray),
200
        ];
201
    }
202
203
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
204
     * @inheritdoc
205
     * @since 1.7.0
0 ignored issues
show
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 6 spaces but found 1
Loading history...
206
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
207
    public function useFieldset(): bool
208
    {
209
        return true;
210
    }
211
212
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $isNew should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $element should have a doc-comment as per coding-style.
Loading history...
213
     * @inheritdoc
214
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
215
    public function afterElementSave(ElementInterface $element, bool $isNew)
216
    {
217
        parent::afterElementSave($element, $isNew);
218
        // Update our OptimizedImages Field data now that the Asset has been saved
219
        // If this element is propagating, we don't need to redo the image saving for each site
220
        if ($element instanceof Asset && $element->id !== null && !$element->propagating) {
221
            // If the scenario is Asset::SCENARIO_FILEOPS or Asset::SCENARIO_MOVE (if using Craft > v3.7.1) treat it as a new asset
222
            $scenario = $element->getScenario();
223
            $request = Craft::$app->getRequest();
224
            $supportsMoveScenario = version_compare(
225
                    Craft::$app->getVersion(),
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 20.
Loading history...
226
                    '3.7.1',
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 20.
Loading history...
227
                    '>='
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 16 spaces, but found 20.
Loading history...
228
                ) === true;
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 16.
Loading history...
229
230
            if ($isNew || $scenario === Asset::SCENARIO_FILEOPS || ($supportsMoveScenario && $scenario === Asset::SCENARIO_MOVE)) {
231
                /**
232
                 * If this is a newly uploaded/created Asset, we can save the variants
233
                 * via a queue job to prevent it from blocking
234
                 */
235
                ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id);
236
            } else if (!$request->isConsoleRequest && $request->getPathInfo() === 'actions/assets/save-image') {
237
                /**
238
                 * If it's not a newly uploaded/created Asset, check to see if the image
239
                 * itself is being updated (via the ImageEditor). If so, update the
240
                 * variants immediately so the AssetSelectorHud displays the new images
241
                 */
242
                try {
243
                    ImageOptimize::$plugin->optimizedImages->updateOptimizedImageFieldData($this, $element);
244
                } catch (Exception $e) {
245
                    Craft::error($e->getMessage(), __METHOD__);
246
                }
247
            } else {
248
                ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id);
249
            }
250
        }
251
    }
252
253
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $value should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $asset should have a doc-comment as per coding-style.
Loading history...
254
     * @inheritdoc
255
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
256
    public function normalizeValue($value, ElementInterface $asset = null)
257
    {
258
        // If we're passed in a string, assume it's JSON-encoded, and decode it
259
        if (is_string($value) && !empty($value)) {
260
            $value = Json::decodeIfJson($value);
261
        }
262
        // If we're passed in an array, make a model from it
263
        if (is_array($value)) {
264
            // Create a new OptimizedImage model and populate it
265
            $model = new OptimizedImage($value);
266
        } elseif ($value instanceof OptimizedImage) {
267
            $model = $value;
268
        } else {
269
            // Just create a new empty model
270
            $model = new OptimizedImage(null);
271
        }
272
273
        return $model;
274
    }
275
276
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
277
     * @inheritdoc
278
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
279
    public function getContentColumnType(): string
280
    {
281
        return Schema::TYPE_TEXT;
282
    }
283
284
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
285
     * @inheritdoc
286
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
287
    public function getSettingsHtml()
288
    {
289
        $namespace = Craft::$app->getView()->getNamespace();
290
        if (strpos($namespace, Matrix::class) !== false || strpos($namespace, SuperTableField::class) !== false) {
291
            // Render an error template, since the field only works when attached to an Asset
292
            try {
293
                return Craft::$app->getView()->renderTemplate(
294
                    'image-optimize/_components/fields/OptimizedImages_error',
295
                    [
296
                    ]
297
                );
298
            } catch (LoaderError $e) {
299
                Craft::error($e->getMessage(), __METHOD__);
300
            } catch (\yii\base\Exception $e) {
301
                Craft::error($e->getMessage(), __METHOD__);
302
            }
303
        }
304
        // Register our asset bundle
305
        try {
306
            Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class);
307
        } catch (InvalidConfigException $e) {
308
            Craft::error($e->getMessage(), __METHOD__);
309
        }
310
311
        try {
312
            $reflect = new ReflectionClass($this);
313
            $thisId = $reflect->getShortName();
314
        } catch (ReflectionException $e) {
315
            Craft::error($e->getMessage(), __METHOD__);
316
            $thisId = 0;
317
        }
318
        // Get our id and namespace
319
        if (ImageOptimize::$craft35) {
320
            $id = Html::id($thisId);
321
        } else {
322
            $id = Craft::$app->getView()->formatInputId($thisId);
323
        }
324
        $namespacedId = Craft::$app->getView()->namespaceInputId($id);
325
        $namespacePrefix = Craft::$app->getView()->namespaceInputName($thisId);
326
        $sizesWrapperId = Craft::$app->getView()->namespaceInputId('sizes-wrapper');
327
        $view = Craft::$app->getView();
328
        $view->registerJs(
329
            'document.addEventListener("vite-script-loaded", function (e) {' .
330
            'if (e.detail.path === "../src/web/assets/src/js/OptimizedImagesField.js") {' .
331
            'new Craft.OptimizedImagesInput(' .
332
            '"' . $namespacedId . '", ' .
333
            '"' . $namespacePrefix . '",' .
334
            '"' . $sizesWrapperId . '"' .
335
            ');' .
336
            '}' .
337
            '});'
338
        );
339
340
        // Prep our aspect ratios
341
        $aspectRatios = [];
342
        $index = 1;
343
        foreach ($this->aspectRatios as $aspectRatio) {
344
            if ($index % 6 === 0) {
345
                $aspectRatio['break'] = true;
346
            }
347
            $aspectRatios[] = $aspectRatio;
348
            $index++;
349
        }
350
        $aspectRatio = ['x' => 2, 'y' => 2, 'custom' => true];
351
        $aspectRatios[] = $aspectRatio;
352
        // Get only the user-editable settings
353
        $settings = ImageOptimize::$plugin->getSettings();
354
355
        // Render the settings template
356
        try {
357
            return Craft::$app->getView()->renderTemplate(
358
                'image-optimize/_components/fields/OptimizedImages_settings',
359
                [
360
                    'field' => $this,
361
                    'settings' => $settings,
362
                    'aspectRatios' => $aspectRatios,
363
                    'id' => $id,
364
                    'name' => $this->handle,
365
                    'namespace' => $namespacedId,
366
                    'fieldVolumes' => $this->getFieldVolumeInfo($this->handle),
367
                ]
368
            );
369
        } catch (LoaderError $e) {
370
            Craft::error($e->getMessage(), __METHOD__);
371
        } catch (\yii\base\Exception $e) {
372
            Craft::error($e->getMessage(), __METHOD__);
373
        }
374
375
        return '';
376
    }
377
378
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
Coding Style introduced by
Parameter $value should have a doc-comment as per coding-style.
Loading history...
Coding Style introduced by
Parameter $element should have a doc-comment as per coding-style.
Loading history...
379
     * @inheritdoc
380
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
381
    public function getInputHtml($value, ElementInterface $element = null): string
382
    {
383
        if ($element !== null && $element instanceof Asset && $this->handle !== null) {
384
            /** @var Asset $element */
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...
385
            // Register our asset bundle
386
            try {
387
                Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class);
388
            } catch (InvalidConfigException $e) {
389
                Craft::error($e->getMessage(), __METHOD__);
390
            }
391
392
            // Get our id and namespace
393
            if (ImageOptimize::$craft35) {
394
                $id = Html::id($this->handle);
395
            } else {
396
                $id = Craft::$app->getView()->formatInputId($this->handle);
397
            }
398
            $nameSpaceId = Craft::$app->getView()->namespaceInputId($id);
399
400
            // Variables to pass down to our field JavaScript to let it namespace properly
401
            $jsonVars = [
402
                'id' => $id,
403
                'name' => $this->handle,
404
                'namespace' => $nameSpaceId,
405
                'prefix' => Craft::$app->getView()->namespaceInputId(''),
406
            ];
407
            $jsonVars = Json::encode($jsonVars);
408
            $view = Craft::$app->getView();
409
            $view->registerJs(
410
                'document.addEventListener("vite-script-loaded", function (e) {' .
411
                'if (e.detail.path === "../src/web/assets/src/js/OptimizedImagesField.js") {' .
412
                "$('#{$nameSpaceId}-field').ImageOptimizeOptimizedImages(" .
413
                $jsonVars .
414
                ");" .
415
                '}' .
416
                '});'
417
            );
418
419
            $settings = ImageOptimize::$plugin->getSettings();
420
            $createVariants = ImageOptimize::$plugin->optimizedImages->shouldCreateVariants($this, $element);
421
422
            // Render the input template
423
            try {
424
                return Craft::$app->getView()->renderTemplate(
425
                    'image-optimize/_components/fields/OptimizedImages_input',
426
                    [
427
                        'name' => $this->handle,
428
                        'value' => $value,
429
                        'variants' => $this->variants,
430
                        'field' => $this,
431
                        'settings' => $settings,
432
                        'elementId' => $element->id,
433
                        'format' => $element->getExtension(),
434
                        'id' => $id,
435
                        'nameSpaceId' => $nameSpaceId,
436
                        'createVariants' => $createVariants,
437
                    ]
438
                );
439
            } catch (LoaderError $e) {
440
                Craft::error($e->getMessage(), __METHOD__);
441
            } catch (\yii\base\Exception $e) {
442
                Craft::error($e->getMessage(), __METHOD__);
443
            }
444
        }
445
446
        // Render an error template, since the field only works when attached to an Asset
447
        try {
448
            return Craft::$app->getView()->renderTemplate(
449
                'image-optimize/_components/fields/OptimizedImages_error',
450
                [
451
                ]
452
            );
453
        } catch (LoaderError $e) {
454
            Craft::error($e->getMessage(), __METHOD__);
455
        } catch (\yii\base\Exception $e) {
456
            Craft::error($e->getMessage(), __METHOD__);
457
        }
458
459
        return '';
460
    }
461
462
    // Protected Methods
463
    // =========================================================================
464
465
    /**
466
     * Returns an array of asset volumes and their sub-folders
467
     *
468
     * @param string|null $fieldHandle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
469
     *
470
     * @return array
471
     * @throws InvalidConfigException
472
     */
473
    protected function getFieldVolumeInfo($fieldHandle): array
474
    {
475
        $result = [];
476
        if ($fieldHandle !== null) {
477
            $volumes = Craft::$app->getVolumes()->getAllVolumes();
478
            $assets = Craft::$app->getAssets();
479
            foreach ($volumes as $volume) {
480
                if (is_subclass_of($volume, Volume::class)) {
481
                    /** @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...
482
                    if ($this->volumeHasField($volume, $fieldHandle)) {
483
                        $tree = $assets->getFolderTreeByVolumeIds([$volume->id]);
484
                        $result[] = [
485
                            'name' => $volume->name,
486
                            'handle' => $volume->handle,
487
                            'subfolders' => $this->assembleSourceList($tree),
488
                        ];
489
                    }
490
                }
491
            }
492
        }
493
        // If there are too many sub-folders in an Asset volume, don't display them, return an empty array
494
        if (count($result) > self::MAX_VOLUME_SUBFOLDERS) {
495
            $result = [];
496
        }
497
498
        return $result;
499
    }
500
501
    /**
502
     * See if the passed $volume has an OptimizedImagesField with the handle $fieldHandle
503
     *
504
     * @param Volume $volume
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
505
     *
506
     * @param string $fieldHandle
0 ignored issues
show
Coding Style introduced by
Parameter tags must be grouped together in a doc comment
Loading history...
Coding Style introduced by
Missing parameter comment
Loading history...
507
     *
508
     * @return bool
509
     * @throws InvalidConfigException
510
     */
511
    protected function volumeHasField(Volume $volume, string $fieldHandle): bool
512
    {
513
        $result = false;
514
        /** @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...
515
        $fieldLayout = $volume->getFieldLayout();
516
        // Loop through the fields in the layout to see if there is an OptimizedImages field
517
        if ($fieldLayout) {
0 ignored issues
show
introduced by
$fieldLayout is of type craft\models\FieldLayout, thus it always evaluated to true.
Loading history...
518
            $fields = $fieldLayout->getFields();
519
            foreach ($fields as $field) {
520
                if ($field instanceof OptimizedImagesField && $field->handle === $fieldHandle) {
521
                    $result = true;
522
                }
523
            }
524
        }
525
526
        return $result;
527
    }
528
529
    /**
530
     * Transforms an asset folder tree into a source list.
531
     *
532
     * @param array $folders
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
533
     * @param bool $includeNestedFolders
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...
534
     *
535
     * @return array
536
     */
537
    protected function assembleSourceList(array $folders, bool $includeNestedFolders = true): array
538
    {
539
        $sources = [];
540
541
        foreach ($folders as $folder) {
542
            $children = $folder->getChildren();
543
            foreach ($children as $child) {
544
                $sources[$child->name] = $child->name;
545
            }
546
        }
547
548
        return $sources;
549
    }
550
}
551