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