|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace mglaman\PHPStanDrupal\Type\EntityStorage; |
| 4 | + |
| 5 | +use Drupal\Core\Config\Entity\ConfigEntityStorageInterface; |
| 6 | +use Drupal\Core\Entity\ContentEntityStorageInterface; |
| 7 | +use Drupal\Core\Entity\EntityStorageInterface; |
| 8 | +use mglaman\PHPStanDrupal\Type\EntityQuery\ConfigEntityQueryType; |
| 9 | +use mglaman\PHPStanDrupal\Type\EntityQuery\ContentEntityQueryType; |
| 10 | +use PhpParser\Node\Expr\MethodCall; |
| 11 | +use PHPStan\Analyser\Scope; |
| 12 | +use PHPStan\Reflection\MethodReflection; |
| 13 | +use PHPStan\Reflection\ParametersAcceptorSelector; |
| 14 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 15 | +use PHPStan\Type\ObjectType; |
| 16 | + |
| 17 | +final class GetQueryReturnTypeExtension implements DynamicMethodReturnTypeExtension |
| 18 | +{ |
| 19 | + |
| 20 | + public function getClass(): string |
| 21 | + { |
| 22 | + return EntityStorageInterface::class; |
| 23 | + } |
| 24 | + |
| 25 | + public function isMethodSupported(MethodReflection $methodReflection): bool |
| 26 | + { |
| 27 | + return $methodReflection->getName() === 'getQuery'; |
| 28 | + } |
| 29 | + |
| 30 | + public function getTypeFromMethodCall( |
| 31 | + MethodReflection $methodReflection, |
| 32 | + MethodCall $methodCall, |
| 33 | + Scope $scope |
| 34 | + ): \PHPStan\Type\Type { |
| 35 | + $returnType = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants())->getReturnType(); |
| 36 | + if (!$returnType instanceof ObjectType) { |
| 37 | + return $returnType; |
| 38 | + } |
| 39 | + |
| 40 | + $callerType = $scope->getType($methodCall->var); |
| 41 | + if (!$callerType instanceof ObjectType) { |
| 42 | + return $returnType; |
| 43 | + } |
| 44 | + |
| 45 | + if ((new ObjectType(ContentEntityStorageInterface::class))->isSuperTypeOf($callerType)->yes()) { |
| 46 | + return new ContentEntityQueryType( |
| 47 | + $returnType->getClassName(), |
| 48 | + $returnType->getSubtractedType(), |
| 49 | + $returnType->getClassReflection() |
| 50 | + ); |
| 51 | + } |
| 52 | + if ((new ObjectType(ConfigEntityStorageInterface::class))->isSuperTypeOf($callerType)->yes()) { |
| 53 | + return new ConfigEntityQueryType( |
| 54 | + $returnType->getClassName(), |
| 55 | + $returnType->getSubtractedType(), |
| 56 | + $returnType->getClassReflection() |
| 57 | + ); |
| 58 | + } |
| 59 | + return $returnType; |
| 60 | + } |
| 61 | +} |
0 commit comments