Passed
Push — master ( 6afa72...f96468 )
by M. Mikkel
04:08
created

CacheFlag   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 77
c 1
b 0
f 0
dl 0
loc 166
rs 10
wmc 18

3 Methods

Rating   Name   Duplication   Size   Complexity  
A maybeRegisterResources() 0 17 5
C addElementEventListeners() 0 67 12
A init() 0 41 1
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\Structures;
28
use craft\utilities\ClearCaches;
29
use craft\web\UrlManager;
30
use craft\web\twig\variables\CraftVariable;
31
use craft\web\View;
32
33
use yii\base\Event;
34
use yii\base\InvalidConfigException;
35
36
use mmikkel\cacheflag\services\CacheFlagService;
37
use mmikkel\cacheflag\services\TemplateCachesService;
38
use mmikkel\cacheflag\twigextensions\Extension as CacheFlagTwigExtension;
39
use mmikkel\cacheflag\variables\CpVariable;
40
41
/**
42
 * Class CacheFlag
43
 *
44
 * @author    Mats Mikkel Rummelhoff
45
 * @package   CacheFlag
46
 * @since     1.0.0
47
 *
48
 * @property  CacheFlagService $cacheFlag
49
 * @property  TemplateCachesService $templateCaches
50
 */
51
class CacheFlag extends Plugin
52
{
53
    // Static Properties
54
    // =========================================================================
55
56
    /**
57
     * @var CacheFlag
58
     */
59
    public static $plugin;
60
61
    // Public Properties
62
    // =========================================================================
63
64
    /**
65
     * @var string
66
     */
67
    public $schemaVersion = '1.0.0';
68
69
    // Public Methods
70
    // =========================================================================
71
72
    /**
73
     * @inheritdoc
74
     */
75
    public function init()
76
    {
77
        parent::init();
78
        self::$plugin = $this;
79
80
        // Register services
81
        $this->setComponents([
82
            'cacheFlag' => CacheFlagService::class,
83
            'templateCaches' => TemplateCachesService::class,
84
        ]);
85
86
        Craft::$app->getView()->registerTwigExtension(new CacheFlagTwigExtension());
87
88
        $this->addElementEventListeners();
89
90
        Event::on(ClearCaches::class, ClearCaches::EVENT_REGISTER_CACHE_OPTIONS,
91
            static function (RegisterCacheOptionsEvent $event) {
92
                $event->options[] = [
93
                    'key' => 'cacheflag-flagged-caches',
94
                    'label' => Craft::t('cache-flag', 'Flagged template caches'),
95
                    'action' => [CacheFlag::getInstance()->cacheFlag, 'invalidateAllFlaggedCaches'],
96
                    'info' => Craft::t('cache-flag', 'All template caches flagged using Cache Flag'),
97
                ];
98
            }
99
        );
100
101
        Event::on(
102
            Plugins::class,
103
            Plugins::EVENT_AFTER_LOAD_PLUGINS,
104
            function () {
105
                $this->maybeRegisterResources();
106
            }
107
        );
108
109
        Craft::info(
110
            Craft::t(
111
                'cache-flag',
112
                '{name} plugin loaded',
113
                ['name' => $this->name]
114
            ),
115
            __METHOD__
116
        );
117
    }
118
119
    // Protected Methods
120
    // =========================================================================
121
122
    /**
123
     * Add event listeners for cache breaking
124
     */
125
    protected function addElementEventListeners()
126
    {
127
        Event::on(
128
            Elements::class,
129
            Elements::EVENT_AFTER_SAVE_ELEMENT,
130
            function (ElementEvent $event) {
131
                $element = $event->element;
132
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
133
                    return;
134
                }
135
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
136
            }
137
        );
138
139
        Event::on(
140
            Elements::class,
141
            Elements::EVENT_BEFORE_DELETE_ELEMENT,
142
            function (ElementEvent $event) {
143
                $element = $event->element;
144
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
145
                    return;
146
                }
147
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
148
            }
149
        );
150
151
        Event::on(
152
            Structures::class,
153
            Structures::EVENT_AFTER_MOVE_ELEMENT,
154
            function (MoveElementEvent $event) {
155
                $element = $event->element;
156
                if (!$element || ElementHelper::isDraftOrRevision($element)) {
157
                    return;
158
                }
159
                CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
160
            }
161
        );
162
163
        Event::on(
164
            Elements::class,
165
            Elements::EVENT_AFTER_PERFORM_ACTION,
166
            function (ElementActionEvent $event) {
167
168
                /* @var ElementQueryInterface|null $criteria */
169
                $criteria = $event->criteria;
170
171
                if (!$criteria) {
172
                    return;
173
                }
174
175
                /* @var ElementActionInterface|null $action */
176
                $action = $event->action;
177
178
                if (!$action || !\in_array(\get_class($action), [
179
                        SetStatus::class,
180
                    ])) {
181
                    return;
182
                }
183
184
                /** @var ElementInterface[] $elements */
185
                $elements = $criteria->all();
186
187
                foreach ($elements as $element) {
188
                    if (ElementHelper::isDraftOrRevision($element)) {
189
                        continue;
190
                    }
191
                    CacheFlag::$plugin->cacheFlag->invalidateFlaggedCachesByElement($element);
192
                }
193
            }
194
        );
195
    }
196
197
    /**
198
     *  Maybe register CP assets bundle and variable
199
     */
200
    protected function maybeRegisterResources()
201
    {
202
203
        $request = Craft::$app->getRequest();
204
205
        if (!Craft::$app->getUser() || !$request->getIsCpRequest() || $request->getIsConsoleRequest() || ($request->getSegments()[0] ?? null) !== 'cache-flag') {
206
            return;
207
        }
208
209
        // Register CP variable
210
        Event::on(
211
            CraftVariable::class,
212
            CraftVariable::EVENT_INIT,
213
            function (Event $event) {
214
                /** @var CraftVariable $variable */
215
                $variable = $event->sender;
216
                $variable->set('cacheFlag', CpVariable::class);
217
            }
218
        );
219
    }
220
221
}
222