|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace PHPStan\Type\Symfony\Form; |
| 4 | + |
| 5 | +use PhpParser\Node\Expr\MethodCall; |
| 6 | +use PHPStan\Analyser\Scope; |
| 7 | +use PHPStan\Reflection\MethodReflection; |
| 8 | +use PHPStan\Type\Constant\ConstantBooleanType; |
| 9 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 10 | +use PHPStan\Type\Generic\GenericObjectType; |
| 11 | +use PHPStan\Type\ObjectType; |
| 12 | +use PHPStan\Type\Type; |
| 13 | +use PHPStan\Type\UnionType; |
| 14 | +use Symfony\Component\Form\FormError; |
| 15 | +use Symfony\Component\Form\FormErrorIterator; |
| 16 | +use Symfony\Component\Form\FormInterface; |
| 17 | + |
| 18 | +final class FormInterfaceDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension |
| 19 | +{ |
| 20 | + |
| 21 | + public function getClass(): string |
| 22 | + { |
| 23 | + return FormInterface::class; |
| 24 | + } |
| 25 | + |
| 26 | + public function isMethodSupported(MethodReflection $methodReflection): bool |
| 27 | + { |
| 28 | + return $methodReflection->getName() === 'getErrors'; |
| 29 | + } |
| 30 | + |
| 31 | + public function getTypeFromMethodCall( |
| 32 | + MethodReflection $methodReflection, |
| 33 | + MethodCall $methodCall, |
| 34 | + Scope $scope |
| 35 | + ): Type |
| 36 | + { |
| 37 | + if (!isset($methodCall->getArgs()[1])) { |
| 38 | + return new GenericObjectType(FormErrorIterator::class, [new ObjectType(FormError::class)]); |
| 39 | + } |
| 40 | + |
| 41 | + $firstArgType = $scope->getType($methodCall->getArgs()[0]->value); |
| 42 | + $secondArgType = $scope->getType($methodCall->getArgs()[1]->value); |
| 43 | + |
| 44 | + $firstIsTrueType = (new ConstantBooleanType(true))->isSuperTypeOf($firstArgType); |
| 45 | + $firstIsFalseType = (new ConstantBooleanType(false))->isSuperTypeOf($firstArgType); |
| 46 | + $secondIsTrueType = (new ConstantBooleanType(true))->isSuperTypeOf($secondArgType); |
| 47 | + $secondIsFalseType = (new ConstantBooleanType(false))->isSuperTypeOf($secondArgType); |
| 48 | + |
| 49 | + $firstCompareType = $firstIsTrueType->compareTo($firstIsFalseType); |
| 50 | + $secondCompareType = $secondIsTrueType->compareTo($secondIsFalseType); |
| 51 | + |
| 52 | + if ($firstCompareType === $firstIsTrueType && $secondCompareType === $secondIsFalseType) { |
| 53 | + return new GenericObjectType(FormErrorIterator::class, [ |
| 54 | + new UnionType([ |
| 55 | + new ObjectType(FormError::class), |
| 56 | + new ObjectType(FormErrorIterator::class), |
| 57 | + ]), |
| 58 | + ]); |
| 59 | + } |
| 60 | + |
| 61 | + return new GenericObjectType(FormErrorIterator::class, [new ObjectType(FormError::class)]); |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments