Passed
Push — develop ( 7a41ad...3e17fa )
by M. Mikkel
04:08
created

CacheFlag::init()   C

Complexity

Conditions 13
Paths 1

Size

Total Lines 141
Code Lines 80

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 80
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 141
rs 5.7295

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Cache Flag plugin for Craft CMS 3.x
4
 *
5
 * Flag and clear template caches.
6
 *
7
 * @link      https://vaersaagod.no
8
 * @copyright Copyright (c) 2018 Mats Mikkel Rummelhoff
9
 */
10
11
namespace mmikkel\cacheflag;
12
13
use Craft;
14
use craft\base\ElementInterface;
15
use craft\base\Plugin;
16
use craft\elements\actions\SetStatus;
17
use craft\events\ElementEvent;
18
use craft\events\ElementActionEvent;
19
use craft\events\MergeElementsEvent;
20
use craft\events\MoveElementEvent;
21
use craft\events\PluginEvent;
22
use craft\events\RegisterCacheOptionsEvent;
23
use craft\events\TemplateEvent;
24
use craft\helpers\ElementHelper;
25
use craft\services\Elements;
26
use craft\services\Plugins;
27
use craft\services\ProjectConfig;
28
use craft\services\Structures;
29
use craft\utilities\ClearCaches;
30
use craft\web\UrlManager;
31
use craft\web\twig\variables\CraftVariable;
32
use craft\web\View;
33
34
use yii\base\Event;
35
use yii\base\InvalidConfigException;
36
37
use mmikkel\cacheflag\services\CacheFlagService;
38
use mmikkel\cacheflag\services\ProjectConfig as CacheFlagProjectConfigService;
39
use mmikkel\cacheflag\services\TemplateCachesService;
40
use mmikkel\cacheflag\twigextensions\Extension as CacheFlagTwigExtension;
41
use mmikkel\cacheflag\variables\CpVariable;
42
43
/**
44
 * Class CacheFlag
45
 *
46
 * @author    Mats Mikkel Rummelhoff
47
 * @package   CacheFlag
48
 * @since     1.0.0
49
 *
50
 * @property CacheFlagService $cacheFlag
51
 * @property CacheFlagProjectConfigService $projectConfig
52
 * @property TemplateCachesService $templateCaches
53
 */
54
class CacheFlag extends Plugin
55
{
56
    // Static Properties
57
    // =========================================================================
58
59
    /**
60
     * @var CacheFlag
61
     */
62
    public static $plugin;
63
64
    // Public Properties
65
    // =========================================================================
66
67
    /**
68
     * @var string
69
     */
70
    public $schemaVersion = '1.0.1';
71
72
    // Public Methods
73
    // =========================================================================
74
75
    /**
76
     * @inheritdoc
77
     */
78
    public function init()
79
    {
80
        parent::init();
81
        self::$plugin = $this;
82
83
        // Register services
84
        $this->setComponents([
85
            'cacheFlag' => CacheFlagService::class,
86
            'projectConfig' => CacheFlagProjectConfigService::class,
87
            'templateCaches' => TemplateCachesService::class,
88
        ]);
89
90
        // Register custom Twig extension
91
        Craft::$app->getView()->registerTwigExtension(new CacheFlagTwigExtension());
92
93
        // Invalidate flagged caches when elements are saved
94
        Event::on(
95
            Elements::class,
96
            Elements::EVENT_AFTER_SAVE_ELEMENT,
97
            function (ElementEvent $event) {
98
                $element = $event->element;
99
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
100
                    return;
101
                }
102
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
103
            }
104
        );
105
106
        // Invalidate flagged caches when elements are deleted
107
        Event::on(
108
            Elements::class,
109
            Elements::EVENT_BEFORE_DELETE_ELEMENT,
110
            function (ElementEvent $event) {
111
                $element = $event->element;
112
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
113
                    return;
114
                }
115
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
116
            }
117
        );
118
119
        // Invalidate flagged caches when structure entries are moved
120
        Event::on(
121
            Structures::class,
122
            Structures::EVENT_AFTER_MOVE_ELEMENT,
123
            function (MoveElementEvent $event) {
124
                $element = $event->element;
125
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
126
                    return;
127
                }
128
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
129
            }
130
        );
131
132
        // Invalidate flagged caches when elements change status
133
        Event::on(
134
            Elements::class,
135
            Elements::EVENT_AFTER_PERFORM_ACTION,
136
            function (ElementActionEvent $event) {
137
138
                /* @var ElementQueryInterface|null $criteria */
139
                $criteria = $event->criteria;
140
141
                if (!$criteria) {
142
                    return;
143
                }
144
145
                /* @var ElementActionInterface|null $action */
146
                $action = $event->action;
147
148
                if (!$action || !\in_array(\get_class($action), [
149
                        SetStatus::class,
150
                    ])) {
151
                    return;
152
                }
153
154
                /** @var ElementInterface[] $elements */
155
                $elements = $criteria->all();
156
157
                foreach ($elements as $element) {
158
                    if (ElementHelper::isDraftOrRevision($element)) {
159
                        continue;
160
                    }
161
                    CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
162
                }
163
            }
164
        );
165
166
        // Add option to the Clear Caches utility to invalidate all flagged caches
167
        Event::on(ClearCaches::class, ClearCaches::EVENT_REGISTER_CACHE_OPTIONS,
168
            static function (RegisterCacheOptionsEvent $event) {
169
                $event->options[] = [
170
                    'key' => 'cacheflag-flagged-caches',
171
                    'label' => Craft::t('cache-flag', 'Flagged template caches'),
172
                    'action' => [CacheFlag::getInstance()->cacheFlag, 'invalidateAllFlaggedCaches'],
173
                    'info' => Craft::t('cache-flag', 'All template caches flagged using Cache Flag'),
174
                ];
175
            }
176
        );
177
178
        // Register CP variable
179
        Event::on(
180
            CraftVariable::class,
181
            CraftVariable::EVENT_INIT,
182
            function (Event $event) {
183
                /** @var CraftVariable $variable */
184
                $variable = $event->sender;
185
                $variable->set('cacheFlagCp', CpVariable::class);
186
            }
187
        );
188
189
        // Support Project Config rebuild
190
        Event::on(
191
            ProjectConfig::class,
192
            ProjectConfig::EVENT_REBUILD,
193
            [$this->projectConfig, 'onProjectConfigRebuild']
194
        );
195
196
        Craft::$app->projectConfig
197
            ->onAdd('cacheFlags.{uid}', [$this->projectConfig, 'onProjectConfigChange'])
198
            ->onUpdate('cacheFlags.{uid}', [$this->projectConfig, 'onProjectConfigChange'])
199
            ->onRemove('cacheFlags.{uid}', [$this->projectConfig, 'onProjectConfigDelete']);
200
201
        // Flush the project config when the plugin is uninstalled
202
        Event::on(
203
            Plugins::class,
204
            Plugins::EVENT_AFTER_UNINSTALL_PLUGIN,
205
            function (PluginEvent $event) {
206
                if ($event->plugin === $this) {
207
                    Craft::$app->getProjectConfig()->remove('cacheFlags');
208
                }
209
            }
210
        );
211
212
        Craft::info(
213
            Craft::t(
214
                'cache-flag',
215
                '{name} plugin loaded',
216
                ['name' => $this->name]
217
            ),
218
            __METHOD__
219
        );
220
    }
221
222
}
223