|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Nette\PHPStan\Schema; |
| 6 | + |
| 7 | +use Nette\Schema\Elements\Structure; |
| 8 | +use Nette\Schema\Elements\Type; |
| 9 | +use Nette\Schema\Expect; |
| 10 | +use Nette\Schema\Schema; |
| 11 | +use PhpParser\Node\Expr\StaticCall; |
| 12 | +use PHPStan\Analyser\Scope; |
| 13 | +use PHPStan\Reflection\MethodReflection; |
| 14 | +use PHPStan\Type\DynamicStaticMethodReturnTypeExtension; |
| 15 | +use PHPStan\Type\ObjectType; |
| 16 | +use PHPStan\Type\Type as PhpStanType; |
| 17 | + |
| 18 | + |
| 19 | +/** |
| 20 | + * Narrows the return type of Expect::array() from Structure|Type |
| 21 | + * to Structure or Type based on the argument content. |
| 22 | + */ |
| 23 | +class ExpectArrayReturnTypeExtension implements DynamicStaticMethodReturnTypeExtension |
| 24 | +{ |
| 25 | + public function getClass(): string |
| 26 | + { |
| 27 | + return Expect::class; |
| 28 | + } |
| 29 | + |
| 30 | + |
| 31 | + public function isStaticMethodSupported(MethodReflection $methodReflection): bool |
| 32 | + { |
| 33 | + return $methodReflection->getName() === 'array'; |
| 34 | + } |
| 35 | + |
| 36 | + |
| 37 | + public function getTypeFromStaticMethodCall( |
| 38 | + MethodReflection $methodReflection, |
| 39 | + StaticCall $methodCall, |
| 40 | + Scope $scope, |
| 41 | + ): ?PhpStanType |
| 42 | + { |
| 43 | + $args = $methodCall->getArgs(); |
| 44 | + if ($args === []) { |
| 45 | + return new ObjectType(Type::class); |
| 46 | + } |
| 47 | + |
| 48 | + $argType = $scope->getType($args[0]->value); |
| 49 | + |
| 50 | + if ($argType->isNull()->yes()) { |
| 51 | + return new ObjectType(Type::class); |
| 52 | + } |
| 53 | + |
| 54 | + $constantArrays = $argType->getConstantArrays(); |
| 55 | + if ($constantArrays === []) { |
| 56 | + return null; |
| 57 | + } |
| 58 | + |
| 59 | + $valueTypes = $constantArrays[0]->getValueTypes(); |
| 60 | + if ($valueTypes === []) { |
| 61 | + return new ObjectType(Type::class); |
| 62 | + } |
| 63 | + |
| 64 | + $schemaType = new ObjectType(Schema::class); |
| 65 | + $hasSchema = false; |
| 66 | + $hasNonSchema = false; |
| 67 | + |
| 68 | + foreach ($valueTypes as $valueType) { |
| 69 | + if ($schemaType->isSuperTypeOf($valueType)->yes()) { |
| 70 | + $hasSchema = true; |
| 71 | + } else { |
| 72 | + $hasNonSchema = true; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + if ($hasSchema && !$hasNonSchema) { |
| 77 | + return new ObjectType(Structure::class); |
| 78 | + } |
| 79 | + |
| 80 | + if ($hasNonSchema && !$hasSchema) { |
| 81 | + return new ObjectType(Type::class); |
| 82 | + } |
| 83 | + |
| 84 | + return null; |
| 85 | + } |
| 86 | +} |
0 commit comments