-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
Autocomplete.php
508 lines (485 loc) · 18.4 KB
/
Autocomplete.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
<?php
/**
* SEOmatic plugin for Craft CMS 3.x
*
* @link https://nystudio107.com/
* @copyright Copyright (c) 2021 nystudio107
* @license https://nystudio107.com/license
*/
namespace nystudio107\seomatic\helpers;
use Craft;
use craft\base\Element;
use craft\helpers\ArrayHelper;
use phpDocumentor\Reflection\DocBlockFactory;
use ReflectionClass;
use ReflectionException;
use ReflectionNamedType;
use ReflectionUnionType;
use yii\base\Behavior;
use yii\base\InvalidConfigException;
use yii\di\ServiceLocator;
/**
* @author nystudio107
* @package Seomatic
* @since 3.4.21
*/
class Autocomplete
{
// Constants
// =========================================================================
const COMPLETION_KEY = '__completions';
const EXCLUDED_PROPERTY_NAMES = [
'controller',
'Controller',
'CraftEdition',
'CraftSolo',
'CraftPro',
];
const EXCLUDED_BEHAVIOR_NAMES = [
'fieldHandles',
'hasMethods',
'owner',
];
const ELEMENT_ROUTE_EXCLUDES = [
'matrixblock',
'globalset'
];
const EXCLUDED_PROPERTY_REGEXES = [
'^_',
];
const EXCLUDED_METHOD_REGEXES = [
'^_',
];
// Faux enum, from: https://microsoft.github.io/monaco-editor/api/enums/monaco.languages.completionitemkind.html
const CompletionItemKind = [
'Class' => 5,
'Color' => 19,
'Constant' => 14,
'Constructor' => 2,
'Customcolor' => 22,
'Enum' => 15,
'EnumMember' => 16,
'Event' => 10,
'Field' => 3,
'File' => 20,
'Folder' => 23,
'Function' => 1,
'Interface' => 7,
'Issue' => 26,
'Keyword' => 17,
'Method' => 0,
'Module' => 8,
'Operator' => 11,
'Property' => 9,
'Reference' => 21,
'Snippet' => 27,
'Struct' => 6,
'Text' => 18,
'TypeParameter' => 24,
'Unit' => 12,
'User' => 25,
'Value' => 13,
'Variable' => 4,
];
const RECURSION_DEPTH_LIMIT = 10;
// Public Static Methods
// =========================================================================
/**
* Core function that generates the autocomplete array
* @param null $additionalCompletionsCacheKey
* @return array
*/
public static function generate($additionalCompletionsCacheKey = null): array
{
$completionList = [];
// Iterate through the globals in the Twig context
/* @noinspection PhpInternalEntityUsedInspection */
$globals = array_merge(
Craft::$app->view->getTwig()->getGlobals(),
self::elementRouteVariables(),
self::overrideValues()
);
foreach ($globals as $key => $value) {
if (!in_array($key, self::EXCLUDED_PROPERTY_NAMES, true)) {
$type = gettype($value);
switch ($type) {
case 'object':
self::parseObject($completionList, $key, $value, 0);
break;
case 'array':
case 'boolean':
case 'double':
case 'integer':
case 'string':
$kind = self::CompletionItemKind['Variable'];
$path = $key;
$normalizedKey = preg_replace("/[^A-Za-z]/", '', $key);
if (ctype_upper($normalizedKey)) {
$kind = self::CompletionItemKind['Constant'];
}
ArrayHelper::setValue($completionList, $path, [
self::COMPLETION_KEY => [
'detail' => "$value",
'kind' => $kind,
'label' => $key,
'insertText' => $key,
]
]);
break;
}
}
}
// Add in additional completion items from the cache, if present
if ($additionalCompletionsCacheKey) {
$cache = Craft::$app->getCache();
$additionalCompletions = $cache->get([self::class, $additionalCompletionsCacheKey]);
if ($additionalCompletions !== false && is_array($additionalCompletions)) {
$completionList = array_merge($completionList, $additionalCompletions);
}
}
return $completionList;
}
/**
* Parse the object passed in, including any properties or methods
*
* @param array $completionList
* @param string $name
* @param $object
* @param int $recursionDepth
* @param string $path
*/
public static function parseObject(array &$completionList, string $name, $object, int $recursionDepth, string $path = '')
{
// Only recurse `RECURSION_DEPTH_LIMIT` deep
if ($recursionDepth > self::RECURSION_DEPTH_LIMIT) {
return;
}
$recursionDepth++;
// Create the docblock factory
$factory = DocBlockFactory::createInstance();
$path = trim(implode('.', [$path, $name]), '.');
// The class itself
self::getClassCompletion($completionList, $object, $factory, $name, $path);
// ServiceLocator Components
self::getComponentCompletion($completionList, $object, $recursionDepth, $path);
// Class properties
self::getPropertyCompletion($completionList, $object, $factory, $recursionDepth, $path);
// Class methods
self::getMethodCompletion($completionList, $object, $factory, $path);
// Behavior properties
self::getBehaviorCompletion($completionList, $object, $factory, $recursionDepth, $path);
}
// Protected Static Methods
// =========================================================================
/**
* @param array $completionList
* @param $object
* @param DocBlockFactory $factory
* @param string $name
* @param $path
*/
protected static function getClassCompletion(array &$completionList, $object, DocBlockFactory $factory, string $name, $path)
{
try {
$reflectionClass = new ReflectionClass($object);
} catch (ReflectionException $e) {
return;
}
// Information on the class itself
$className = $reflectionClass->getName();
$docs = $reflectionClass->getDocComment();
if ($docs) {
$docblock = $factory->create($docs);
if ($docblock) {
$summary = $docblock->getSummary();
if (!empty($summary)) {
$docs = $summary;
}
$description = $docblock->getDescription()->render();
if (!empty($description)) {
$docs = $description;
}
}
}
ArrayHelper::setValue($completionList, $path, [
self::COMPLETION_KEY => [
'detail' => "$className",
'documentation' => $docs,
'kind' => self::CompletionItemKind['Class'],
'label' => $name,
'insertText' => $name,
]
]);
}
/**
* @param array $completionList
* @param $object
* @param $recursionDepth
* @param $path
*/
protected static function getComponentCompletion(array &$completionList, $object, $recursionDepth, $path)
{
if ($object instanceof ServiceLocator) {
foreach ($object->getComponents() as $key => $value) {
$componentObject = null;
try {
$componentObject = $object->get($key);
} catch (InvalidConfigException $e) {
// That's okay
}
if ($componentObject) {
self::parseObject($completionList, $key, $componentObject, $recursionDepth, $path);
}
}
}
}
/**
* @param array $completionList
* @param $object
* @param DocBlockFactory $factory
* @param string $path
*/
protected static function getPropertyCompletion(array &$completionList, $object, DocBlockFactory $factory, $recursionDepth, string $path)
{
try {
$reflectionClass = new ReflectionClass($object);
} catch (ReflectionException $e) {
return;
}
$reflectionProperties = $reflectionClass->getProperties();
$customField = false;
if ($object instanceof Behavior) {
$customField = true;
}
$sortPrefix = $customField ? '~' : '~~';
foreach ($reflectionProperties as $reflectionProperty) {
$propertyName = $reflectionProperty->getName();
// Exclude some properties
$propertyAllowed = true;
foreach (self::EXCLUDED_PROPERTY_REGEXES as $excludePattern) {
$pattern = '`' . $excludePattern . '`i';
if (preg_match($pattern, $propertyName) === 1) {
$propertyAllowed = false;
}
}
if (in_array($propertyName, self::EXCLUDED_PROPERTY_NAMES, true)) {
$propertyAllowed = false;
}
if ($customField && in_array($propertyName, self::EXCLUDED_BEHAVIOR_NAMES, true)) {
$propertyAllowed = false;
}
// Process the property
if ($propertyAllowed && $reflectionProperty->isPublic()) {
$detail = "Property";
$docblock = null;
$docs = $reflectionProperty->getDocComment();
if ($docs) {
$docblock = $factory->create($docs);
$docs = '';
if ($docblock) {
$summary = $docblock->getSummary();
if (!empty($summary)) {
$docs = $summary;
}
$description = $docblock->getDescription()->render();
if (!empty($description)) {
$docs = $description;
}
}
}
// Figure out the type
if ($docblock) {
$tag = $docblock->getTagsByName('var');
if ($tag && isset($tag[0])) {
$detail = strval($tag[0]);
}
}
if ($detail === "Property") {
if (preg_match('/@var\s+([^\s]+)/', $docs, $matches)) {
list(, $type) = $matches;
$detail = $type;
} else {
$detail = "Property";
}
}
if ($detail === "Property") {
if ((PHP_MAJOR_VERSION >= 7 && PHP_MINOR_VERSION >= 4) || (PHP_MAJOR_VERSION >= 8)) {
if ($reflectionProperty->hasType()) {
$reflectionType = $reflectionProperty->getType();
if ($reflectionType instanceof ReflectionNamedType) {
$type = $reflectionType->getName();
$detail = $type;
}
}
if (PHP_MAJOR_VERSION >= 8) {
if ($reflectionProperty->hasDefaultValue()) {
$value = $reflectionProperty->getDefaultValue();
if (is_array($value)) {
$value = json_encode($value);
}
if (!empty($value)) {
$detail = "$value";
}
}
}
}
}
$thisPath = trim(implode('.', [$path, $propertyName]), '.');
$label = $propertyName;
ArrayHelper::setValue($completionList, $thisPath, [
self::COMPLETION_KEY => [
'detail' => $detail,
'documentation' => $docs,
'kind' => $customField ? self::CompletionItemKind['Field'] : self::CompletionItemKind['Property'],
'label' => $label,
'insertText' => $label,
'sortText' => $sortPrefix . $label,
]
]);
// Recurse through if this is an object
if (isset($object->$propertyName) && is_object($object->$propertyName)) {
if (!$customField && !in_array($propertyName, self::EXCLUDED_PROPERTY_NAMES, true)) {
self::parseObject($completionList, $propertyName, $object->$propertyName, $recursionDepth, $path);
}
}
}
}
}
/**
* @param array $completionList
* @param $object
* @param DocBlockFactory $factory
* @param string $path
*/
protected static function getMethodCompletion(array &$completionList, $object, DocBlockFactory $factory, string $path)
{
try {
$reflectionClass = new ReflectionClass($object);
} catch (ReflectionException $e) {
return;
}
$reflectionMethods = $reflectionClass->getMethods();
foreach ($reflectionMethods as $reflectionMethod) {
$methodName = $reflectionMethod->getName();
// Exclude some properties
$methodAllowed = true;
foreach (self::EXCLUDED_METHOD_REGEXES as $excludePattern) {
$pattern = '`' . $excludePattern . '`i';
if (preg_match($pattern, $methodName) === 1) {
$methodAllowed = false;
}
}
// Process the method
if ($methodAllowed && $reflectionMethod->isPublic()) {
$docblock = null;
$docs = $reflectionMethod->getDocComment();
if ($docs) {
$docblock = $factory->create($docs);
if ($docblock) {
$summary = $docblock->getSummary();
if (!empty($summary)) {
$docs = $summary;
}
$description = $docblock->getDescription()->render();
if (!empty($description)) {
$docs = $description;
}
}
}
$detail = $methodName . '(';
$params = $reflectionMethod->getParameters();
$paramList = [];
foreach ($params as $param) {
if ($param->hasType()) {
$reflectionType = $param->getType();
if ($reflectionType instanceof ReflectionUnionType) {
$unionTypes = $reflectionType->getTypes();
$typeName = '';
foreach ($unionTypes as $unionType) {
$typeName .= '|' . $unionType->getName();
}
$typeName = trim($typeName, '|');
$paramList[] = $typeName . ': ' . '$' . $param->getName();
} else {
$paramList[] = $param->getType()->getName() . ': ' . '$' . $param->getName();
}
} else {
$paramList[] = '$' . $param->getName();
}
}
$detail .= implode(', ', $paramList) . ')';
$thisPath = trim(implode('.', [$path, $methodName]), '.');
$label = $methodName . '()';
$docsPreamble = '';
// Figure out the type
if ($docblock) {
$tags = $docblock->getTagsByName('param');
if ($tags) {
$docsPreamble = "Parameters:\n\n";
foreach ($tags as $tag) {
$docsPreamble .= $tag . "\n";
}
$docsPreamble .= "\n";
}
}
ArrayHelper::setValue($completionList, $thisPath, [
self::COMPLETION_KEY => [
'detail' => $detail,
'documentation' => $docsPreamble . $docs,
'kind' => self::CompletionItemKind['Method'],
'label' => $label,
'insertText' => $label,
'sortText' => '~~~' . $label,
]
]);
}
}
}
/**
* @param array $completionList
* @param $object
* @param DocBlockFactory $factory
* @param string $path
*/
protected static function getBehaviorCompletion(array &$completionList, $object, DocBlockFactory $factory, $recursionDepth, string $path)
{
if ($object instanceof Element) {
$behaviorClass = $object->getBehavior('customFields');
if ($behaviorClass) {
self::getPropertyCompletion($completionList, $behaviorClass, $factory, $recursionDepth, $path);
}
}
}
// Private Static Methods
// =========================================================================
/**
* Add in the element types that could be injected as route variables
*
* @return array
*/
private static function elementRouteVariables(): array
{
$routeVariables = [];
$elementTypes = Craft::$app->elements->getAllElementTypes();
foreach ($elementTypes as $elementType) {
/* @var Element $elementType */
$key = $elementType::refHandle();
if (!empty($key) && !in_array($key, static::ELEMENT_ROUTE_EXCLUDES)) {
$routeVariables[$key] = new $elementType();
}
}
return $routeVariables;
}
/**
* Override certain values that we always want hard-coded
*
* @return array
*/
private static function overrideValues(): array
{
return [
// Set the nonce to a blank string, as it changes on every request
'nonce' => '',
];
}
}