|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Symfony; |
| 4 | + |
| 5 | +use PhpParser\Node\Expr\MethodCall; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Reflection\MethodReflection; |
| 8 | +use PHPStan\Symfony\ConsoleApplicationResolver; |
| 9 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 10 | +use PHPStan\Type\ObjectType; |
| 11 | +use PHPStan\Type\Type; |
| 12 | +use PHPStan\Type\TypeCombinator; |
| 13 | +use PHPStan\Type\TypeUtils; |
| 14 | +use Throwable; |
| 15 | +use function count; |
| 16 | +use function get_class; |
| 17 | + |
| 18 | +final class CommandGetHelperDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension |
| 19 | +{ |
| 20 | + |
| 21 | + /** @var \PHPStan\Symfony\ConsoleApplicationResolver */ |
| 22 | + private $consoleApplicationResolver; |
| 23 | + |
| 24 | + public function __construct(ConsoleApplicationResolver $consoleApplicationResolver) |
| 25 | + { |
| 26 | + $this->consoleApplicationResolver = $consoleApplicationResolver; |
| 27 | + } |
| 28 | + |
| 29 | + public function getClass(): string |
| 30 | + { |
| 31 | + return 'Symfony\Component\Console\Command\Command'; |
| 32 | + } |
| 33 | + |
| 34 | + public function isMethodSupported(MethodReflection $methodReflection): bool |
| 35 | + { |
| 36 | + return $methodReflection->getName() === 'getHelper'; |
| 37 | + } |
| 38 | + |
| 39 | + public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type |
| 40 | + { |
| 41 | + $defaultReturnType = new ObjectType('Symfony\Component\Console\Helper\HelperInterface'); |
| 42 | + |
| 43 | + if (!isset($methodCall->getArgs()[0])) { |
| 44 | + return $defaultReturnType; |
| 45 | + } |
| 46 | + |
| 47 | + $classReflection = $scope->getClassReflection(); |
| 48 | + if ($classReflection === null) { |
| 49 | + return $defaultReturnType; |
| 50 | + } |
| 51 | + |
| 52 | + $argStrings = TypeUtils::getConstantStrings($scope->getType($methodCall->getArgs()[0]->value)); |
| 53 | + if (count($argStrings) !== 1) { |
| 54 | + return $defaultReturnType; |
| 55 | + } |
| 56 | + $argName = $argStrings[0]->getValue(); |
| 57 | + |
| 58 | + $returnTypes = []; |
| 59 | + foreach ($this->consoleApplicationResolver->findCommands($classReflection) as $command) { |
| 60 | + try { |
| 61 | + $command->mergeApplicationDefinition(); |
| 62 | + $returnTypes[] = new ObjectType(get_class($command->getHelper($argName))); |
| 63 | + } catch (Throwable $e) { |
| 64 | + // no-op |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + return count($returnTypes) > 0 ? TypeCombinator::union(...$returnTypes) : $defaultReturnType; |
| 69 | + } |
| 70 | + |
| 71 | +} |
0 commit comments