|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace WP_CLI\Tests\PHPStan; |
| 6 | + |
| 7 | +use PhpParser\Comment\Doc; |
| 8 | +use PhpParser\Node\Expr\StaticCall; |
| 9 | +use PHPStan\Analyser\Scope; |
| 10 | +use PHPStan\Reflection\MethodReflection; |
| 11 | +use PHPStan\Type\DynamicStaticMethodReturnTypeExtension; |
| 12 | +use PHPStan\Type\FileTypeMapper; |
| 13 | +use PHPStan\Type\NullType; |
| 14 | +use PHPStan\Type\Type; |
| 15 | + |
| 16 | +use function count; |
| 17 | + |
| 18 | +final class WPCliDoHookDynamicReturnTypeExtension implements DynamicStaticMethodReturnTypeExtension { |
| 19 | + |
| 20 | + /** |
| 21 | + * @var FileTypeMapper |
| 22 | + */ |
| 23 | + private $fileTypeMapper; |
| 24 | + |
| 25 | + public function __construct( FileTypeMapper $fileTypeMapper ) { |
| 26 | + $this->fileTypeMapper = $fileTypeMapper; |
| 27 | + } |
| 28 | + |
| 29 | + public function getClass(): string { |
| 30 | + return 'WP_CLI'; |
| 31 | + } |
| 32 | + |
| 33 | + public function isStaticMethodSupported( MethodReflection $methodReflection ): bool { |
| 34 | + return $methodReflection->getName() === 'do_hook'; |
| 35 | + } |
| 36 | + |
| 37 | + public function getTypeFromStaticMethodCall( |
| 38 | + MethodReflection $methodReflection, |
| 39 | + StaticCall $methodCall, |
| 40 | + Scope $scope |
| 41 | + ): Type { |
| 42 | + $args = $methodCall->getArgs(); |
| 43 | + |
| 44 | + if ( count( $args ) < 2 ) { |
| 45 | + return new NullType(); |
| 46 | + } |
| 47 | + |
| 48 | + $docComment = $methodCall->getAttribute( 'latestDocComment' ); |
| 49 | + if ( $docComment instanceof Doc ) { |
| 50 | + $classReflection = $scope->getClassReflection(); |
| 51 | + $traitReflection = $scope->getTraitReflection(); |
| 52 | + |
| 53 | + $resolvedPhpDoc = $this->fileTypeMapper->getResolvedPhpDoc( |
| 54 | + $scope->getFile(), |
| 55 | + ( $scope->isInClass() && null !== $classReflection ) ? $classReflection->getName() : null, |
| 56 | + ( $scope->isInTrait() && null !== $traitReflection ) ? $traitReflection->getName() : null, |
| 57 | + $scope->getFunctionName(), |
| 58 | + $docComment->getText() |
| 59 | + ); |
| 60 | + |
| 61 | + $params = $resolvedPhpDoc->getParamTags(); |
| 62 | + foreach ( $params as $paramTag ) { |
| 63 | + return $paramTag->getType(); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + return $scope->getType( $args[1]->value ); |
| 68 | + } |
| 69 | +} |
0 commit comments