|
| 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\Analyser\SpecifiedTypes; |
| 8 | +use PHPStan\Analyser\TypeSpecifier; |
| 9 | +use PHPStan\Analyser\TypeSpecifierAwareExtension; |
| 10 | +use PHPStan\Analyser\TypeSpecifierContext; |
| 11 | +use PHPStan\Broker\Broker; |
| 12 | +use PHPStan\Reflection\MethodReflection; |
| 13 | +use PHPStan\Reflection\ParametersAcceptorSelector; |
| 14 | +use PHPStan\Type\MethodTypeSpecifyingExtension; |
| 15 | +use PHPStan\Type\TypeCombinator; |
| 16 | + |
| 17 | +final class RequestTypeSpecifyingExtension implements MethodTypeSpecifyingExtension, TypeSpecifierAwareExtension |
| 18 | +{ |
| 19 | + |
| 20 | + private const REQUEST_CLASS = 'Symfony\Component\HttpFoundation\Request'; |
| 21 | + private const HAS_METHOD_NAME = 'hasSession'; |
| 22 | + private const GET_METHOD_NAME = 'getSession'; |
| 23 | + |
| 24 | + /** @var Broker */ |
| 25 | + private $broker; |
| 26 | + |
| 27 | + /** @var TypeSpecifier */ |
| 28 | + private $typeSpecifier; |
| 29 | + |
| 30 | + public function __construct(Broker $broker) |
| 31 | + { |
| 32 | + $this->broker = $broker; |
| 33 | + } |
| 34 | + |
| 35 | + public function getClass(): string |
| 36 | + { |
| 37 | + return self::REQUEST_CLASS; |
| 38 | + } |
| 39 | + |
| 40 | + public function isMethodSupported(MethodReflection $methodReflection, MethodCall $node, TypeSpecifierContext $context): bool |
| 41 | + { |
| 42 | + return $methodReflection->getName() === self::HAS_METHOD_NAME && !$context->null(); |
| 43 | + } |
| 44 | + |
| 45 | + public function specifyTypes(MethodReflection $methodReflection, MethodCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes |
| 46 | + { |
| 47 | + $classReflection = $this->broker->getClass(self::REQUEST_CLASS); |
| 48 | + $methodVariants = $classReflection->getNativeMethod(self::GET_METHOD_NAME)->getVariants(); |
| 49 | + |
| 50 | + return $this->typeSpecifier->create( |
| 51 | + new MethodCall($node->var, self::GET_METHOD_NAME), |
| 52 | + TypeCombinator::removeNull(ParametersAcceptorSelector::selectSingle($methodVariants)->getReturnType()), |
| 53 | + $context |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void |
| 58 | + { |
| 59 | + $this->typeSpecifier = $typeSpecifier; |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments