-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathVisitor.php
883 lines (700 loc) · 26.3 KB
/
Visitor.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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
<?php
declare(strict_types=1);
namespace PhpStubs\WordPress\Core;
use phpDocumentor\Reflection\DocBlock;
use phpDocumentor\Reflection\DocBlock\Description;
use phpDocumentor\Reflection\DocBlock\Tags\Param;
use phpDocumentor\Reflection\DocBlock\Tags\Return_;
use phpDocumentor\Reflection\DocBlock\Tags\Var_;
use phpDocumentor\Reflection\Type;
use phpDocumentor\Reflection\Types\Never_;
use phpDocumentor\Reflection\Types\Void_;
use PhpParser\Comment\Doc;
use PhpParser\ConstExprEvaluator;
use PhpParser\Node;
use PhpParser\NodeFinder;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Expr\Exit_;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassLike;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Expression;
use PhpParser\Node\Stmt\Function_;
use PhpParser\Node\Stmt\Namespace_;
use PhpParser\Node\Stmt\Property;
use PhpParser\Node\Stmt\Return_ as Stmt_Return;
use StubsGenerator\NodeVisitor;
// phpcs:disable NeutronStandard.Functions.LongFunction.LongFunction,NeutronStandard.Functions.TypeHint.NoReturnType
class Visitor extends NodeVisitor
{
private \phpDocumentor\Reflection\DocBlockFactoryInterface $docBlockFactory;
/** @var array<string,array<int|string,string>> */
private array $functionMap;
/** @var array<string, list<\PhpStubs\WordPress\Core\WordPressTag>> */
private array $additionalTags = [];
/** @var array<string, list<string>> */
private array $additionalTagStrings = [];
private \PhpParser\NodeFinder $nodeFinder;
public function __construct()
{
$this->docBlockFactory = \phpDocumentor\Reflection\DocBlockFactory::createInstance();
$this->nodeFinder = new NodeFinder();
$this->functionMap = require sprintf('%s/functionMap.php', dirname(__DIR__));
}
/**
* @return int|null
*/
public function enterNode(Node $node)
{
$voidOrNever = $this->voidOrNever($node);
parent::enterNode($node);
if (! ($node instanceof Function_) && ! ($node instanceof ClassMethod) && ! ($node instanceof Property) && ! ($node instanceof Class_)) {
return null;
}
$docComment = $node->getDocComment();
if (! ($docComment instanceof Doc)) {
return null;
}
$symbolName = self::getNodeName($node);
if ($node instanceof ClassMethod) {
$parent = $this->stack[count($this->stack) - 2];
\assert($parent instanceof \PhpParser\Node\Stmt\ClassLike);
if ($parent->name !== null) {
$symbolName = sprintf(
'%1$s::%2$s',
$parent->name->name,
$node->name->name
);
}
}
$node->setAttribute('fullSymbolName', $symbolName);
$additions = $this->generateAdditionalTagsFromDoc($docComment);
if (count($additions) > 0) {
$this->additionalTags[$symbolName] = $additions;
}
$additions = $this->getAdditionalTagsFromMap($symbolName);
if (count($additions) > 0) {
$this->additionalTagStrings[$symbolName] = $additions;
}
if ($voidOrNever !== '') {
$addition = sprintf(
'@phpstan-return %s',
$voidOrNever === 'never'
? (new Never_())->__toString()
: (new Void_())->__toString()
);
if (
! isset($this->additionalTagStrings[$symbolName])
|| ! in_array($addition, $this->additionalTagStrings[$symbolName], true)
) {
$this->additionalTagStrings[$symbolName][] = $addition;
}
}
return null;
}
private static function getNodeName(Node $node): string
{
if ((($node instanceof Function_) || ($node instanceof ClassMethod) || ($node instanceof Class_)) && $node->name instanceof Identifier) {
return $node->name->name;
}
if ($node instanceof Property) {
return sprintf(
'property_%s',
uniqid()
);
}
return '';
}
/**
* @return array<\PhpParser\Node>
*/
public function getStubStmts(): array
{
$stmts = parent::getStubStmts();
foreach ($stmts as $stmt) {
$this->postProcessNode($stmt);
}
return $stmts;
}
private function postProcessNode(Node $node): void
{
if ($node instanceof ClassLike || $node instanceof Namespace_) {
foreach ($node->stmts as $stmt) {
$this->postProcessNode($stmt);
}
}
if (! ($node instanceof Function_) && ! ($node instanceof ClassMethod) && ! ($node instanceof Property) && ! ($node instanceof Class_)) {
return;
}
/** @var ?string $fullSymbolName */
$fullSymbolName = $node->getAttribute('fullSymbolName');
if ($fullSymbolName === null) {
return;
}
$docComment = $node->getDocComment();
if (! ($docComment instanceof Doc)) {
return;
}
$newDocComment = $this->addTags($fullSymbolName, $docComment);
if ($newDocComment instanceof Doc) {
$node->setDocComment($newDocComment);
}
if (! isset($this->additionalTagStrings[$fullSymbolName])) {
return;
}
$docComment = $node->getDocComment();
if (! ($docComment instanceof Doc)) {
return;
}
$newDocComment = $this->addStringTags($fullSymbolName, $docComment);
if (! ($newDocComment instanceof Doc)) {
return;
}
$node->setDocComment($newDocComment);
}
/**
* @return list<\PhpStubs\WordPress\Core\WordPressTag>
*/
private function generateAdditionalTagsFromDoc(Doc $docComment): array
{
$docCommentText = $docComment->getText();
try {
$docblock = $this->docBlockFactory->create($docCommentText);
} catch (\RuntimeException | \InvalidArgumentException $e) {
return [];
}
/** @var list<\phpDocumentor\Reflection\DocBlock\Tags\Param> $paramTags*/
$paramTags = $docblock->getTagsByName('param');
/** @var list<\phpDocumentor\Reflection\DocBlock\Tags\Return_> $returnTags */
$returnTags = $docblock->getTagsByName('return');
/** @var list<\phpDocumentor\Reflection\DocBlock\Tags\Var_> $varTags */
$varTags = $docblock->getTagsByName('var');
/** @var list<\PhpStubs\WordPress\Core\WordPressTag> $additions */
$additions = [];
foreach ($paramTags as $paramTag) {
$addition = self::getAdditionFromParam($paramTag);
if (! ($addition instanceof WordPressTag)) {
continue;
}
$additions[] = $addition;
}
foreach ($returnTags as $returnTag) {
$addition = self::getAdditionFromReturn($returnTag);
if (! ($addition instanceof WordPressTag)) {
continue;
}
$additions[] = $addition;
}
foreach ($varTags as $varTag) {
$addition = self::getAdditionFromVar($varTag);
if (! ($addition instanceof WordPressTag)) {
continue;
}
$additions[] = $addition;
}
return $additions;
}
private function addTags(string $name, Doc $docComment): ?Doc
{
$additions = $this->additionalTags[$name] ?? [];
$docCommentText = $docComment->getText();
try {
$docblock = $this->docBlockFactory->create($docCommentText);
} catch (\RuntimeException | \InvalidArgumentException $e) {
return null;
}
$additions = $this->discoverInheritedArgs($docblock, $additions);
/** @var list<string> $additionStrings */
$additionStrings = array_map(
static function (WordPressTag $tag): string {
$lines = $tag->format();
if (count($lines) === 0) {
return '';
}
return sprintf(' * %s', implode("\n * ", $lines));
},
$additions
);
$additionStrings = array_filter($additionStrings);
if (count($additionStrings) === 0) {
return null;
}
$newDocComment = sprintf(
"%s\n%s\n */",
substr($docCommentText, 0, -4),
implode("\n", $additionStrings)
);
return new Doc($newDocComment, $docComment->getStartLine(), $docComment->getStartFilePos());
}
/**
* @param list<\PhpStubs\WordPress\Core\WordPressTag> $additions
* @return list<\PhpStubs\WordPress\Core\WordPressTag>
*/
private function discoverInheritedArgs(DocBlock $docblock, array $additions): array
{
/** @var list<\phpDocumentor\Reflection\DocBlock\Tags\Param> $params */
$params = $docblock->getTagsByName('param');
$phpStanParams = array_filter(
$additions,
static function (WordPressTag $addition): bool {
return $addition->tag === '@phpstan-param';
}
);
foreach ($params as $param) {
$inherited = $this->getInheritedTagsForParam($param);
if (count($inherited) === 0) {
continue;
}
foreach ($phpStanParams as $addition) {
foreach ($inherited as $inherit) {
if ($addition->name !== $inherit->name) {
continue;
}
$addition->children = array_merge($addition->children, $inherit->children);
continue 3;
}
}
$additions = array_merge($additions, $inherited);
}
return $additions;
}
/**
* @return list<\PhpStubs\WordPress\Core\WordPressTag>
*/
private function getInheritedTagsForParam(Param $param): array
{
$type = $param->getType();
if (! $type instanceof Type) {
return [];
}
$typeName = self::getTypeNameFromType($type);
if ($typeName === null) {
return [];
}
$paramDescription = $param->getDescription();
if (! $paramDescription instanceof Description) {
return [];
}
$description = explode("\n\n", $paramDescription->__toString())[0];
if (strpos($description, '()') === false) {
return [];
}
$description = str_replace("\n", ' ', $description);
$description = str_replace('@see \\', '@see ', $description);
$additions = [];
foreach ($this->additionalTags as $symbolName => $tags) {
$search = sprintf(
'see %s()',
$symbolName
);
if (stripos($description, $search) === false) {
continue;
}
$match = self::getMatchingInheritedTag($param, $tags, $symbolName);
if (! ($match instanceof WordPressTag)) {
continue;
}
$additions[] = $match;
}
return $additions;
}
/**
* @param list<\PhpStubs\WordPress\Core\WordPressTag> $tags
*/
private static function getMatchingInheritedTag(Param $param, array $tags, string $symbolName): ?WordPressTag
{
$paramName = $param->getVariableName();
$matchNames = [
$paramName,
'args',
'options',
'query',
];
$matchingTags = array_filter(
$tags,
static function (WordPressTag $tag) use ($matchNames): bool {
return in_array($tag->name, $matchNames, true);
}
);
foreach ($matchingTags as $tag) {
$addTag = clone $tag;
$addTag->name = $paramName;
$addTag->description = sprintf(
'See %s()',
$symbolName
);
return $addTag;
}
return null;
}
/**
* @return list<string>
*/
private function getAdditionalTagsFromMap(string $symbolName): array
{
if (! array_key_exists($symbolName, $this->functionMap)) {
return [];
}
$parameters = $this->functionMap[$symbolName];
$returnType = array_shift($parameters);
/** @var array<string, string|array<int, string>> $parameters */
$otherTags = array_filter(
$parameters,
static function ($paramName): bool {
return strpos($paramName, '@') === 0;
},
ARRAY_FILTER_USE_KEY
);
$parameters = array_diff_key($parameters, $otherTags);
/** @var array<string, string> $parameters */
$additions = [];
foreach ($otherTags as $tagName => $tagValues) {
foreach ((array)$tagValues as $tagValue) {
$additions[] = sprintf(
($tagValue === '') ? '%s' : '%s %s',
$tagName,
$tagValue
);
}
}
foreach ($parameters as $paramName => $paramType) {
$additions[] = sprintf(
'@phpstan-param %s $%s',
$paramType,
$paramName
);
}
if ($returnType !== null) {
$additions[] = sprintf(
'@phpstan-return %s',
$returnType
);
}
return $additions;
}
private function addStringTags(string $name, Doc $docComment): ?Doc
{
if (! isset($this->additionalTagStrings[$name])) {
return null;
}
$additions = $this->additionalTagStrings[$name];
$docCommentText = $docComment->getText();
$newDocComment = sprintf(
"%s\n * %s\n */",
substr($docCommentText, 0, -4),
implode("\n * ", $additions)
);
return new Doc($newDocComment, $docComment->getStartLine(), $docComment->getStartFilePos());
}
private function getAdditionFromParam(Param $tag): ?WordPressTag
{
$tagDescription = $tag->getDescription();
$tagVariableName = $tag->getVariableName();
$tagVariableType = $tag->getType();
// Skip if information we need is missing.
if (! $tagDescription instanceof Description || $tagVariableName === null || $tagVariableName === '' || ! $tagVariableType instanceof Type) {
return null;
}
$tagDescriptionType = self::getTypeNameFromDescription($tagDescription, $tagVariableType);
if ($tagDescriptionType !== null) {
$tag = new WordPressTag();
$tag->tag = '@phpstan-param';
$tag->type = $tagDescriptionType;
$tag->name = $tagVariableName;
return $tag;
}
$elements = self::getElementsFromDescription($tagDescription, true);
if (count($elements) === 0) {
return null;
}
$tagVariableType = self::getTypeNameFromType($tagVariableType);
if ($tagVariableType === null) {
return null;
}
// It's common for an args parameter to accept a query var string or array with `string|array`.
// Remove the accepted string type for these so we get the strongest typing we can manage.
$tagVariableType = str_replace(['|string', 'string|'], '', $tagVariableType);
$tag = new WordPressTag();
$tag->tag = '@phpstan-param';
$tag->type = $tagVariableType;
$tag->name = $tagVariableName;
$tag->children = $elements;
return $tag;
}
private function getAdditionFromReturn(Return_ $tag): ?WordPressTag
{
$tagDescription = $tag->getDescription();
$tagVariableType = $tag->getType();
// Skip if information we need is missing.
if (! $tagDescription instanceof Description || ! $tagVariableType instanceof Type) {
return null;
}
$tagDescriptionType = self::getTypeNameFromDescription($tagDescription, $tagVariableType);
if ($tagDescriptionType !== null) {
$tag = new WordPressTag();
$tag->tag = '@phpstan-return';
$tag->type = $tagDescriptionType;
return $tag;
}
$elements = self::getElementsFromDescription($tagDescription, false);
if (count($elements) === 0) {
return null;
}
$tagVariableType = self::getTypeNameFromType($tagVariableType);
if ($tagVariableType === null) {
return null;
}
$tag = new WordPressTag();
$tag->tag = '@phpstan-return';
$tag->type = $tagVariableType;
$tag->children = $elements;
return $tag;
}
private static function getAdditionFromVar(Var_ $tag): ?WordPressTag
{
$tagDescription = $tag->getDescription();
$tagVariableType = $tag->getType();
// Skip if information we need is missing.
if (! $tagDescription instanceof Description || ! $tagVariableType instanceof Type) {
return null;
}
$elements = self::getElementsFromDescription($tagDescription, false);
if (count($elements) === 0) {
return null;
}
$tagVariableType = self::getTypeNameFromType($tagVariableType);
if ($tagVariableType === null) {
return null;
}
$tag = new WordPressTag();
$tag->tag = '@phpstan-var';
$tag->type = $tagVariableType;
$tag->children = $elements;
return $tag;
}
private static function getTypeNameFromDescription(Description $tagVariableDescription, Type $tagVariableType): ?string
{
if (! ($tagVariableType instanceof \phpDocumentor\Reflection\Types\String_)) {
return null;
}
return self::getTypeNameFromDescriptionString($tagVariableDescription->__toString());
}
private static function getTypeNameFromDescriptionString(?string $tagDescription = null): ?string
{
if ($tagDescription === null) {
return null;
}
$fullDescription = str_replace("\n", ' ', $tagDescription);
/**
* This matches phrases that contain a list of two or more single-quoted strings, with the last
* item separated by 'or' or 'and'. The Oxford comma is optional. For example:
*
* - Either 'am', 'pm', 'AM', or 'PM'
* - Accepts 'comment' or 'term'
* - Either 'plugin' or 'theme'
* - Accepts 'big', or 'little'.
* - One of 'default', 'theme', or 'custom'
* - Either 'network-active', 'active' or 'inactive'
* - : 'top' or 'bottom'
*/
$matched = preg_match("#(?>returns|either|one of|accepts|values are|:) ('.+'),? (?>or|and) '([^']+)'#i", $fullDescription, $matches);
if ($matched !== 1) {
return null;
}
$items = $matches[1];
$final = $matches[2];
// Pluck out phrases between single quotes, so messy sentences are handled:
preg_match_all("#'([^']+)'#", $items, $matches);
$accepted = $matches[1];
// Append the final item:
$accepted[] = $final;
return sprintf("'%s'", implode("'|'", $accepted));
}
private static function getTypeNameFromType(Type $tagVariableType): ?string
{
return self::getTypeNameFromString($tagVariableType->__toString());
}
private static function getTypeNameFromString(string $tagVariable): ?string
{
// PHPStan doesn't support typed array shapes (`int[]{...}`) so replace
// typed arrays such as `int[]` with `array`.
$tagVariableType = preg_replace('#[a-zA-Z0-9_]+\[\]#', 'array', $tagVariable);
if ($tagVariableType === null) {
return null;
}
$tagVariableType = str_replace(
[
'stdClass',
'\\object',
],
'object',
$tagVariableType
);
$supportedTypes = [
'object',
'array',
];
foreach ($supportedTypes as $supportedType) {
if (strpos($tagVariableType, "{$supportedType}|") === false) {
continue;
}
// Move the type that uses the hash notation to the end of union types so the shape works.
$tagVariableType = sprintf('%s|%s', str_replace("{$supportedType}|", '', $tagVariableType), $supportedType);
}
return $tagVariableType;
}
/**
* @return list<\PhpStubs\WordPress\Core\WordPressArg>
*/
private static function getElementsFromDescription(Description $tagDescription, bool $optional): array
{
$text = $tagDescription->__toString();
// Skip if the description doesn't contain at least one correctly
// formatted `@type`, which indicates an array hash.
if (strpos($text, ' @type ') === false) {
return [];
}
return self::getTypesAtLevel($text, $optional, 1);
}
/**
* @return list<\PhpStubs\WordPress\Core\WordPressArg>
*/
private static function getTypesAtLevel(string $text, bool $optional, int $level): array
{
// Populate `$types` with the value of each top level `@type`.
$spaces = str_repeat(' ', ($level * 4));
$types = preg_split("/\R+{$spaces}@type /", $text);
if ($types === false) {
return [];
}
unset($types[0]);
$elements = [];
foreach ($types as $typeTag) {
$parts = preg_split('#\s+#', trim($typeTag), 3);
if ($parts === false || count($parts) < 2) {
return [];
}
$type = $parts[0];
$name = $parts[1];
$optionalArg = $optional;
$nameTrimmed = ltrim($name, '$');
if (is_numeric($nameTrimmed)) {
$optionalArg = false;
} elseif ($optional && ($level > 1)) {
$optionalArg = self::isOptional($parts[2]);
}
if (strpos($name, '...$') !== false) {
$name = null;
} elseif (strpos($name, '$') !== 0) {
return [];
} else {
$name = $nameTrimmed;
}
$arg = new WordPressArg();
$arg->type = $type;
$arg->optional = $optionalArg;
$arg->name = $name;
$nextLevel = $level + 1;
$subTypes = self::getTypesAtLevel($typeTag, $optional, $nextLevel);
if (count($subTypes) > 0) {
$type = self::getTypeNameFromString($type);
if ($type !== null) {
$arg->type = $type;
}
$arg->children = $subTypes;
}
$elements[] = $arg;
}
return $elements;
}
private static function isOptional(string $description): bool
{
return (stripos($description, 'Optional') !== false)
|| (stripos($description, 'Default ') !== false)
|| (stripos($description, 'Default: ') !== false)
|| (stripos($description, 'Defaults to ') !== false);
}
private function voidOrNever(Node $node): string
{
if (! ($node instanceof Function_) && ! ($node instanceof ClassMethod)) {
return '';
}
if (! isset($node->stmts) || count($node->stmts) === 0) {
// Interfaces and abstract methods.
return '';
}
$returnStmts = $this->nodeFinder->findInstanceOf($node, Stmt_Return::class);
// If there is a return statement, it's not return type never.
if (count($returnStmts) !== 0) {
// If there is at least one return statement that is not void,
// it's not return type void.
if (
$this->nodeFinder->findFirst(
$returnStmts,
static function (Node $node): bool {
return property_exists($node, 'expr') && $node->expr !== null;
}
) instanceof Node
) {
return '';
}
// If there is no return statement that is not void,
// it's return type void.
return 'void';
}
// Check for never return type.
foreach ($node->stmts as $stmt) {
if (! ($stmt instanceof Expression)) {
continue;
}
// If a first level statement is exit/die, it's return type never.
if ($stmt->expr instanceof Exit_) {
if (! $stmt->expr->expr instanceof String_) {
return 'never';
}
if (strpos($stmt->expr->expr->value, 'must be overridden') !== false) {
return '';
}
return 'never';
}
if (! ($stmt->expr instanceof FuncCall) || ! ($stmt->expr->name instanceof Name)) {
continue;
}
$name = $stmt->expr->name;
// If a first level statement is a call to wp_send_json(_success/error),
// it's return type never.
if (strpos($name->toString(), 'wp_send_json') === 0) {
return 'never';
}
// Skip all functions but wp_die().
if (strpos($name->toString(), 'wp_die') !== 0) {
continue;
}
$args = $stmt->expr->getArgs();
// If wp_die is called without 3rd parameter, it's return type never.
if (count($args) < 3) {
return 'never';
}
// If wp_die is called with 3rd parameter, we need additional checks.
try {
$arg = (new ConstExprEvaluator())->evaluateSilently($args[2]->value);
} catch (\PhpParser\ConstExprEvaluationException $e) {
// If we don't know the value of the 3rd parameter, we can't be sure.
continue;
}
if (is_int($arg)) {
return 'never';
}
if (! is_array($arg)) {
continue;
}
if (! array_key_exists('exit', $arg) || (bool)$arg['exit']) {
return 'never';
}
}
return '';
}
}