Passed
Push — v1 ( de0b85...7efdab )
by Andrew
15:48 queued 11:42
created

AutocompleteService::getTwigfieldPublishUrl()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 10
1
<?php
2
/**
3
 * Twigfield for Craft CMS
4
 *
5
 * Provides a twig editor field with Twig & Craft API autocomplete
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
 * @copyright Copyright (c) 2022 nystudio107
0 ignored issues
show
Coding Style introduced by
@copyright tag must contain a year and the name of the copyright holder
Loading history...
9
 */
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...
10
11
namespace nystudio107\twigfield\services;
12
13
use Craft;
14
use craft\base\Component;
15
use nystudio107\twigfield\base\Autocomplete as BaseAutoComplete;
16
use nystudio107\twigfield\events\RegisterTwigfieldAutocompletesEvent;
17
use nystudio107\twigfield\Twigfield;
18
use yii\caching\TagDependency;
19
20
/**
21
 * Class Autocomplete
22
 *
23
 * @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...
24
 * @package   Twigfield
0 ignored issues
show
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
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...
26
 */
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...
27
class AutocompleteService extends Component
28
{
29
    // Constants
30
    // =========================================================================
31
32
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
33
     * @event RegisterTwigfieldAutocompletesEvent The event that is triggered when registering
34
     *        Twigfield Autocomplete types
35
     *
36
     * Autocomplete Generator types must implement [[AutocompleteInterface]]. [[AutoComplete]]
37
     * provides a base implementation.
38
     *
39
     * ```php
40
     * use nystudio107\twigfield\services\AutocompleteService;
41
     * use nystudio107\twigfield\events\RegisterTwigfieldAutocompletesEvent;
42
     * use yii\base\Event;
43
     *
44
     * Event::on(AutocompleteService::class,
45
     *     AutocompleteService::EVENT_REGISTER_TWIGFIELD_AUTOCOMPLETES,
46
     *     function(RegisterTwigfieldAutocompletesEvent $event) {
47
     *         $event->types[] = MyAutocomplete::class;
48
     *     }
49
     * );
50
     *
51
     * or to pass in a config array for the Autocomplete object:
52
     *
53
     * Event::on(AutocompleteService::class,
54
     *     AutocompleteService::EVENT_REGISTER_TWIGFIELD_AUTOCOMPLETES,
55
     *     function(RegisterTwigfieldAutocompletesEvent $event) {
56
     *         $config = [
57
     *             'property' => value,
58
     *         ];
59
     *         $event->types[] = [MyAutocomplete::class => $config];
60
     *     }
61
     * );
62
     *
63
     * ```
64
     */
65
    const EVENT_REGISTER_TWIGFIELD_AUTOCOMPLETES = 'registerTwigfieldAutocompletes';
66
67
    const AUTOCOMPLETE_CACHE_TAG = 'TwigFieldAutocompleteTag';
68
69
    // Public Properties
70
    // =========================================================================
71
72
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
73
     * @var string Prefix for the cache key
74
     */
75
    public $cacheKeyPrefix = 'TwigFieldAutocomplete';
76
77
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
78
     * @var int Cache duration
79
     */
80
    public $cacheDuration = 3600;
81
82
    // Public Methods
83
    // =========================================================================
84
85
    /**
0 ignored issues
show
Coding Style introduced by
Missing short description in doc comment
Loading history...
86
     * @inerhitDoc
87
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
88
    public function init(): void
89
    {
90
        // Short cacheDuration if we're in devMode
91
        if (Craft::$app->getConfig()->getGeneral()->devMode) {
92
            $this->cacheDuration = 1;
93
        }
94
        parent::init();
95
    }
96
97
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $fieldType should have a doc-comment as per coding-style.
Loading history...
98
     * Call each of the autocompletes to generate their complete items
99
     */
0 ignored issues
show
Coding Style introduced by
Missing @return tag in function comment
Loading history...
100
    public function generateAutocompletes(string $fieldType = Twigfield::DEFAULT_FIELD_TYPE): array
101
    {
102
        $autocompleteItems = [];
103
        $autocompletes = $this->getAllAutocompleteGenerators($fieldType);
104
        foreach ($autocompletes as $autocompleteGenerator) {
105
            /* @var BaseAutoComplete $autocomplete */
106
            // Assume the generator is a class name string
107
            $config = [];
108
            $autocompleteClass = $autocompleteGenerator;
109
            // If we're passed in an array instead, extract the class name and config from the key/value pair
110
            // in the form of [className => configArray]
111
            if (is_array($autocompleteGenerator)) {
112
                $autocompleteClass = array_key_first($autocompleteGenerator);
113
                $config = $autocompleteGenerator[$autocompleteClass];
114
            }
115
            $autocomplete = new $autocompleteClass($config);
116
            $name = $autocomplete->name;
117
            // Set up the cache parameters
118
            $cache = Craft::$app->getCache();
119
            $cacheKey = $this->cacheKeyPrefix . $name;
120
            $dependency = new TagDependency([
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...
121
                'tags' => [
122
                    self::AUTOCOMPLETE_CACHE_TAG,
123
                    self::AUTOCOMPLETE_CACHE_TAG . $name,
124
                ],
125
            ]);
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...
126
            // Get the autocompletes from the cache, or generate them if they aren't cached
127
            $autocompleteItems[$name] = $cache->getOrSet($cacheKey, static function () use ($name, $autocomplete) {
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...
128
                $autocomplete->generateCompleteItems();
129
                return [
130
                    'name' => $name,
131
                    'type' => $autocomplete->type,
132
                    'hasSubProperties' => $autocomplete->hasSubProperties,
133
                    BaseAutoComplete::COMPLETION_KEY => $autocomplete->getCompleteItems(),
134
                ];
135
            }, $this->cacheDuration, $dependency);
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...
136
        }
137
        Craft::info('Twigfield Autocompletes generated', __METHOD__);
138
139
        return $autocompleteItems;
140
    }
141
142
    /**
143
     * Clear the specified autocomplete cache (or all autocomplete caches if left empty)
144
     *
145
     * @param string $autocompleteName
0 ignored issues
show
Coding Style introduced by
Missing parameter comment
Loading history...
Coding Style introduced by
Tag value for @param tag indented incorrectly; expected 2 spaces but found 1
Loading history...
146
     * @return void
0 ignored issues
show
Coding Style introduced by
Tag @return cannot be grouped with parameter tags in a doc comment
Loading history...
147
     */
148
    public function clearAutocompleteCache(string $autocompleteName = ''): void
149
    {
150
        $cache = Craft::$app->getCache();
151
        TagDependency::invalidate($cache, self::AUTOCOMPLETE_CACHE_TAG . $autocompleteName);
152
        Craft::info('Twigfield caches invalidated', __METHOD__);
153
    }
154
155
    // Protected Methods
156
    // =========================================================================
157
158
    /**
0 ignored issues
show
Coding Style introduced by
Parameter $fieldType should have a doc-comment as per coding-style.
Loading history...
159
     * Returns all available autocompletes classes.
160
     *
161
     * @return string[] The available autocompletes classes
162
     */
163
    public function getAllAutocompleteGenerators(string $fieldType = Twigfield::DEFAULT_FIELD_TYPE): array
164
    {
165
        $event = new RegisterTwigfieldAutocompletesEvent([
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...
166
            'types' => Twigfield::$settings->defaultTwigfieldAutocompletes,
167
            'fieldType' => $fieldType,
168
        ]);
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...
169
        $this->trigger(self::EVENT_REGISTER_TWIGFIELD_AUTOCOMPLETES, $event);
170
171
        return $event->types;
172
    }
173
}
174