|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Doctrine\QueryBuilder; |
| 4 | + |
| 5 | +use PhpParser\Node\Arg; |
| 6 | +use PhpParser\Node\Expr\MethodCall; |
| 7 | +use PhpParser\Node\Identifier; |
| 8 | +use PhpParser\Node\Scalar\String_; |
| 9 | +use PHPStan\Analyser\Scope; |
| 10 | +use PHPStan\Reflection\MethodReflection; |
| 11 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 12 | +use PHPStan\Type\Generic\GenericClassStringType; |
| 13 | +use PHPStan\Type\Type; |
| 14 | +use PHPStan\Type\TypeWithClassName; |
| 15 | + |
| 16 | +class EntityRepositoryCreateQueryBuilderDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension |
| 17 | +{ |
| 18 | + |
| 19 | + public function getClass(): string |
| 20 | + { |
| 21 | + return 'Doctrine\ORM\EntityRepository'; |
| 22 | + } |
| 23 | + |
| 24 | + public function isMethodSupported(MethodReflection $methodReflection): bool |
| 25 | + { |
| 26 | + return $methodReflection->getName() === 'createQueryBuilder'; |
| 27 | + } |
| 28 | + |
| 29 | + public function getTypeFromMethodCall( |
| 30 | + MethodReflection $methodReflection, |
| 31 | + MethodCall $methodCall, |
| 32 | + Scope $scope |
| 33 | + ): Type |
| 34 | + { |
| 35 | + $entityNameExpr = new MethodCall($methodCall->var, new Identifier('getEntityName')); |
| 36 | + |
| 37 | + $entityNameExprType = $scope->getType($entityNameExpr); |
| 38 | + if ($entityNameExprType instanceof GenericClassStringType && $entityNameExprType->getGenericType() instanceof TypeWithClassName) { |
| 39 | + $entityNameExpr = new String_($entityNameExprType->getGenericType()->getClassName()); |
| 40 | + } |
| 41 | + |
| 42 | + $fromArgs = $methodCall->args; |
| 43 | + array_unshift($fromArgs, new Arg($entityNameExpr)); |
| 44 | + |
| 45 | + $callStack = new MethodCall($methodCall->var, new Identifier('getEntityManager')); |
| 46 | + $callStack = new MethodCall($callStack, new Identifier('createQueryBuilder')); |
| 47 | + $callStack = new MethodCall($callStack, new Identifier('select'), [$methodCall->args[0]]); |
| 48 | + $callStack = new MethodCall($callStack, new Identifier('from'), $fromArgs); |
| 49 | + |
| 50 | + return $scope->getType($callStack); |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments