Passed
Push — develop ( 3e17fa...313af9 )
by M. Mikkel
03:39
created

CacheFlag::addElementEventListeners()   C

Complexity

Conditions 12
Paths 1

Size

Total Lines 71
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 40
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 71
rs 6.9666

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
        // Add option to the Clear Caches utility to invalidate all flagged caches
94
        Event::on(ClearCaches::class, ClearCaches::EVENT_REGISTER_CACHE_OPTIONS,
95
            static function (RegisterCacheOptionsEvent $event) {
96
                $event->options[] = [
97
                    'key' => 'cacheflag-flagged-caches',
98
                    'label' => Craft::t('cache-flag', 'Flagged template caches'),
99
                    'action' => [CacheFlag::getInstance()->cacheFlag, 'invalidateAllFlaggedCaches'],
100
                    'info' => Craft::t('cache-flag', 'All template caches flagged using Cache Flag'),
101
                ];
102
            }
103
        );
104
105
        // Register CP variable
106
        Event::on(
107
            CraftVariable::class,
108
            CraftVariable::EVENT_INIT,
109
            function (Event $event) {
110
                /** @var CraftVariable $variable */
111
                $variable = $event->sender;
112
                $variable->set('cacheFlagCp', CpVariable::class);
113
            }
114
        );
115
116
        $this->initProjectConfig();
117
118
        $this->addElementEventListeners();
119
120
        Craft::info(
121
            Craft::t(
122
                'cache-flag',
123
                '{name} plugin loaded',
124
                ['name' => $this->name]
125
            ),
126
            __METHOD__
127
        );
128
    }
129
130
    /** @inheritDoc */
131
    public function getCpNavItem()
132
    {
133
        if (!Craft::$app->getConfig()->getGeneral()->allowAdminChanges) {
134
            return null;
135
        }
136
        return parent::getCpNavItem();
137
    }
138
139
    /**
140
     *
141
     */
142
    protected function initProjectConfig()
143
    {
144
        Event::on(
145
            ProjectConfig::class,
146
            ProjectConfig::EVENT_REBUILD,
147
            [$this->projectConfig, 'onProjectConfigRebuild']
148
        );
149
150
        Craft::$app->projectConfig
151
            ->onAdd('cacheFlags.{uid}', [$this->projectConfig, 'onProjectConfigChange'])
152
            ->onUpdate('cacheFlags.{uid}', [$this->projectConfig, 'onProjectConfigChange'])
153
            ->onRemove('cacheFlags.{uid}', [$this->projectConfig, 'onProjectConfigDelete']);
154
155
        // Flush the project config when the plugin is uninstalled
156
        Event::on(
157
            Plugins::class,
158
            Plugins::EVENT_AFTER_UNINSTALL_PLUGIN,
159
            function (PluginEvent $event) {
160
                if ($event->plugin === $this) {
161
                    Craft::$app->getProjectConfig()->remove('cacheFlags');
162
                }
163
            }
164
        );
165
    }
166
167
    /**
168
     *
169
     */
170
    protected function addElementEventListeners()
171
    {
172
        // Invalidate flagged caches when elements are saved
173
        Event::on(
174
            Elements::class,
175
            Elements::EVENT_AFTER_SAVE_ELEMENT,
176
            function (ElementEvent $event) {
177
                $element = $event->element;
178
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
179
                    return;
180
                }
181
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
182
            }
183
        );
184
185
        // Invalidate flagged caches when elements are deleted
186
        Event::on(
187
            Elements::class,
188
            Elements::EVENT_BEFORE_DELETE_ELEMENT,
189
            function (ElementEvent $event) {
190
                $element = $event->element;
191
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
192
                    return;
193
                }
194
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
195
            }
196
        );
197
198
        // Invalidate flagged caches when structure entries are moved
199
        Event::on(
200
            Structures::class,
201
            Structures::EVENT_AFTER_MOVE_ELEMENT,
202
            function (MoveElementEvent $event) {
203
                $element = $event->element;
204
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
205
                    return;
206
                }
207
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
208
            }
209
        );
210
211
        // Invalidate flagged caches when elements change status
212
        Event::on(
213
            Elements::class,
214
            Elements::EVENT_AFTER_PERFORM_ACTION,
215
            function (ElementActionEvent $event) {
216
217
                /* @var ElementQueryInterface|null $criteria */
218
                $criteria = $event->criteria;
219
220
                if (!$criteria) {
221
                    return;
222
                }
223
224
                /* @var ElementActionInterface|null $action */
225
                $action = $event->action;
226
227
                if (!$action || !\in_array(\get_class($action), [
228
                        SetStatus::class,
229
                    ])) {
230
                    return;
231
                }
232
233
                /** @var ElementInterface[] $elements */
234
                $elements = $criteria->all();
235
236
                foreach ($elements as $element) {
237
                    if (ElementHelper::isDraftOrRevision($element)) {
238
                        continue;
239
                    }
240
                    CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
241
                }
242
            }
243
        );
244
    }
245
246
}
247