|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Kris\LaravelFormBuilder\PhpStan; |
| 4 | + |
| 5 | +use Kris\LaravelFormBuilder\Fields\ChildFormType; |
| 6 | +use Kris\LaravelFormBuilder\Form; |
| 7 | +use Kris\LaravelFormBuilder\FormHelper; |
| 8 | +use Larastan\Larastan\Concerns\HasContainer; |
| 9 | +use PHPStan\Analyser\Scope; |
| 10 | +use PHPStan\Reflection\Annotations\AnnotationPropertyReflection; |
| 11 | +use PHPStan\Reflection\MethodReflection; |
| 12 | +use PHPStan\Reflection\ReflectionProvider; |
| 13 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 14 | +use PHPStan\Type\ObjectType; |
| 15 | +use PHPStan\Type\Type; |
| 16 | +use PHPStan\Type\TypeWithClassName; |
| 17 | +use PhpParser\Node\Expr; |
| 18 | +use PhpParser\Node\Expr\Array_; |
| 19 | +use PhpParser\Node\Expr\ClassConstFetch; |
| 20 | +use PhpParser\Node\Expr\MethodCall; |
| 21 | +use PhpParser\Node\Scalar\String_; |
| 22 | + |
| 23 | +class FormGetFieldExtension implements DynamicMethodReturnTypeExtension |
| 24 | +{ |
| 25 | + |
| 26 | + public function __construct( |
| 27 | + protected ReflectionProvider $reflectionProvider, |
| 28 | + ) {} |
| 29 | + |
| 30 | + public function getClass(): string { |
| 31 | + return Form::class; |
| 32 | + } |
| 33 | + |
| 34 | + public function isMethodSupported(MethodReflection $methodReflection): bool { |
| 35 | + return $methodReflection->getName() == 'getField'; |
| 36 | + } |
| 37 | + |
| 38 | + public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type { |
| 39 | + return $this->getTypeFromMethodCallGetField($methodReflection, $methodCall, $scope); |
| 40 | + } |
| 41 | + |
| 42 | + protected function getTypeFromMethodCallGetField(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): ?Type |
| 43 | + { |
| 44 | + if (count($methodCall->getArgs()) < 1) { |
| 45 | + return null; |
| 46 | + } |
| 47 | + |
| 48 | + $fieldNameArg = $methodCall->getArgs()[0]->value; |
| 49 | + if (!($fieldNameArg instanceof String_)) { |
| 50 | + return null; |
| 51 | + } |
| 52 | + |
| 53 | + $fieldName = $fieldNameArg->value; |
| 54 | + |
| 55 | + $calledOnType = $scope->getType($methodCall->var); |
| 56 | + assert($calledOnType instanceof TypeWithClassName); |
| 57 | + $formClass = $calledOnType->getClassName(); |
| 58 | + |
| 59 | + $formClassReflection = $this->reflectionProvider->getClass($formClass); |
| 60 | + |
| 61 | + if (!$formClassReflection->hasProperty($fieldName)) { |
| 62 | + return null; |
| 63 | + } |
| 64 | + |
| 65 | + $formClassFieldProperty = $formClassReflection->getProperty($fieldName, $scope); |
| 66 | + if (!($formClassFieldProperty instanceof AnnotationPropertyReflection)) { |
| 67 | + return null; |
| 68 | + } |
| 69 | + |
| 70 | + return $formClassFieldProperty->getReadableType(); |
| 71 | + } |
| 72 | + |
| 73 | +} |
0 commit comments