-
-
Notifications
You must be signed in to change notification settings - Fork 18
/
DoctrineConnectionQueryDynamicReturnTypeExtension.php
78 lines (64 loc) · 2.47 KB
/
DoctrineConnectionQueryDynamicReturnTypeExtension.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
<?php
declare(strict_types=1);
namespace staabm\PHPStanDba\Extensions;
use Composer\InstalledVersions;
use Composer\Semver\VersionParser;
use Doctrine\DBAL\Connection;
use PhpParser\Node\Expr;
use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\MixedType;
use PHPStan\Type\Type;
use staabm\PHPStanDba\DoctrineReflection\DoctrineReflection;
use staabm\PHPStanDba\QueryReflection\QueryReflection;
use staabm\PHPStanDba\QueryReflection\QueryReflector;
use staabm\PHPStanDba\UnresolvableQueryException;
final class DoctrineConnectionQueryDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension
{
public function getClass(): string
{
return Connection::class;
}
public function isMethodSupported(MethodReflection $methodReflection): bool
{
return \in_array(strtolower($methodReflection->getName()), ['query'], true);
}
public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
$args = $methodCall->getArgs();
$defaultReturn = ParametersAcceptorSelector::selectFromArgs(
$scope,
$methodCall->getArgs(),
$methodReflection->getVariants(),
)->getReturnType();
if (\count($args) < 1) {
return $defaultReturn;
}
if ($scope->getType($args[0]->value) instanceof MixedType) {
return $defaultReturn;
}
// make sure we don't report wrong types in doctrine 2.x
if (!InstalledVersions::satisfies(new VersionParser(), 'doctrine/dbal', '3.*')) {
return $defaultReturn;
}
try {
$resultType = $this->inferType($args[0]->value, $scope);
if (null !== $resultType) {
return $resultType;
}
} catch (UnresolvableQueryException $exception) {
// simulation not possible.. use default value
}
return $defaultReturn;
}
private function inferType(Expr $queryExpr, Scope $scope): ?Type
{
$queryReflection = new QueryReflection();
$queryStrings = $queryReflection->resolveQueryStrings($queryExpr, $scope);
$doctrineReflection = new DoctrineReflection();
return $doctrineReflection->createGenericResult($queryStrings, QueryReflector::FETCH_TYPE_BOTH);
}
}