|
| 1 | +<?php declare(strict_types=1); |
| 2 | + |
| 3 | +namespace mglaman\PHPStanDrupal\Type; |
| 4 | + |
| 5 | +use Drupal\Core\Entity\EntityTypeInterface; |
| 6 | +use PhpParser\Node\Expr\MethodCall; |
| 7 | +use PhpParser\Node\Identifier; |
| 8 | +use PHPStan\Analyser\Scope; |
| 9 | +use PHPStan\Reflection\MethodReflection; |
| 10 | +use PHPStan\Type\Constant\ConstantBooleanType; |
| 11 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 12 | +use PHPStan\Type\StringType; |
| 13 | +use PHPStan\Type\Type; |
| 14 | + |
| 15 | +/** |
| 16 | + * @author Daniel Phin <[email protected]> |
| 17 | + */ |
| 18 | +class EntityTypeKeyByExistence implements DynamicMethodReturnTypeExtension |
| 19 | +{ |
| 20 | + |
| 21 | + public function getClass(): string |
| 22 | + { |
| 23 | + return EntityTypeInterface::class; |
| 24 | + } |
| 25 | + |
| 26 | + public function isMethodSupported(MethodReflection $methodReflection): bool |
| 27 | + { |
| 28 | + return $methodReflection->getName() === 'getKey'; |
| 29 | + } |
| 30 | + |
| 31 | + public function getTypeFromMethodCall( |
| 32 | + MethodReflection $methodReflection, |
| 33 | + MethodCall $methodCall, |
| 34 | + Scope $scope |
| 35 | + ): ?Type { |
| 36 | + $keyArg = $methodCall->getArg('key', 0); |
| 37 | + if (null === $keyArg) { |
| 38 | + // Key is a required arg but ignore if it isn't set. |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + $originalReturnType = $methodReflection->getVariants()[0]->getReturnType(); |
| 43 | + $hasKeyMethodCall = new MethodCall($methodCall->var, new Identifier('hasKey'), [$keyArg]); |
| 44 | + if ($scope->getType($hasKeyMethodCall)->isTrue()->yes()) { |
| 45 | + return $originalReturnType->tryRemove(new ConstantBooleanType(false)); |
| 46 | + } elseif ($scope->getType($hasKeyMethodCall)->isFalse()->yes()) { |
| 47 | + return $originalReturnType->tryRemove(new StringType()); |
| 48 | + } |
| 49 | + |
| 50 | + return $originalReturnType; |
| 51 | + } |
| 52 | +} |
0 commit comments