Passed
Push — develop ( 2f6a2c...05df40 )
by Andrew
03:48
created

ImageOptimize::installElementEventHandlers()   A

Complexity

Conditions 4
Paths 1

Size

Total Lines 44
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 27
dl 0
loc 44
rs 9.488
c 0
b 0
f 0
cc 4
nc 1
nop 0
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;
12
13
use nystudio107\imageoptimize\fields\OptimizedImages;
14
use nystudio107\imageoptimize\imagetransforms\ImageTransformInterface;
15
use nystudio107\imageoptimize\listeners\GetCraftQLSchema;
16
use nystudio107\imageoptimize\models\Settings;
17
use nystudio107\imageoptimize\services\Optimize as OptimizeService;
18
use nystudio107\imageoptimize\services\OptimizedImages as OptimizedImagesService;
19
use nystudio107\imageoptimize\services\Placeholder as PlaceholderService;
20
use nystudio107\imageoptimize\variables\ImageOptimizeVariable;
21
22
use Craft;
23
use craft\base\Field;
24
use craft\base\Plugin;
25
use craft\base\Volume;
26
use craft\elements\Asset;
27
use craft\events\AssetTransformImageEvent;
28
use craft\events\ElementEvent;
29
use craft\events\FieldEvent;
30
use craft\events\GetAssetUrlEvent;
31
use craft\events\GenerateTransformEvent;
32
use craft\events\PluginEvent;
33
use craft\events\RegisterComponentTypesEvent;
34
use craft\events\RegisterUrlRulesEvent;
35
use craft\events\ReplaceAssetEvent;
36
use craft\events\VolumeEvent;
37
use craft\helpers\UrlHelper;
38
use craft\models\FieldLayout;
39
use craft\services\Assets;
40
use craft\services\AssetTransforms;
41
use craft\services\Elements;
42
use craft\services\Fields;
43
use craft\services\Plugins;
44
use craft\services\Volumes;
45
use craft\web\twig\variables\CraftVariable;
46
use craft\web\Controller;
47
use craft\web\UrlManager;
48
49
use markhuot\CraftQL\CraftQL;
0 ignored issues
show
Bug introduced by
The type markhuot\CraftQL\CraftQL 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...
50
51
use yii\base\Event;
52
use yii\base\Exception;
53
use yii\base\InvalidConfigException;
54
55
/** @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...
56
57
/**
58
 * Class ImageOptimize
59
 *
60
 * @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 indented incorrectly; expected 2 spaces but found 4
Loading history...
61
 * @package   ImageOptimize
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
62
 * @since     1.0.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 indented incorrectly; expected 3 spaces but found 5
Loading history...
63
 *
64
 * @property OptimizeService         optimize
65
 * @property PlaceholderService      placeholder
66
 * @property OptimizedImagesService  optimizedImages
67
 * @property ImageTransformInterface transformMethod
68
 * @property Settings                $settings
69
 * @method   Settings                getSettings()
70
 */
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...
71
class ImageOptimize extends Plugin
72
{
73
74
    // Constants
75
    // =========================================================================
76
77
    const CRAFTQL_PLUGIN_HANDLE = 'craftql';
78
79
    // Static Properties
80
    // =========================================================================
81
82
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
83
     * @var ImageOptimize
84
     */
85
    public static $plugin;
86
87
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
88
     * @var array
89
     */
90
    public static $transformParams = [];
91
92
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
93
     * @var bool
94
     */
95
    public static $generatePlaceholders = true;
96
97
    // Public Methods
98
    // =========================================================================
99
100
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
101
     * @inheritdoc
102
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
103
    public function init()
104
    {
105
        parent::init();
106
        self::$plugin = $this;
107
        // Handle any console commands
108
        $request = Craft::$app->getRequest();
109
        if ($request->getIsConsoleRequest()) {
110
            $this->controllerNamespace = 'nystudio107\imageoptimize\console\controllers';
111
        }
112
        // Set the image transform component
113
        $this->setImageTransformComponent();
114
        // Add in our Craft components
115
        $this->addComponents();
116
        // Install our global event handlers
117
        $this->installEventHandlers();
118
        // Log that the plugin has loaded
119
        Craft::info(
120
            Craft::t(
121
                'image-optimize',
122
                '{name} plugin loaded',
123
                ['name' => $this->name]
124
            ),
125
            __METHOD__
126
        );
127
    }
128
129
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
130
     * @inheritdoc
131
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
132
    public function getSettingsResponse()
133
    {
134
        $view = Craft::$app->getView();
135
        $namespace = $view->getNamespace();
136
        $view->setNamespace('settings');
137
        $settingsHtml = $this->settingsHtml();
138
        $view->setNamespace($namespace);
139
        /** @var Controller $controller */
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...
140
        $controller = Craft::$app->controller;
0 ignored issues
show
Documentation Bug introduced by
It seems like Craft::app->controller can also be of type yii\web\Controller. However, the property $controller is declared as type yii\console\Controller. 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...
141
142
        return $controller->renderTemplate('image-optimize/_settings', [
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...
143
            'plugin'       => $this,
144
            'settingsHtml' => $settingsHtml,
145
        ]);
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...
146
    }
147
148
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
149
     * @inheritdoc
150
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
151
    public function settingsHtml()
152
    {
153
        $imageProcessors = ImageOptimize::$plugin->optimize->getActiveImageProcessors();
154
        $variantCreators = ImageOptimize::$plugin->optimize->getActiveVariantCreators();
155
        // Get only the user-editable settings
156
        $settings = $this->getSettings();
157
158
        // Render the settings template
159
        try {
160
            return Craft::$app->getView()->renderTemplate(
161
                'image-optimize/settings',
162
                [
163
                    'settings'        => $settings,
164
                    'imageProcessors' => $imageProcessors,
165
                    'variantCreators' => $variantCreators,
166
                    'gdInstalled'     => \function_exists('imagecreatefromjpeg'),
167
                ]
168
            );
169
        } catch (\Twig_Error_Loader $e) {
170
            Craft::error($e->getMessage(), __METHOD__);
171
        } catch (Exception $e) {
172
            Craft::error($e->getMessage(), __METHOD__);
173
        }
174
175
        return '';
176
    }
177
178
    // Protected Methods
179
    // =========================================================================
180
181
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
182
     * @inheritdoc
183
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
184
    protected function createSettingsModel()
185
    {
186
        return new Settings();
187
    }
188
189
    /**
190
     * Set the transformMethod component
191
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
192
    protected function setImageTransformComponent()
193
    {
194
        $settings = $this->getSettings();
195
        $definition = array_merge(
196
            $settings->imageTransformSettings[$settings->transformClass] ?? [],
197
            ['class' => $settings->transformClass]
198
        );
199
        try {
200
            $this->set('transformMethod', $definition);
201
        } catch (InvalidConfigException $e) {
202
            Craft::error($e->getMessage(), __METHOD__);
203
        }
204
        self::$transformParams = ImageOptimize::$plugin->transformMethod->getTransformParams();
205
    }
206
207
    /**
208
     * Add in our Craft components
209
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
210
    protected function addComponents()
211
    {
212
        // Register our variables
213
        Event::on(
214
            CraftVariable::class,
215
            CraftVariable::EVENT_INIT,
216
            function (Event $event) {
217
                /** @var CraftVariable $variable */
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...
218
                $variable = $event->sender;
219
                $variable->set('imageOptimize', ImageOptimizeVariable::class);
220
            }
