Passed
Push — v1 ( 2b94f4...f851e8 )
by Andrew
20:48 queued 13:49
created

OptimizedImages::afterElementSave()   B

Complexity

Conditions 11
Paths 5

Size

Total Lines 34
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 7
Bugs 2 Features 0
Metric Value
eloc 18
c 7
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 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\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) {
0 ignored issues
show
introduced by
$settings is of type nystudio107\imageoptimize\models\Settings, thus it always evaluated to true.
Loading history...
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
            'new Craft.OptimizedImagesInput(' .
330
            '"' . $namespacedId . '", ' .
331
            '"' . $namespacePrefix . '",' .
332
            '"' . $sizesWrapperId . '"' .
333
            ');'
334
        );
335
336
        // Prep our aspect ratios
337
        $aspectRatios = [];
338
        $index = 1;
339
        foreach ($this->aspectRatios as $aspectRatio) {
340
            if ($index % 6 === 0) {
341
                $aspectRatio['break'] = true;
342
            }
343
            $aspectRatios[] = $aspectRatio;
344
            $index++;
345
        }
346
        $aspectRatio = ['x' => 2, 'y' => 2, 'custom' => true];
347
        $aspectRatios[] = $aspectRatio;
348
        // Get only the user-editable settings
349
        $settings = ImageOptimize::$plugin->getSettings();
350
351
        // Render the settings template
352
        try {
353
            return Craft::$app->getView()->renderTemplate(
354
                'image-optimize/_components/fields/OptimizedImages_settings',
355
                [
356
                    'field' => $this,
357
                    'settings' => $settings,
358
                    'aspectRatios' => $aspectRatios,
359
                    'id' => $id,
360
                    'name' => $this->handle,
361
                    'namespace' => $namespacedId,
362
                    'fieldVolumes' => $this->getFieldVolumeInfo($this->handle),
363
                ]
364
            );
365
        } catch (LoaderError $e) {
366
            Craft::error($e->getMessage(), __METHOD__);
367
        } catch (\yii\base\Exception $e) {
368
            Craft::error($e->getMessage(), __METHOD__);
369
        }
370
371
        return '';
372
    }
373
374
    /**
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...
375
     * @inheritdoc
376
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
377
    public function getInputHtml($value, ElementInterface $element = null): string
378
    {
379
        if ($element !== null && $element instanceof Asset && $this->handle !== null) {
380
            /** @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...
381
            // Register our asset bundle
382
            try {
383
                Craft::$app->getView()->registerAssetBundle(ImageOptimizeAsset::class);
384
            } catch (InvalidConfigException $e) {
385
                Craft::error($e->getMessage(), __METHOD__);
386
            }
387
388
            // Get our id and namespace
389
            if (ImageOptimize::$craft35) {
390
                $id = Html::id($this->handle);
391
            } else {
392
                $id = Craft::$app->getView()->formatInputId($this->handle);
393
            }
394
            $nameSpaceId = Craft::$app->getView()->namespaceInputId($id);
395
396
            // Variables to pass down to our field JavaScript to let it namespace properly
397
            $jsonVars = [
398
                'id' => $id,
399
                'name' => $this->handle,
400
                'namespace' => $nameSpaceId,
401
                'prefix' => Craft::$app->getView()->namespaceInputId(''),
402
            ];
403
            $jsonVars = Json::encode($jsonVars);
404
            $view = Craft::$app->getView();
405
            $view->registerJs(
406
                "$('#{$nameSpaceId}-field').ImageOptimizeOptimizedImages(" .
407
                $jsonVars .
408
                ");"
409
            );
410
411
            $settings = ImageOptimize::$plugin->getSettings();
412
            $createVariants = ImageOptimize::$plugin->optimizedImages->shouldCreateVariants($this, $element);
413
414
            // Render the input template
415
            try {
416
                return Craft::$app->getView()->renderTemplate(
417
                    'image-optimize/_components/fields/OptimizedImages_input',
418
                    [
419
                        'name' => $this->handle,
420
                        'value' => $value,
421
                        'variants' => $this->variants,
422
                        'field' => $this,
423
                        'settings' => $settings,
424
                        'elementId' => $element->id,
425
                        'format' => $element->getExtension(),
426
                        'id' => $id,
427
                        'nameSpaceId' => $nameSpaceId,
428
                        'createVariants' => $createVariants,
429
                    ]
430
                );
431
            } catch (LoaderError $e) {
432
                Craft::error($e->getMessage(), __METHOD__);
433
            } catch (\yii\base\Exception $e) {
434
                Craft::error($e->getMessage(), __METHOD__);
435
            }
436
        }
437
438
        // Render an error template, since the field only works when attached to an Asset
439
        try {
440
            return Craft::$app->getView()->renderTemplate(
441
                'image-optimize/_components/fields/OptimizedImages_error',
442
                [
443
                ]
444
            );
445
        } catch (LoaderError $e) {
446
            Craft::error($e->getMessage(), __METHOD__);
447
        } catch (\yii\base\Exception $e) {
448
            Craft::error($e->getMessage(), __METHOD__);
449
        }
450
451
        return '';
452
    }
453
454
    // Protected Methods
455
    // =========================================================================
456
457
    /**
458
     * Returns an array of asset volumes and their sub-folders
459
     *
460
     * @param string|null $fieldHandle
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
461
     *
462
     * @return array
463
     * @throws InvalidConfigException
464
     */
465
    protected function getFieldVolumeInfo($fieldHandle): array
466
    {
467
        $result = [];
468
        if ($fieldHandle !== null) {
469
            $volumes = Craft::$app->getVolumes()->getAllVolumes();
470
            $assets = Craft::$app->getAssets();
471
            foreach ($volumes as $volume) {
472
                if (is_subclass_of($volume, Volume::class)) {
473
                    /** @var Volume $volume */
0 ignored issues
show
Coding Style introduced by
The close comment tag must be the only content on the line
Loading history...
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...
474
                    if ($this->volumeHasField($volume, $fieldHandle)) {
475
                        $tree = $assets->getFolderTreeByVolumeIds([$volume->id]);
476
                        $result[] = [
477
                            'name' => $volume->name,
478
                            'handle' => $volume->handle,
479
                            'subfolders' => $this->assembleSourceList($tree),
480
                        ];
481
                    }
482
                }
483
            }
484
        }
485
        // If there are too many sub-folders in an Asset volume, don't display them, return an empty array
486
        if (count($result) > self::MAX_VOLUME_SUBFOLDERS) {
487
            $result = [];
488
        }
489
490
        return $result;
491
    }
492
493
    /**
494
     * See if the passed $volume has an OptimizedImagesField with the handle $fieldHandle
495
     *
496
     * @param Volume $volume
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
497
     *
498
     * @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...
499
     *
500
     * @return bool
501
     * @throws InvalidConfigException
502
     */
503
    protected function volumeHasField(Volume $volume, string $fieldHandle): bool
504
    {
505
        $result = false;
506
        /** @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...
507
        $fieldLayout = $volume->getFieldLayout();
508
        // Loop through the fields in the layout to see if there is an OptimizedImages field
509
        if ($fieldLayout) {
0 ignored issues
show
introduced by
$fieldLayout is of type craft\models\FieldLayout, thus it always evaluated to true.
Loading history...
510
            $fields = $fieldLayout->getFields();
511
            foreach ($fields as $field) {
512
                if ($field instanceof OptimizedImagesField && $field->handle === $fieldHandle) {
513
                    $result = true;
514
                }
515
            }
516
        }
517
518
        return $result;
519
    }
520
521
    /**
522
     * Transforms an asset folder tree into a source list.
523
     *
524
     * @param array $folders
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
525
     * @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...
526
     *
527
     * @return array
528
     */
529
    protected function assembleSourceList(array $folders, bool $includeNestedFolders = true): array
530
    {
531
        $sources = [];
532
533
        foreach ($folders as $folder) {
534
            $children = $folder->getChildren();
535
            foreach ($children as $child) {
536
                $sources[$child->name] = $child->name;
537
            }
538
        }
539
540
        return $sources;
541
    }
542
}
543