generateInternal()   B
last analyzed

Complexity

Conditions 11
Paths 20

Size

Total Lines 59
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 1 Features 0
Metric Value
cc 11
eloc 37
c 5
b 1
f 0
nc 20
nop 0
dl 0
loc 59
rs 7.3166

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
 * Autocomplete module for Craft CMS
4
 *
5
 * Provides Twig template IDE autocomplete of Craft CMS & plugin variables
6
 *
7
 * @link      https://nystudio107.com
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @copyright tag
Loading history...
8
 * @link      https://putyourlightson.com
9
 * @copyright Copyright (c) nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
10
 * @copyright Copyright (c) PutYourLightsOn
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
11
 */
0 ignored issues
show
Coding Style introduced by
PHP version not specified
Loading history...
Coding Style introduced by
Missing @category tag in file comment
Loading history...
Coding Style introduced by
Missing @package tag in file comment
Loading history...
Coding Style introduced by
Missing @author tag in file comment
Loading history...
Coding Style introduced by
Missing @license tag in file comment
Loading history...
12
13
namespace nystudio107\autocomplete\generators;
14
15
use Craft;
16
use craft\base\Element;
17
use craft\web\twig\GlobalsExtension;
18
use nystudio107\autocomplete\base\Generator;
19
use nystudio107\autocomplete\events\DefineGeneratorValuesEvent;
20
use yii\base\Event;
21
22
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
23
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
Coding Style introduced by
Content of the @author tag must be in the form "Display Name <[email protected]>"
Loading history...
Coding Style introduced by
The tag in position 1 should be the @package tag
Loading history...
24
 * @package   autocomplete
0 ignored issues
show
Coding Style introduced by
Package name "autocomplete" is not valid; consider "Autocomplete" instead
Loading history...
Coding Style introduced by
Tag value for @package tag indented incorrectly; expected 1 spaces but found 3
Loading history...
25
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
26
 */
