|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\PhpDoc; |
| 4 | + |
| 5 | +use Nette\Utils\Strings; |
| 6 | +use PhpParser\Node; |
| 7 | +use PhpParser\Node\Expr; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Node\Constant\ClassConstantFetch; |
| 10 | +use PHPStan\PhpDocParser\Ast\AbstractNodeVisitor; |
| 11 | +use PHPStan\PhpDocParser\Ast\ConstExpr\ConstFetchNode; |
| 12 | +use PHPStan\Reflection\ClassReflection; |
| 13 | +use function preg_quote; |
| 14 | +use function str_replace; |
| 15 | + |
| 16 | +class PhpDocPrivateClassConstFetchFinderVisitor extends AbstractNodeVisitor |
| 17 | +{ |
| 18 | + |
| 19 | + /** @var list<ClassConstantFetch> */ |
| 20 | + public array $classConstantFetches = []; |
| 21 | + |
| 22 | + public function __construct(private ClassReflection $classReflection, private Scope $scope) |
| 23 | + { |
| 24 | + } |
| 25 | + |
| 26 | + public function enterNode(\PHPStan\PhpDocParser\Ast\Node $node) |
| 27 | + { |
| 28 | + if (!$node instanceof ConstFetchNode) { |
| 29 | + return null; |
| 30 | + } |
| 31 | + |
| 32 | + if ($node->className !== 'self') { |
| 33 | + return null; |
| 34 | + } |
| 35 | + |
| 36 | + $constantName = $node->name; |
| 37 | + if (Strings::contains($constantName, '*')) { |
| 38 | + // convert * into .*? and escape everything else so the constants can be matched against the pattern |
| 39 | + $pattern = '{^' . str_replace('\\*', '.*?', preg_quote($constantName)) . '$}D'; |
| 40 | + foreach ($this->classReflection->getNativeReflection()->getReflectionConstants() as $reflectionConstant) { |
| 41 | + $classConstantName = $reflectionConstant->getName(); |
| 42 | + if (Strings::match($classConstantName, $pattern) === null) { |
| 43 | + continue; |
| 44 | + } |
| 45 | + |
| 46 | + $this->addClassConstantFetch($classConstantName); |
| 47 | + } |
| 48 | + } else { |
| 49 | + $this->addClassConstantFetch($constantName); |
| 50 | + } |
| 51 | + |
| 52 | + return null; |
| 53 | + } |
| 54 | + |
| 55 | + private function addClassConstantFetch(string $constantName): void |
| 56 | + { |
| 57 | + $this->classConstantFetches[] = new ClassConstantFetch( |
| 58 | + new Expr\ClassConstFetch( |
| 59 | + new Node\Name\FullyQualified($this->classReflection->getName()), |
| 60 | + $constantName, |
| 61 | + ), |
| 62 | + $this->scope, |
| 63 | + ); |
| 64 | + } |
| 65 | + |
| 66 | +} |
0 commit comments