Passed
Push — master ( 207640...c55bfc )
by M. Mikkel
04:28
created

Reasons::init()   C

Complexity

Conditions 10
Paths 1

Size

Total Lines 115
Code Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 10
eloc 72
c 3
b 0
f 0
nc 1
nop 0
dl 0
loc 115
rs 6.7442

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
 * Reasons plugin for Craft CMS 3.x
4
 *
5
 * Adds conditionals to field layouts.
6
 *
7
 * @link      https://vaersaagod.no
8
 * @copyright Copyright (c) 2020 Mats Mikkel Rummelhoff
9
 */
10
11
namespace mmikkel\reasons;
12
13
use mmikkel\reasons\assetbundles\reasons\ReasonsAssetBundle;
14
use mmikkel\reasons\services\ReasonsService;
15
16
use Craft;
17
use craft\base\Plugin;
18
use craft\elements\Asset;
19
use craft\elements\Category;
20
use craft\elements\Entry;
21
use craft\elements\GlobalSet;
22
use craft\elements\Tag;
23
use craft\elements\User;
24
use craft\events\ConfigEvent;
25
use craft\events\FieldLayoutEvent;
26
use craft\events\PluginEvent;
27
use craft\events\TemplateEvent;
28
use craft\services\Fields;
29
use craft\services\Plugins;
30
use craft\services\ProjectConfig;
31
use craft\web\View;
32
33
use yii\base\Event;
34
use yii\base\InvalidConfigException;
35
36
/**
37
 * Class Reasons
38
 *
39
 * @author    Mats Mikkel Rummelhoff
40
 * @package   Reasons
41
 * @since     2.0.0
42
 *
43
 * @property  ReasonsService $reasons
44
 */
45
class Reasons extends Plugin
46
{
47
    // Static Properties
48
    // =========================================================================
49
50
    /**
51
     * @var Reasons
52
     */
53
    public static $plugin;
54
55
    // Public Properties
56
    // =========================================================================
57
58
    /**
59
     * @var string
60
     */
61
    public $schemaVersion = '2.1.1';
62
63
    /**
64
     * @var bool
65
     */
66
    public $hasCpSettings = false;
67
68
    /**
69
     * @var bool
70
     */
71
    public $hasCpSection = false;
72
73
    // Public Methods
74
    // =========================================================================
75
76
    /**
77
     * @inheritdoc
78
     */
79
    public function init()
80
    {
81
        parent::init();
82
        self::$plugin = $this;
83
84
        $this->setComponents([
85
            'reasons' => ReasonsService::class,
86
        ]);
87
88
        Event::on(
89
            Plugins::class,
90
            Plugins::EVENT_AFTER_INSTALL_PLUGIN,
91
            function (PluginEvent $event) {
92
                if ($event->plugin === $this) {
93
                    $this->reasons->clearCache();
94
                }
95
            }
96
        );
97
98
        Event::on(
99
            Plugins::class,
100
            Plugins::EVENT_AFTER_UNINSTALL_PLUGIN,
101
            function (PluginEvent $event) {
102
                if ($event->plugin === $this) {
103
                    $this->reasons->clearCache();
104
                    Craft::$app->getProjectConfig()->remove('reasons_conditionals');
105
                }
106
            }
107
        );
108
109
        // Save or delete conditionals when field layout is saved
110
        Event::on(
111
            Fields::class,
112
            Fields::EVENT_AFTER_SAVE_FIELD_LAYOUT,
113
            function (FieldLayoutEvent $event) {
114
                if (Craft::$app->getRequest()->getIsConsoleRequest()) {
115
                    return;
116
                }
117
                $fieldLayout = $event->layout;
118
                if (!$fieldLayout) {
119
                    return;
120
                }
121
                $conditionals = Craft::$app->getRequest()->getBodyParam('_reasons', null);
122
                if ($conditionals === null) {
123
                    return;
124
                }
125
                try {
126
                    if ($conditionals) {
127
                        $this->reasons->saveFieldLayoutConditionals($fieldLayout, $conditionals);
128
                    } else {
129
                        $this->reasons->deleteFieldLayoutConditionals($fieldLayout);
130
                    }
131
                } catch (\Throwable $e) {
132
                    Craft::error($e->getMessage(), __METHOD__);
133
                    if (Craft::$app->getConfig()->getGeneral()->devMode) {
134
                        throw $e;
135
                    }
136
                }
137
            }
138
        );
139
140
        // Delete conditionals when field layouts are deleted
141
        Event::on(
142
            Fields::class,
143
            Fields::EVENT_AFTER_DELETE_FIELD_LAYOUT,
144
            function (FieldLayoutEvent $event) {
145
                $fieldLayout = $event->layout;
146
                if (!$fieldLayout) {
147
                    return;
148
                }
149
                $this->reasons->deleteFieldLayoutConditionals($fieldLayout);
150
            }
151
        );
152
153
        // Clear data caches when fields are saved
154
        Event::on(
155
            Fields::class,
156
            Fields::EVENT_AFTER_SAVE_FIELD,
157
            [$this->reasons, 'clearCache']
158
        );
159
160
        // Clear data caches when fields are deleted
161
        Event::on(
162
            Fields::class,
163
            Fields::EVENT_AFTER_DELETE_FIELD,
164
            [$this->reasons, 'clearCache']
165
        );
166
167
        // Support Project Config rebuild
168
        Event::on(
169
            ProjectConfig::class,
170
            ProjectConfig::EVENT_REBUILD,
171
            [$this->reasons, 'onProjectConfigRebuild']
172
        );
173
174
        // Listen for appropriate Project Config changes
175
        Craft::$app->projectConfig
176
            ->onAdd('reasons_conditionals.{uid}', [$this->reasons, 'onProjectConfigChange'])
0 ignored issues
show
Bug introduced by
The method onAdd() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

176
            ->/** @scrutinizer ignore-call */ 
177
              onAdd('reasons_conditionals.{uid}', [$this->reasons, 'onProjectConfigChange'])

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
177
            ->onUpdate('reasons_conditionals.{uid}', [$this->reasons, 'onProjectConfigChange'])
178
            ->onRemove('reasons_conditionals.{uid}', [$this->reasons, 'onProjectConfigDelete']);
179
180
        // Queue up asset bundle or handle AJAX action requests
181
        Event::on(
182
            Plugins::class,
183
            Plugins::EVENT_AFTER_LOAD_PLUGINS,
184
            [$this, 'initReasons']
185
        );
186
187
        Craft::info(
188
            Craft::t(
189
                'reasons',
190
                '{name} plugin loaded',
191
                ['name' => $this->name]
192
            ),
193
            __METHOD__
194
        );
195
    }
196
197
    /**
198
     * @return void
199
     */
200
    public function initReasons()
201
    {
202
203
        $request = Craft::$app->getRequest();
204
205
        /** @var User $user */
206
        $user = Craft::$app->getUser()->getIdentity();
207
208
        if ($request->getIsConsoleRequest() || !$request->getIsCpRequest() || $request->getIsSiteRequest() || !$user || !$user->can('accessCp')) {
209
            return;
210
        }
211
212
        $isAjax = $request->getIsAjax() || $request->getAcceptsJson();
213
        if ($isAjax) {
214
            $this->initAjaxRequest();
215
        } else {
216
            $this->registerAssetBundle();
217
        }
218
219
    }
220
221
    // Protected Methods
222
    // =========================================================================
223
224
    /**
225
     * @return void
226
     */
227
    protected function registerAssetBundle()
228
    {
229
        // Register asset bundle
230
        Event::on(
231
            View::class,
232
            View::EVENT_BEFORE_RENDER_TEMPLATE,
233
            function (/** @scrutinizer ignore-unused */ TemplateEvent $event) {
234
                try {
235
                    Craft::$app->getView()->registerAssetBundle(ReasonsAssetBundle::class);
236
                } catch (InvalidConfigException $e) {
237
                    Craft::error(
238
                        'Error registering AssetBundle - ' . $e->getMessage(),
239
                        __METHOD__
240
                    );
241
                }
242
            }
243
        );
244
    }
245
246
    /**
247
     * @return void
248
     */
249
    protected function initAjaxRequest()
250
    {
251
252
        $request = Craft::$app->getRequest();
253
        if (!$request->getIsPost() || !$request->getIsActionRequest()) {
254
            return;
255
        }
256
257
        $actionSegments = $request->getActionSegments();
258
        $actionSegment = $actionSegments[\count($actionSegments) - 1] ?? null;
259
260
        if (!$actionSegment) {
261
            return;
262
        }
263
264
        if ($actionSegment === 'switch-entry-type') {
265
            Craft::$app->getView()->registerJs('Craft.ReasonsPlugin.initPrimaryForm();');
266
            return;
267
        }
268
269
        if ($actionSegment === 'get-editor-html') {
270
271
            $elementId = (int)$request->getBodyParam('elementId');
272
273
            if (!$elementId) {
274
                return;
275
            }
276
277
            $element = Craft::$app->getElements()->getElementById($elementId);
278
            if ($element === null) {
279
                return;
280
            }
281
282
            $elementType = \get_class($element);
283
            $conditionalsKey = null;
284
285
            switch ($elementType) {
286
                case Entry::class:
287
                    /** @var Entry $element */
288
                    $conditionalsKey = "entryType:{$element->typeId}";
289
                    break;
290
291
                case GlobalSet::class:
292
                    /** @var GlobalSet $element */
293
                    $conditionalsKey = "globalSet:{$element->id}";
294
                    break;
295
296
                case Asset::class:
297
                    /** @var Asset $element */
298
                    $conditionalsKey = "assetSource:{$element->volumeId}";
299
                    break;
300
301
                case Category::class:
302
                    /** @var Category $element */
303
                    $conditionalsKey = "categoryGroup:{$element->groupId}";
304
                    break;
305
306
                case Tag::class:
307
                    /** @var Tag $element */
308
                    $conditionalsKey = "tagGroup:{$element->groupId}";
309
                    break;
310
311
                case User::class:
312
                    $conditionalsKey = "users";
313
                    break;
314
315
                default:
316
                    return;
317
318
            }
319
320
            Craft::$app->getView()->registerJs("Craft.ReasonsPlugin.initElementEditor('{$conditionalsKey}');");
321
322
        }
323
324
    }
325
326
}
327