Passed
Push — develop ( e34a78...4b00a7 )
by Andrew
04:04
created

getCachedValues()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 4
rs 10
1
<?php
2
/**
3
 * Autocomplete plugin for Craft CMS 3.x
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) 2021 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) 2021 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 nystudio107\autocomplete\base\Generator;
16
17
use Craft;
18
19
/**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
20
 * @author    nystudio107
0 ignored issues
show
Coding Style introduced by
The tag in position 1 should be the @package tag
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
Tag value for @author tag indented incorrectly; expected 2 spaces but found 4
Loading history...
21
 * @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...
22
 * @since     1.0.0
0 ignored issues
show
Coding Style introduced by
The tag in position 3 should be the @author tag
Loading history...
Coding Style introduced by
Tag value for @since tag indented incorrectly; expected 3 spaces but found 5
Loading history...
23
 */
0 ignored issues
show
Coding Style introduced by
Missing @category tag in class comment
Loading history...
Coding Style introduced by
Missing @license tag in class comment
Loading history...
Coding Style introduced by
Missing @link tag in class comment
Loading history...
24
class AutocompleteTwigExtensionGenerator extends Generator
25
{
26
    // Constants
27
    // =========================================================================
28
    const CACHE_KEY = '_VALUES_CACHE';
29
30
    // Public Static Methods
31
    // =========================================================================
32
33
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
34
     * @inheritDoc
35
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
36
    public static function getGeneratorName(): string
37
    {
38
        return 'AutocompleteTwigExtension';
39
    }
40
41
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
42
     * @inheritDoc
43
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
44
    public static function generate()
45
    {
46
        // We always regenerate, to be context-sensitive based on the last page that was loaded/rendered
47
        self::generateInternal();
48
    }
49
50
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
51
     * @inheritDoc
52
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
53
    public static function regenerate()
54
    {
55
        static::clearCachedValues();
56
        self::generateInternal();
57
    }
58
59
    // Private Static Methods
60
    // =========================================================================
61
62
    /**
63
     * Core function that generates the autocomplete class
64
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
65
    private static function generateInternal()
0 ignored issues
show
Coding Style introduced by
Private method name "AutocompleteTwigExtensionGenerator::generateInternal" must be prefixed with an underscore
Loading history...
66
    {
67
        // Start from the cache values, so the auto-complete variables are additive for generation
68
        $values = static::getCachedValues();
69
        // Route variables are not merged in until the template is rendered, so do it here manually
70
        /* @noinspection PhpInternalEntityUsedInspection */
71
        $globals = array_merge(
72
            Craft::$app->view->getTwig()->getGlobals(),
73
            Craft::$app->controller->actionParams['variables'] ?? []
74
        );
75
        foreach ($globals as $key => $value) {
76
            $type = gettype($value);
77
            switch ($type) {
78
                case 'object':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
79
                    $values[$key] = 'new \\' . get_class($value) . '()';
80
                    break;
81
82
                case 'boolean':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
83
                    $values[$key] = $value ? 'true' : 'false';
84
                    break;
85
86
                case 'integer':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
87
                case 'double':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
88
                    $values[$key] = $value;
89
                    break;
90
91
                case 'string':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
92
                    $values[$key] = "'" . addslashes($value) . "'";
93
                    break;
94
95
                case 'array':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
96
                    $values[$key] = '[]';
97
                    break;
98
99
                case 'NULL':
0 ignored issues
show
Coding Style introduced by
Line indented incorrectly; expected 12 spaces, found 16
Loading history...
100
                    $values[$key] = 'null';
101
                    break;
102
            }
103
        }
104
105
        // Override values that should be used for autocompletion
106
        static::overrideValues($values);
107
        // Cache the values
108
        static::setCachedValues($values);
109
        // Format the line output for each value
110
        foreach ($values as $key => $value) {
111
            $values[$key] = "            '" . $key . "' => " . $value . ",";
112
        }
113
114
        // Save the template with variable substitution
115
        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...
116
            '{{ globals }}' => implode(PHP_EOL, $values),
117
        ]);
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...
118
    }
119
120
    /**
121
     * Get the cached values
122
     *
123
     * @return array
124
     */
125
    private static function getCachedValues(): array
0 ignored issues
show
Coding Style introduced by
Private method name "AutocompleteTwigExtensionGenerator::getCachedValues" must be prefixed with an underscore
Loading history...
126
    {
127
        $cache = Craft::$app->getCache();
128
        return $cache->get(static::getCacheKey()) ?: [];
129
    }
130
131
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $values should have a doc-comment as per coding-style.
Loading history...
132
     * Set the cached values
133
     *
134
     * @return array
135
     */
136
    private static function setCachedValues(array $values)
0 ignored issues
show
Coding Style introduced by
Private method name "AutocompleteTwigExtensionGenerator::setCachedValues" must be prefixed with an underscore
Loading history...
137
    {
138
        $cache = Craft::$app->getCache();
139
        $cache->set(static::getCacheKey(), $values, 0);
140
    }
141
142
    /**
143
     * Clear the cached values
144
     *
145
     * @return array
146
     */
147
    private static function clearCachedValues()
0 ignored issues
show
Coding Style introduced by
Private method name "AutocompleteTwigExtensionGenerator::clearCachedValues" must be prefixed with an underscore
Loading history...
148
    {
149
        $cache = Craft::$app->getCache();
150
        $cache->delete(static::getCacheKey());
151
    }
152
153
    /**
154
     * Get the cached key
155
     *
156
     * @return string
157
     */
158
    private static function getCacheKey(): string
0 ignored issues
show
Coding Style introduced by
Private method name "AutocompleteTwigExtensionGenerator::getCacheKey" must be prefixed with an underscore
Loading history...
159
    {
160
        return static::getGeneratorName() . static::CACHE_KEY;
161
    }
162
163
    /**
164
     * Override certain values that we always want hard-coded
165
     *
166
     * @param array $values
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
167
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
168
    private static function overrideValues(array &$values)
0 ignored issues
show
Coding Style introduced by
Private method name "AutocompleteTwigExtensionGenerator::overrideValues" must be prefixed with an underscore
Loading history...
169
    {
170
        // Swap in our variable in place of the `craft` variable
171
        $values['craft'] = 'new \nystudio107\autocomplete\variables\AutocompleteVariable()';
172
173
        // Set the current user to a new user, so it is never `null`
174
        $values['currentUser'] = 'new \craft\elements\User()';
175
176
        // Set the nonce to a blank string, as it changes on every request
177
        $values['nonce'] = "''";
178
    }
179
}
180