/
GuardExtension.php
81 lines (66 loc) · 2.11 KB
/
GuardExtension.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
<?php
declare(strict_types=1);
namespace NunoMaduro\Larastan\ReturnTypes;
use Illuminate\Contracts\Auth\Guard;
use NunoMaduro\Larastan\Concerns;
use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Expr\MethodCall;
use PhpParser\Node\Expr\StaticCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeUtils;
final class GuardExtension implements DynamicMethodReturnTypeExtension
{
use Concerns\HasContainer;
use Concerns\LoadsAuthModel;
/**
* {@inheritdoc}
*/
public function getClass(): string
{
return Guard::class;
}
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'user';
}
public function getTypeFromMethodCall(
MethodReflection $methodReflection,
MethodCall $methodCall,
Scope $scope
): ?Type {
$config = $this->getContainer()->get('config');
$authModel = null;
if ($config !== null) {
$guard = $this->getGuardFromMethodCall($scope, $methodCall);
$authModel = $this->getAuthModel($config, $guard);
}
if ($authModel === null) {
return null;
}
return TypeCombinator::addNull(new ObjectType($authModel));
}
private function getGuardFromMethodCall(Scope $scope, MethodCall $methodCall): ?string
{
if (
! ($methodCall->var instanceof StaticCall) &&
! ($methodCall->var instanceof MethodCall) &&
! ($methodCall->var instanceof FuncCall)
) {
return null;
}
if (count($methodCall->var->args) !== 1) {
return null;
}
$guardType = $scope->getType($methodCall->var->getArgs()[0]->value);
$constantStrings = TypeUtils::getConstantStrings($guardType);
if (count($constantStrings) !== 1) {
return null;
}
return $constantStrings[0]->getValue();
}
}