Passed
Push — develop ( 9e87b1...d502bc )
by Andrew
04:00
created

ImageOptimize   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 497
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 229
dl 0
loc 497
rs 8.96
c 0
b 0
f 0
wmc 43

14 Methods

Rating   Name   Duplication   Size   Complexity  
A init() 0 23 2
A createSettingsModel() 0 3 1
A settingsHtml() 0 40 5
A installElementEventHandlers() 0 44 4
A customFrontendRoutes() 0 3 1
A setImageTransformComponent() 0 13 2
A installCraftQLEventHandlers() 0 7 2
B installMiscEventHandlers() 0 68 10
A installSiteEventListeners() 0 15 1
A installAssetEventHandlers() 0 85 3
A installEventHandlers() 0 10 3
A getSettingsResponse() 0 13 1
A addComponents() 0 23 1
B checkForOptimizedImagesField() 0 21 7

How to fix   Complexity   

Complex Class

Complex classes like ImageOptimize often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use ImageOptimize, and based on these observations, apply Extract Interface, too.

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\ArrayHelper;
38
use craft\helpers\UrlHelper;
39
use craft\models\FieldLayout;
40
use craft\services\Assets;
41
use craft\services\AssetTransforms;
42
use craft\services\Elements;
43
use craft\services\Fields;
44
use craft\services\Plugins;
45
use craft\services\Volumes;
46
use craft\web\twig\variables\CraftVariable;
47
use craft\web\Controller;
48
use craft\web\UrlManager;
49
50
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...
51
52
use yii\base\Event;
53
use yii\base\Exception;
54
use yii\base\InvalidConfigException;
55
56
/** @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...
57
58
/**
59
 * Class ImageOptimize
60
 *
61
 * @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...
62
 * @package   ImageOptimize
0 ignored issues
show
Coding Style introduced by
Tag value indented incorrectly; expected 1 spaces but found 3
Loading history...
63
 * @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...
64
 *
65
 * @property OptimizeService         optimize
66
 * @property PlaceholderService      placeholder
67
 * @property OptimizedImagesService  optimizedImages
68
 * @property ImageTransformInterface transformMethod
69
 * @property Settings                $settings
70
 * @method   Settings                getSettings()
71
 */
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...
72
class ImageOptimize extends Plugin
73
{
74
75
    // Constants
76
    // =========================================================================
77
78
    const CRAFTQL_PLUGIN_HANDLE = 'craftql';
79
80
    // Static Properties
81
    // =========================================================================
82
83
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
84
     * @var ImageOptimize
85
     */
86
    public static $plugin;
87
88
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
89
     * @var array
90
     */
91
    public static $transformParams = [];
92
93
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
94
     * @var bool
95
     */
96
    public static $generatePlaceholders = true;
97
98
    // Public Methods
99
    // =========================================================================
100
101
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
102
     * @inheritdoc
103
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
104
    public function init()
105
    {
106
        parent::init();
107
        self::$plugin = $this;
108
        // Handle any console commands
109
        $request = Craft::$app->getRequest();
110
        if ($request->getIsConsoleRequest()) {
111
            $this->controllerNamespace = 'nystudio107\imageoptimize\console\controllers';
112
        }
113
        // Set the image transform component
114
        $this->setImageTransformComponent();
115
        // Add in our Craft components
116
        $this->addComponents();
117
        // Install our global event handlers
118
        $this->installEventHandlers();
119
        // Log that the plugin has loaded
120
        Craft::info(
121
            Craft::t(
122
                'image-optimize',
123
                '{name} plugin loaded',
124
                ['name' => $this->name]
125
            ),
126
            __METHOD__
127
        );
128
    }
129
130
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
131
     * @inheritdoc
132
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
133
    public function getSettingsResponse()
134
    {
135
        $view = Craft::$app->getView();
136
        $namespace = $view->getNamespace();
137
        $view->setNamespace('settings');
138
        $settingsHtml = $this->settingsHtml();
139
        $view->setNamespace($namespace);
140
        /** @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...
141
        $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...
142
143
        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...
144
            'plugin'       => $this,
145
            'settingsHtml' => $settingsHtml,
146
        ]);
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...
147
    }
148
149
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
150
     * @inheritdoc
151
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
152
    public function settingsHtml()
153
    {
154
        $imageProcessors = ImageOptimize::$plugin->optimize->getActiveImageProcessors();
155
        $variantCreators = ImageOptimize::$plugin->optimize->getActiveVariantCreators();
156
        // Get only the user-editable settings
157
        $settings = $this->getSettings();
158
159
        // Get the image transform types
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 (ImageOptimize::$plugin->optimize->getAllImageTransformTypes() 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
                    'imageProcessors' => $imageProcessors,
180
                    'variantCreators' => $variantCreators,
181
                    'gdInstalled'     => \function_exists('imagecreatefromjpeg'),
182
                    'imageTransformOptions' => $imageTransformTypeOptions,
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->imageTransformSettings[$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: AssetTransforms::EVENT_GENERATE_TRANSFORM
291
        Event::on(
292
            AssetTransforms::class,
293
            AssetTransforms::EVENT_GENERATE_TRANSFORM,
294
            function (GenerateTransformEvent $event) {
295
                Craft::debug(
296
                    'AssetTransforms::EVENT_GENERATE_TRANSFORM',
297
                    __METHOD__
298
                );
299
                // Return the path to the optimized image to _createTransformForAsset()
300
                $event->tempPath = ImageOptimize::$plugin->optimize->handleGenerateTransformEvent(
301
                    $event
302
                );
303
            }
304
        );
305
306
        // Handler: AssetTransforms::EVENT_AFTER_DELETE_TRANSFORMS
307
        Event::on(
308
            AssetTransforms::class,
309
            AssetTransforms::EVENT_AFTER_DELETE_TRANSFORMS,
310
            function (AssetTransformImageEvent $event) {
311
                Craft::debug(
312
                    'AssetTransforms::EVENT_AFTER_DELETE_TRANSFORMS',
313
                    __METHOD__
314
                );
315
                // Clean up any stray variant files
316
                ImageOptimize::$plugin->optimize->handleAfterDeleteTransformsEvent(
317
                    $event
318
                );
319
            }
320
        );
321
322
        // Handler: Assets::EVENT_BEFORE_REPLACE_ASSET
323
        Event::on(
324
            Assets::class,
325
            Assets::EVENT_BEFORE_REPLACE_ASSET,
326
            function (ReplaceAssetEvent $event) {
327
                Craft::debug(
328
                    'Assets::EVENT_BEFORE_REPLACE_ASSET',
329
                    __METHOD__
330
                );
331
                /** @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...
332
                $element = $event->asset;
333
                // Purge the URL
334
                $purgeUrl = ImageOptimize::$plugin->transformMethod->getPurgeUrl(
335
                    $element,
336
                    ImageOptimize::$transformParams
337
                );
338
                if ($purgeUrl) {
339
                    ImageOptimize::$plugin->transformMethod->purgeUrl($purgeUrl, ImageOptimize::$transformParams);
340
                }
341
            }
342
        );
343
344
        // Handler: Assets::EVENT_AFTER_REPLACE_ASSET
345
        Event::on(
346
            Assets::class,
347
            Assets::EVENT_AFTER_REPLACE_ASSET,
348
            function (ReplaceAssetEvent $event) {
349
                Craft::debug(
350
                    'Assets::EVENT_AFTER_REPLACE_ASSET',
351
                    __METHOD__
352
                );
353
                /** @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...
354
                $element = $event->asset;
355
                if ($element->id !== null) {
356
                    ImageOptimize::$plugin->optimizedImages->resaveAsset($element->id);
357
                }
358
            }
359
        );
360
    }
361
362
    /**
363
     * Install our Element event handlers
364
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
365
    protected function installElementEventHandlers()
366
    {
367
        // Handler: Elements::EVENT_BEFORE_SAVE_ELEMENT
368
        Event::on(
369
            Assets::class,
370
            Elements::EVENT_BEFORE_SAVE_ELEMENT,
371
            function (ElementEvent $event) {
372
                Craft::debug(
373
                    'Elements::EVENT_BEFORE_SAVE_ELEMENT',
374
                    __METHOD__
375
                );
376
                /** @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...
377
                $asset = $event->element;
378
                if (!$event->isNew) {
379
                    // Purge the URL
380
                    $purgeUrl = ImageOptimize::$plugin->transformMethod->getPurgeUrl(
381
                        $asset,
382
                        ImageOptimize::$transformParams
383
                    );
384
                    if ($purgeUrl) {
385
                        ImageOptimize::$plugin->transformMethod->purgeUrl($purgeUrl, ImageOptimize::$transformParams);
386
                    }
387
                }
388
            }
389
        );
390
391
        // Handler: Elements::EVENT_BEFORE_DELETE_ELEMENT
392
        Event::on(
393
            Asset::class,
394
            Elements::EVENT_BEFORE_DELETE_ELEMENT,
395
            function (ElementEvent $event) {
396
                Craft::debug(
397
                    'Elements::EVENT_BEFORE_DELETE_ELEMENT',
398
                    __METHOD__
399
                );
400
                /** @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...
401
                $asset = $event->element;
402
                // Purge the URL
403
                $purgeUrl = ImageOptimize::$plugin->transformMethod->getPurgeUrl(
404
                    $asset,
405
                    ImageOptimize::$transformParams
406
                );
407
                if ($purgeUrl) {
408
                    ImageOptimize::$plugin->transformMethod->purgeUrl($purgeUrl, ImageOptimize::$transformParams);
409
                }
410
            }
411
        );
412
    }
413
414
415
    /**
416
     * Install our miscellaneous event handlers
417
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
418
    protected function installMiscEventHandlers()
419
    {
420
        // Handler: Fields::EVENT_AFTER_SAVE_FIELD
421
        Event::on(
422
            Fields::class,
423
            Fields::EVENT_AFTER_SAVE_FIELD,
424
            function (FieldEvent $event) {
425
                Craft::debug(
426
                    'Fields::EVENT_AFTER_SAVE_FIELD',
427
                    __METHOD__
428
                );
429
                $settings = $this->getSettings();
430
                /** @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...
431
                if (!$event->isNew && $settings->automaticallyResaveImageVariants) {
432
                    $this->checkForOptimizedImagesField($event);
433
                }
434
            }
435
        );
436
437
        // Handler: Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS
438
        Event::on(
439
            Plugins::class,
440
            Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS,
441
            function (PluginEvent $event) {
442
                if ($event->plugin === $this) {
443
                    Craft::debug(
444
                        'Plugins::EVENT_AFTER_SAVE_PLUGIN_SETTINGS',
445
                        __METHOD__
446
                    );
447
                    $settings = $this->getSettings();
448
                    if ($settings->automaticallyResaveImageVariants) {
449
                        // After they have changed the settings, resave all of the assets
450
                        ImageOptimize::$plugin->optimizedImages->resaveAllVolumesAssets();
451
                    }
452
                }
453
            }
454
        );
455
456
        // Handler: Volumes::EVENT_AFTER_SAVE_VOLUME
457
        Event::on(
458
            Volumes::class,
459
            Volumes::EVENT_AFTER_SAVE_VOLUME,
460
            function (VolumeEvent $event) {
461
                Craft::debug(
462
                    'Volumes::EVENT_AFTER_SAVE_VOLUME',
463
                    __METHOD__
464
                );
465
                $settings = $this->getSettings();
466
                // Only worry about this volume if it's not new
467
                if (!$event->isNew && $settings->automaticallyResaveImageVariants) {
468
                    /** @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...
469
                    $volume = $event->volume;
470
                    if ($volume !== null) {
471
                        ImageOptimize::$plugin->optimizedImages->resaveVolumeAssets($volume);
472
                    }
473
                }
474
            }
475
        );
476
477
        // Handler: Plugins::EVENT_AFTER_INSTALL_PLUGIN
478
        Event::on(
479
            Plugins::class,
480
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
481
            function (PluginEvent $event) {
482
                if ($event->plugin === $this) {
483
                    $request = Craft::$app->getRequest();
484
                    if ($request->isCpRequest) {
485
                        Craft::$app->getResponse()->redirect(UrlHelper::cpUrl('image-optimize/welcome'))->send();
486
                    }
487
                }
488
            }
489
        );
490
    }
491
492
    /**
493
     * Install our CraftQL event handlers
494
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
495
    protected function installCraftQLEventHandlers()
496
    {
497
        if (class_exists(CraftQL::class)) {
498
            Event::on(
499
                OptimizedImages::class,
500
                GetCraftQLSchema::EVENT_GET_FIELD_SCHEMA,
501
                [new GetCraftQLSchema, 'handle']
502
            );
503
        }
504
    }
505
506
    /**
507
     * Install site event listeners for site requests only
508
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
509
    protected function installSiteEventListeners()
510
    {
511
        // Handler: UrlManager::EVENT_REGISTER_SITE_URL_RULES
512
        Event::on(
513
            UrlManager::class,
514
            UrlManager::EVENT_REGISTER_SITE_URL_RULES,
515
            function (RegisterUrlRulesEvent $event) {
516
                Craft::debug(
517
                    'UrlManager::EVENT_REGISTER_SITE_URL_RULES',
518
                    __METHOD__
519
                );
520
                // Register our Control Panel routes
521
                $event->rules = array_merge(
522
                    $event->rules,
523
                    $this->customFrontendRoutes()
524
                );
525
            }
526
        );
527
    }
528
529
    /**
530
     * Return the custom frontend routes
531
     *
532
     * @return array
533
     */
534
    protected function customFrontendRoutes(): array
535
    {
536
        return [
537
        ];
538
    }
539
540
    /**
541
     * If the Field being saved is an OptimizedImages field, re-save the
542
     * responsive image variants automatically
543
     *
544
     * @param FieldEvent $event
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
545
     *
546
     * @throws \yii\base\InvalidConfigException
547
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
548
    protected function checkForOptimizedImagesField(FieldEvent $event)
549
    {
550
        $thisField = $event->field;
551
        if ($thisField instanceof OptimizedImages) {
552
            $volumes = Craft::$app->getVolumes()->getAllVolumes();
553
            foreach ($volumes as $volume) {
554
                $needToReSave = false;
555
                /** @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...
556
                /** @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...
557
                $fieldLayout = $volume->getFieldLayout();
558
                // Loop through the fields in the layout to see if it contains our field
559
                if ($fieldLayout) {
560
                    $fields = $fieldLayout->getFields();
561
                    foreach ($fields as $field) {
562
                        /** @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...
563
                        if ($thisField->handle === $field->handle) {
564
                            $needToReSave = true;
565
                        }
566
                    }
567
                    if ($needToReSave) {
568
                        ImageOptimize::$plugin->optimizedImages->resaveVolumeAssets($volume);
569
                    }
570
                }
571
            }
572
        }
573
    }
574
}
575