Skip to content

Commit ec4ab2b

Browse files
committed
Support for Request::getSession type specifying.
1 parent 66d7f9e commit ec4ab2b

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

extension.neon

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,11 @@ services:
5959
factory: PHPStan\Type\Symfony\RequestDynamicReturnTypeExtension
6060
tags: [phpstan.broker.dynamicMethodReturnTypeExtension]
6161

62+
# Request::getSession() type specification
63+
-
64+
factory: PHPStan\Type\Symfony\RequestTypeSpecifyingExtension
65+
tags: [phpstan.typeSpecifier.methodTypeSpecifyingExtension]
66+
6267
# HeaderBag::get() return type
6368
-
6469
factory: PHPStan\Type\Symfony\HeaderBagDynamicReturnTypeExtension
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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+
use Symfony\Component\HttpFoundation\Request;
17+
18+
final class RequestTypeSpecifyingExtension implements MethodTypeSpecifyingExtension, TypeSpecifierAwareExtension
19+
{
20+
21+
/** @var Broker */
22+
private $broker;
23+
24+
/** @var TypeSpecifier */
25+
private $typeSpecifier;
26+
27+
public function __construct(Broker $broker)
28+
{
29+
$this->broker = $broker;
30+
}
31+
32+
public function getClass(): string
33+
{
34+
return Request::class;
35+
}
36+
37+
public function isMethodSupported(MethodReflection $methodReflection, MethodCall $node, TypeSpecifierContext $context): bool
38+
{
39+
return $methodReflection->getName() === 'hasSession' && !$context->null();
40+
}
41+
42+
public function specifyTypes(MethodReflection $methodReflection, MethodCall $node, Scope $scope, TypeSpecifierContext $context): SpecifiedTypes
43+
{
44+
$classReflection = $this->broker->getClass(Request::class);
45+
$methodVariants = $classReflection->getNativeMethod('getSession')->getVariants();
46+
47+
return $this->typeSpecifier->create(
48+
new MethodCall($node->var, 'getSession'),
49+
TypeCombinator::removeNull(ParametersAcceptorSelector::selectSingle($methodVariants)->getReturnType()),
50+
$context
51+
);
52+
}
53+
54+
public function setTypeSpecifier(TypeSpecifier $typeSpecifier): void
55+
{
56+
$this->typeSpecifier = $typeSpecifier;
57+
}
58+
59+
}

0 commit comments

Comments
 (0)