221
        );
222
223
        // Register our Field
224
        Event::on(
225
            Fields::class,
226
            Fields::EVENT_REGISTER_FIELD_TYPES,
227
            function (RegisterComponentTypesEvent $event) {
228
                Craft::debug(
229
                    'Fields::EVENT_REGISTER_FIELD_TYPES',
230
                    __METHOD__
231
                );
232
                $event->types[] = OptimizedImages::class;
233
            }
234
        );
235
    }
236
237
    /**
238
     * Install our event handlers
239
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
240
    protected function installEventHandlers()
241
    {
242
        $this->installAssetEventHandlers();
243
        $this->installElementEventHandlers();
244
        $this->installMiscEventHandlers();
245
        $this->installCraftQLEventHandlers();
246
        $request = Craft::$app->getRequest();
247
        // Install only for non-console site requests
248
        if ($request->getIsSiteRequest() && !$request->getIsConsoleRequest()) {
249
            $this->installSiteEventListeners();
250
        }
251
    }
252
253
    /**
254
     * Install our Asset event handlers
255
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
256
    protected function installAssetEventHandlers()
257
    {
258
        // Handler: Assets::EVENT_GET_ASSET_URL
259
        Event::on(
260
            Assets::class,
261
            Assets::EVENT_GET_ASSET_URL,
262
            function (GetAssetUrlEvent $event) {
263
                Craft::debug(
264
                    'Assets::EVENT_GET_ASSET_URL',
265
                    __METHOD__
266
                );
267
                // Return the URL to the asset URL or null to let Craft handle it
268
                $event->url = ImageOptimize::$plugin->optimize->handleGetAssetUrlEvent(
269
                    $event
270
                );
271
            }
272
        );
273
274
        // Handler: AssetTransforms::EVENT_GENERATE_TRANSFORM
275
        Event::on(
276
            AssetTransforms::class,
277
            AssetTransforms::EVENT_GENERATE_TRANSFORM,
278
            function (GenerateTransformEvent $event) {
279
                Craft::debug(
280
                    'AssetTransforms::EVENT_GENERATE_TRANSFORM',
281
                    __METHOD__
282
                );
283
                // Return the path to the optimized image to _createTransformForAsset()
284
                $event->tempPath = ImageOptimize::$plugin->optimize->handleGenerateTransformEvent(
285
                    $event
286
                );
287
            }
288
        );
289
290
        // Handler: AssetTransforms::EVENT_AFTER_DELETE_TRANSFORMS
291
        Event::on(
292
            AssetTransforms::class,
293
            AssetTransforms::EVENT_AFTER_DELETE_TRANSFORMS,
294
            function (AssetTransformImageEvent $event) {
295
                Craft::debug(
296
                    'AssetTransforms::EVENT_AFTER_DELETE_TRANSFORMS',
297
                    __METHOD__
298
                );
299
                // Clean up any stray variant files
300
                ImageOptimize::$plugin->optimize->handleAfterDeleteTransformsEvent(
301
                    $event
302
                );
303
            }
304
        );
305
306
        // Handler: Assets::EVENT_BEFORE_REPLACE_ASSET
307
        Event::on(
308
            Assets::class,
309
            Assets::EVENT_BEFORE_REPLACE_ASSET,
310
            function (ReplaceAssetEvent $event) {
311
                Craft::debug(
312
                    'Assets::EVENT_BEFORE_REPLACE_ASSET',
313
                    __METHOD__
314
                );
315
                /** @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...
316
                $element = $event->asset;
317
                // Purge the URL
318
                $purgeUrl = ImageOptimize::$plugin->transformMethod->getPurgeUrl(
319
                    $element,
320
                    ImageOptimize::$transformParams
321
                );
322
                if ($purgeUrl) {
323
                    ImageOptimize::$plugin->transformMethod->purgeUrl($purgeUrl, ImageOptimize::$transformParams);
324
                }
325
            }
326
        );
327
328
        // Handler: Assets::EVENT_AFTER_REPLACE_ASSET
329
        Event::on(
330
            Assets::class,
331
            Assets::EVENT_AFTER_REPLACE_ASSET,
332
            function (ReplaceAssetEvent $event) {
333
                Craft::debug(
334
                    'Assets::EVENT_AFTER_REPLACE_ASSET',
335
                    __METHOD__
336
                );
337
                /** @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...
338
                $element = $event->asset;
339
                if ($element->id !== null) {
340
                    ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id);
341
                }
342
            }
343
        );
344
    }
345
346
    /**
347
     * Install our Element event handlers
348
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
349
    protected function installElementEventHandlers()
350
    {
351
        // Handler: Elements::EVENT_BEFORE_SAVE_ELEMENT
352
        Event::on(
353
            Assets::class,
354
            Elements::EVENT_BEFORE_SAVE_ELEMENT,
355
            function (ElementEvent $event) {
356
                Craft::debug(
357
                    'Elements::EVENT_BEFORE_SAVE_ELEMENT',
358
                    __METHOD__
359
                );
360
                /** @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...
361
                $asset = $event->element;
362
                if (!$event->isNew) {
363
                    // Purge the URL
364
                    $purgeUrl = ImageOptimize::$plugin->transformMethod->getPurgeUrl(
365
                        $asset,
366
                        ImageOptimize::$transformParams
367
                    );
368
                    if ($purgeUrl) {
369
                        ImageOptimize::$plugin->transformMethod->purgeUrl($purgeUrl, ImageOptimize::$transformParams);
370
                    }
371
                }
372
            }
373
        );
374
375
        // Handler: Elements::EVENT_BEFORE_DELETE_ELEMENT
376
        Event::on(
377
            Asset::class,
378
            Elements::EVENT_BEFORE_DELETE_ELEMENT,
379
            function (ElementEvent $event) {
380
                Craft::debug(
381
                    'Elements::EVENT_BEFORE_DELETE_ELEMENT',
382
                    __METHOD__
383
                );
384
                /** @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...
385
                $asset = $event->element;
386
                // Purge the URL
387
                $purgeUrl = ImageOptimize::$plugin->transformMethod->getPurgeUrl(
388
                    $asset,
389
                    ImageOptimize::$transformParams
390
                );
391
                if ($purgeUrl) {
392
                    ImageOptimize::$plugin->transformMethod->purgeUrl($purgeUrl, ImageOptimize::$transformParams);
393
                }
394
            }
395
        );
396
    }
397
398
399
    /**
400
     * Install our miscellaneous event handlers
401
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
402
    protected function installMiscEventHandlers()
403
    {
404
        // Handler: Fields::EVENT_AFTER_SAVE_FIELD
405
        Event::on(
406
            Fields::class,
407
            Fields::EVENT_AFTER_SAVE_FIELD,
408
            function (FieldEvent $event) {
409
                Craft::debug(
410
                    'Fields::EVENT_AFTER_SAVE_FIELD',
411
                    __METHOD__
412
                );
413
                $settings = $this->getSettings();
414
                /** @var Field $field */
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...
415
                if (!$event->isNew && $settings->automaticallyResaveImageVariants) {
416
                    $this->checkForOptimizedImagesField($event);
417
                }
418
            }
419
        );
420
421
        // Handler: Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS
422
        Event::on(
423
            Plugins::class,
424
            Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS,
425
            function (PluginEvent $event) {
426
                if ($event->plugin === $this) {
427
                    Craft::debug(
428
                        'Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS',
429
                        __METHOD__
430
                    );
431
                    $settings = $this->getSettings();
432
                    if ($settings->automaticallyResaveImageVariants) {
433
                        // After they have changed the settings, resave all of the assets
434
                        ImageOptimize::$plugin->optimizedImages->resaveAllVolumesAssets();
435
                    }
436
                }
437
            }
438
        );
439
440
        // Handler: Volumes::EVENT_AFTER_SAVE_VOLUME
441
        Event::on(
442
            Volumes::class,
443
            Volumes::EVENT_AFTER_SAVE_VOLUME,
444
            function (VolumeEvent $event) {
445
                Craft::debug(
446
                    'Volumes::EVENT_AFTER_SAVE_VOLUME',
447
                    __METHOD__
448
                );
449
                $settings = $this->getSettings();
450
                // Only worry about this volume if it's not new
451
                if (!$event->isNew && $settings->automaticallyResaveImageVariants) {
452
                    /** @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...
453
                    $volume = $event->volume;
454
                    if ($volume !== null) {
455
                        ImageOptimize::$plugin->optimizedImages->resaveVolumeAssets($volume);
456
                    }
457
                }
458
            }
459
        );
460
461
        // Handler: Plugins::EVENT_AFTER_INSTALL_PLUGIN
462
        Event::on(
463
            Plugins::class,
464
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
465
            function (PluginEvent $event) {
466
                if ($event->plugin === $this) {
467
                    $request = Craft::$app->getRequest();
468
                    if ($request->isCpRequest) {
469
                        Craft::$app->getResponse()->redirect(UrlHelper::cpUrl('image-optimize/welcome'))->send();
470
                    }
471
                }
472
            }
473
        );
474
    }
475
476
    /**
477
     * Install our CraftQL event handlers
478
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
479
    protected function installCraftQLEventHandlers()
480
    {
481
        if (class_exists(CraftQL::class)) {
482
            Event::on(
483
                OptimizedImages::class,
484
                GetCraftQLSchema::EVENT_GET_FIELD_SCHEMA,
485
                [new GetCraftQLSchema, 'handle']
486
            );
487
        }
488
    }
489
490
    /**
491
     * Install site event listeners for site requests only
492
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
493
    protected function installSiteEventListeners()
494
    {
495
        // Handler: UrlManager::EVENT_REGISTER_SITE_URL_RULES
496
        Event::on(
497
            UrlManager::class,
498
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
499
            function (RegisterUrlRulesEvent $event) {
500
                Craft::debug(
501
                    'UrlManager::EVENT_REGISTER_SITE_URL_RULES',
502
                    __METHOD__
503
                );
504
                // Register our Control Panel routes
505
                $event->rules = array_merge(
506
                    $event->rules,
507
                    $this->customFrontendRoutes()
508
                );
509
            }
510
        );
511
    }
512
513
    /**
514
     * Return the custom frontend routes
515
     *
516
     * @return array
517
     */
518
    protected function customFrontendRoutes(): array
519
    {
520
        return [
521
        ];
522
    }
523
524
    /**
525
     * If the Field being saved is an OptimizedImages field, re-save the
526
     * responsive image variants automatically
527
     *
528
     * @param FieldEvent $event
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
529
     *
530
     * @throws \yii\base\InvalidConfigException
531
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
532
    protected function checkForOptimizedImagesField(FieldEvent $event)
533
    {
534
        $thisField = $event->field;
535
        if ($thisField instanceof OptimizedImages) {
536
            $volumes = Craft::$app->getVolumes()->getAllVolumes();
537
            foreach ($volumes as $volume) {
538
                $needToReSave = false;
539
                /** @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...
540
                /** @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...
541
                $fieldLayout = $volume->getFieldLayout();
542
                // Loop through the fields in the layout to see if it contains our field
543
                if ($fieldLayout) {
544
                    $fields = $fieldLayout->getFields();
545
                    foreach ($fields as $field) {
546
                        /** @var Field $field */
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...
547
                        if ($thisField->handle === $field->handle) {
548
                            $needToReSave = true;
549
                        }
550
                    }
551
                    if ($needToReSave) {
552
                        ImageOptimize::$plugin->optimizedImages->resaveVolumeAssets($volume);
553
                    }
554
                }
555
            }
556
        }
557
    }
558
}
559