|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Symfony; |
| 4 | + |
| 5 | +use PhpParser\Node\Expr; |
| 6 | +use PhpParser\Node\Expr\MethodCall; |
| 7 | +use PhpParser\Node\Identifier; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Type\ExpressionTypeResolverExtension; |
| 10 | +use PHPStan\Type\NullType; |
| 11 | +use PHPStan\Type\ObjectType; |
| 12 | +use PHPStan\Type\Type; |
| 13 | +use PHPStan\Type\TypeCombinator; |
| 14 | +use PHPStan\Type\UnionType; |
| 15 | +use function count; |
| 16 | + |
| 17 | +final class BrowserKitAssertionTraitReturnTypeExtension implements ExpressionTypeResolverExtension |
| 18 | +{ |
| 19 | + |
| 20 | + private const TRAIT_NAME = 'Symfony\Bundle\FrameworkBundle\Test\BrowserKitAssertionsTrait'; |
| 21 | + private const TRAIT_METHOD_NAME = 'getclient'; |
| 22 | + |
| 23 | + public function getType(Expr $expr, Scope $scope): ?Type |
| 24 | + { |
| 25 | + if ($this->isSupported($expr, $scope)) { |
| 26 | + $args = $expr->getArgs(); |
| 27 | + if (count($args) > 0) { |
| 28 | + return TypeCombinator::intersect( |
| 29 | + $scope->getType($args[0]->value), |
| 30 | + new UnionType([ |
| 31 | + new ObjectType('Symfony\Component\BrowserKit\AbstractBrowser'), |
| 32 | + new NullType(), |
| 33 | + ]), |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + return new ObjectType('Symfony\Component\BrowserKit\AbstractBrowser'); |
| 38 | + } |
| 39 | + |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + /** |
| 44 | + * @phpstan-assert-if-true =MethodCall $expr |
| 45 | + */ |
| 46 | + private function isSupported(Expr $expr, Scope $scope): bool |
| 47 | + { |
| 48 | + if (!($expr instanceof MethodCall) || !($expr->name instanceof Identifier) || $expr->name->toLowerString() !== self::TRAIT_METHOD_NAME) { |
| 49 | + return false; |
| 50 | + } |
| 51 | + |
| 52 | + if (!$scope->isInClass()) { |
| 53 | + return false; |
| 54 | + } |
| 55 | + |
| 56 | + $methodReflection = $scope->getMethodReflection($scope->getType($expr->var), $expr->name->toString()); |
| 57 | + if ($methodReflection === null) { |
| 58 | + return false; |
| 59 | + } |
| 60 | + |
| 61 | + $reflectionClass = $methodReflection->getDeclaringClass()->getNativeReflection(); |
| 62 | + if (!$reflectionClass->hasMethod(self::TRAIT_METHOD_NAME)) { |
| 63 | + return false; |
| 64 | + } |
| 65 | + |
| 66 | + $traitMethodReflection = $reflectionClass->getMethod(self::TRAIT_METHOD_NAME); |
| 67 | + $declaringClassReflection = $traitMethodReflection->getBetterReflection()->getDeclaringClass(); |
| 68 | + |
| 69 | + return $declaringClassReflection->getName() === self::TRAIT_NAME; |
| 70 | + } |
| 71 | + |
| 72 | +} |
0 commit comments