Passed
Push — master ( 1ca40c...54695a )
by Josh
07:44 queued 11s
created

Spoon::getSettingsResponse()   B

Complexity

Conditions 10
Paths 2

Size

Total Lines 65
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 32
c 1
b 0
f 0
dl 0
loc 65
rs 7.6666
cc 10
nc 2
nop 0

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
 * Spoon plugin for Craft CMS 3.x
4
 *
5
 * Enhance Matrix
6
 *
7
 * @link      https://angell.io
8
 * @copyright Copyright (c) 2018 Angell & Co
9
 */
10
11
namespace angellco\spoon;
12
13
use angellco\spoon\models\Settings;
14
use angellco\spoon\services\BlockTypes;
15
use angellco\spoon\services\Fields as FieldsService;
16
use angellco\spoon\services\BlockTypes as BlockTypesService;
17
use angellco\spoon\services\Loader as LoaderService;
18
use angellco\spoon\helpers\ProjectConfig as ProjectConfigHelper;
19
20
use Craft;
21
use craft\base\Plugin;
22
use craft\events\RebuildConfigEvent;
23
use craft\helpers\Db;
24
use craft\services\Plugins;
25
use craft\services\ProjectConfig;
26
27
use yii\base\Event;
28
29
/**
30
 * Craft plugins are very much like little applications in and of themselves. We’ve made
31
 * it as simple as we can, but the training wheels are off. A little prior knowledge is
32
 * going to be required to write a plugin.
33
 *
34
 * For the purposes of the plugin docs, we’re going to assume that you know PHP and SQL,
35
 * as well as some semi-advanced concepts like object-oriented programming and PHP namespaces.
36
 *
37
 * https://craftcms.com/docs/plugins/introduction
38
 *
39
 * @author    Angell & Co
40
 * @package   Spoon
41
 * @since     3.0.0
42
 *
43
 * @property  FieldsService $fields
44
 * @property  BlockTypesService $blockTypes
45
 * @property  LoaderService $loader
46
 * @method    Settings getSettings()
47
 */
48
class Spoon extends Plugin
49
{
50
    // Static Properties
51
    // =========================================================================
52
53
    /**
54
     * Static property that is an instance of this plugin class so that it can be accessed via
55
     * Spoon::$plugin
56
     *
57
     * @var Spoon
58
     */
59
    public static $plugin;
60
61
    // Public Properties
62
    // =========================================================================
63
64
    /**
65
     * To execute your plugin’s migrations, you’ll need to increase its schema version.
66
     *
67
     * @var string
68
     */
69
    public $schemaVersion = '3.4.0';
70
71
    // Public Methods
72
    // =========================================================================
73
74
    /**
75
     * Set our $plugin static property to this class so that it can be accessed via
76
     * Spoon::$plugin
77
     *
78
     * Called after the plugin class is instantiated; do any one-time initialization
79
     * here such as hooks and events.
80
     *
81
     * If you have a '/vendor/autoload.php' file, it will be loaded for you automatically;
82
     * you do not need to load it in your init() method.
83
     *
84
     */
85
    public function init()
86
    {
87
        parent::init();
88
        self::$plugin = $this;
89
90
        // Wait until all the plugins have loaded before running the loader
91
        Event::on(
92
            Plugins::class,
93
            Plugins::EVENT_AFTER_LOAD_PLUGINS,
94
            function() {
95
                if ($this->isInstalled && !Craft::$app->plugins->doesPluginRequireDatabaseUpdate($this)) {
96
                    $this->loader->run();
97
                }
98
            }
99
        );
100
101
        // Project config listeners
102
        Craft::$app->projectConfig
103
            ->onAdd($this->blockTypes::CONFIG_BLOCKTYPE_KEY.'.{uid}', [$this->blockTypes, 'handleChangedBlockType'])
104
            ->onUpdate($this->blockTypes::CONFIG_BLOCKTYPE_KEY.'.{uid}', [$this->blockTypes, 'handleChangedBlockType'])
105
            ->onRemove($this->blockTypes::CONFIG_BLOCKTYPE_KEY.'.{uid}', [$this->blockTypes, 'handleDeletedBlockType']);
106
107
        // Project config rebuild listener
108
        Event::on(ProjectConfig::class, ProjectConfig::EVENT_REBUILD, function(RebuildConfigEvent $e) {
109
            $e->config[BlockTypes::CONFIG_BLOCKTYPE_KEY] = ProjectConfigHelper::rebuildProjectConfig();
110
        });
111
112
        // Log on load for debugging
113
        Craft::info(
114
            Craft::t(
115
                'spoon',
116
                '{name} plugin loaded',
117
                ['name' => $this->name]
118
            ),
119
            __METHOD__
120
        );
121
    }
122
123
    /**
124
     * Loads the edit page for the global context.
125
     *
126
     * @return mixed|\yii\web\Response
127
     * @throws \yii\base\InvalidConfigException
128
     */
129
    public function getSettingsResponse()
130
    {
131
        $variables['matrixFields'] = Spoon::$plugin->fields->getMatrixFields();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$variables was never initialized. Although not strictly required by PHP, it is generally a good practice to add $variables = array(); before regardless.
Loading history...
132
133
        $variables['globalSpoonedBlockTypes'] = Spoon::$plugin->blockTypes->getByContext('global', 'fieldId', true);
134
135
        // If Super Table is installed get all of the ST fields and store by child field context
136
        $superTablePlugin = \Craft::$app->plugins->getPlugin('super-table');
137
        if ($superTablePlugin && $variables['matrixFields']) {
138
            $superTableService = new \verbb\supertable\services\SuperTableService();
0 ignored issues
show
Bug introduced by
The type verbb\supertable\services\SuperTableService 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...
139
140
            foreach ($variables['matrixFields'] as $matrixField) {
141
                if (strpos($matrixField->context, 'superTableBlockType') === 0) {
142
                    $parts = explode(':', $matrixField->context);
143
                    if (isset($parts[1])) {
144
145
                        $superTableBlockTypeId = Db::idByUid('{{%supertableblocktypes}}', $parts[1]);
146
147
                        if ($superTableBlockTypeId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $superTableBlockTypeId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
148
                            /** @var \verbb\supertable\models\SuperTableBlockTypeModel $superTableBlockType */
149
                            $superTableBlockType = $superTableService->getBlockTypeById($superTableBlockTypeId);
150
151
                            /** @var \verbb\supertable\fields\SuperTableField $superTableField */
152
                            $superTableField = \Craft::$app->fields->getFieldById($superTableBlockType->fieldId);
153
154
                            $variables['superTableFields'][$matrixField->context] = [
155
                                'kind' => 'Super Table',
156
                                'field' => $superTableField,
157
                                'child' => false
158
                            ];
159
160
                            // If the context of _this_ field is inside a Matrix block ... then we need to do more inception
161
                            if (strpos($superTableField->context, 'matrixBlockType') === 0) {
162
                                $nestedParts = explode(':', $superTableField->context);
163
                                if (isset($nestedParts[1])) {
164
165
                                    $matrixBlockTypeId = Db::idByUid('{{%matrixblocktypes}}', $nestedParts[1]);
166
167
                                    if ($matrixBlockTypeId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $matrixBlockTypeId of type integer|null is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
168
                                        /** @var craft\models\MatrixBlockType $matrixBlockType */
169
                                        $matrixBlockType = \Craft::$app->matrix->getBlockTypeById($matrixBlockTypeId);
170
171
                                        /** @var craft\fields\Matrix $globalField */
172
                                        $globalField = \Craft::$app->fields->getFieldById($matrixBlockType->fieldId);
0 ignored issues
show
Bug introduced by
It seems like $matrixBlockType->fieldId can also be of type null; however, parameter $fieldId of craft\services\Fields::getFieldById() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

172
                                        $globalField = \Craft::$app->fields->getFieldById(/** @scrutinizer ignore-type */ $matrixBlockType->fieldId);
Loading history...
173
174
                                        $variables['superTableFields'][$matrixField->context] = [
175
                                            'kind' => 'Matrix',
176
                                            'field' => $globalField,
177
                                            'child' => [
178
                                                'kind' => 'Super Table',
179
                                                'field' => $superTableField
180
                                            ]
181
                                        ];
182
                                    }
183
                                }
184
                            }
185
                        }
186
                    }
187
                }
188
            }
189
        }
190
191
        Spoon::$plugin->loader->configurator('#spoon-global-context-table', 'global');
192
193
        return Craft::$app->controller->renderTemplate('spoon/edit-global-context', $variables);
194
    }
195
196
    // Protected Methods
197
    // =========================================================================
198
199
    /**
200
     * @inheritdoc
201
     */
202
    protected function createSettingsModel()
203
    {
204
        return new Settings();
205
    }
206
207
}
208