0 ignored issues
show
Coding Style introduced by
Missing @link tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @category tag in class comment
Loading history...
27
class AutocompleteTwigExtensionGenerator extends Generator
28
{
29
    // Constants
30
    // =========================================================================
31
32
    public const ELEMENT_ROUTE_EXCLUDES = [
33
        'matrixblock',
34
        'globalset',
35
    ];
36
37
    // Public Static Methods
38
    // =========================================================================
39
40
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
41
     * @inheritDoc
42
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
43
    public static function getGeneratorName(): string
44
    {
45
        return 'AutocompleteTwigExtension';
46
    }
47
48
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
49
     * @inheritDoc
50
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
51
    public static function generate()
52
    {
53
        if (self::shouldRegenerateFile()) {
54
            static::generateInternal();
55
        }
56
    }
57
58
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
59
     * @inheritDoc
60
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
61
    public static function regenerate()
62
    {
63
        self::generateInternal();
64
    }
65
66
    // Protected Static Methods
67
    // =========================================================================
68
69
    /**
70
     * Core function that generates the autocomplete class
71
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
72
    protected static function generateInternal()
73
    {
74
        $values = [];
75
        // Iterate through the globals in the Twig context
76
        /* @noinspection PhpInternalEntityUsedInspection */
77
        $globals = Craft::$app->view->getTwig()->getGlobals();
78
        foreach ($globals as $key => $value) {
79
            $type = gettype($value);
80
            switch ($type) {
81
                case 'object':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
82
                    $values[$key] = 'new \\' . get_class($value) . '()';
83
                    break;
84
85
                case 'boolean':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
86
                    $values[$key] = $value ? 'true' : 'false';
87
                    break;
88
89
                case 'integer':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
90
                case 'double':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
91
                    $values[$key] = $value;
92
                    break;
93
94
                case 'string':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
95
                    $values[$key] = "'" . addslashes($value) . "'";
96
                    break;
97
98
                case 'array':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
99
                    $values[$key] = '[]';
100
                    break;
101
102
                case 'NULL':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
103
                    $values[$key] = 'null';
104
                    break;
105
            }
106
        }
107
108
        // Mix in element route variables, and override values that should be used for autocompletion
109
        $values = array_merge(
110
            $values,
111
            static::elementRouteVariables(),
112
            static::globalVariables(),
113
            static::overrideValues()
114
        );
115
116
        // Allow plugins to modify the values
117
        $event = new DefineGeneratorValuesEvent([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
118
            'values' => $values,
119
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
120
        Event::trigger(self::class, self::EVENT_BEFORE_GENERATE, $event);
121
        $values = $event->values;
122
123
        // Format the line output for each value
124
        foreach ($values as $key => $value) {
125
            $values[$key] = "            '" . $key . "' => " . $value . ",";
126
        }
127
128
        // Save the template with variable substitution
129
        self::saveTemplate([
0 ignored issues
show
Coding Style introduced by
The opening parenthesis of a multi-line function call should be the last content on the line.
Loading history...
130
            '{{ globals }}' => implode(PHP_EOL, $values),
131
        ]);
0 ignored issues
show
Coding Style introduced by
For multi-line function calls, the closing parenthesis should be on a new line.

If a function call spawns multiple lines, the coding standard suggests to move the closing parenthesis to a new line:

someFunctionCall(
    $firstArgument,
    $secondArgument,
    $thirdArgument
); // Closing parenthesis on a new line.
Loading history...
132
    }
133
134
    /**
135
     * Add in the element types that could be injected as route variables
136
     *
137
     * @return array
138
     */
139
    protected static function elementRouteVariables(): array
140
    {
141
        $routeVariables = [];
142
        $elementTypes = Craft::$app->elements->getAllElementTypes();
0 ignored issues
show
Bug introduced by
The method getAllElementTypes() 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

142
        /** @scrutinizer ignore-call */ 
143
        $elementTypes = Craft::$app->elements->getAllElementTypes();

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...
143
        foreach ($elementTypes as $elementType) {
144
            /* @var Element $elementType */
145
            $key = $elementType::refHandle();
146
            if (!empty($key) && !in_array($key, static::ELEMENT_ROUTE_EXCLUDES, true)) {
147
                $routeVariables[$key] = 'new \\' . $elementType . '()';
148
            }
149
        }
150
151
        return $routeVariables;
152
    }
153
154
    /**
155
     * Add in the global variables manually, because Craft conditionally loads the GlobalsExtension as of
156
     * Craft CMS 3.7.8 only for frontend routes
157
     *
158
     * @return array
159
     */
160
    protected static function globalVariables(): array
161
    {
162
        $globalVariables = [];
163
        // See if the GlobalsExtension class is available (Craft CMS 3.7.8 or later) and use it
164
        if (class_exists(GlobalsExtension::class)) {
165
            $globalsExtension = new GlobalsExtension();
166
            foreach ($globalsExtension->getGlobals() as $key => $value) {
167
                $globalVariables[$key] = 'new \\' . get_class($value) . '()';
168
            }
169
170
            return $globalVariables;
171
        }
172
        // Fall back and get the globals ourselves
173
        foreach (Craft::$app->getGlobals()->getAllSets() as $globalSet) {
174
            $globalVariables[$globalSet->handle] = 'new \\' . get_class($globalSet) . '()';
175
        }
176
177
        return $globalVariables;
178
    }
179
180
    /**
181
     * Override certain values that we always want hard-coded
182
     *
183
     * @return array
184
     */
185
    protected static function overrideValues(): array
186
    {
187
        return [
188
            // Swap in our variable in place of the `craft` variable
189
            'craft' => 'new \nystudio107\autocomplete\variables\AutocompleteVariable()',
190
            // Set the current user to a new user, so it is never `null`
191
            'currentUser' => 'new \craft\elements\User()',
192
            // Set the nonce to a blank string, as it changes on every request
193
            'nonce' => "''",
194
        ];
195
    }
196
}
197