|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Proget\PHPStan\Yii2\Type; |
| 6 | + |
| 7 | +use PhpParser\Node\Expr\ConstFetch; |
| 8 | +use PhpParser\Node\Expr\MethodCall; |
| 9 | +use PHPStan\Analyser\Scope; |
| 10 | +use PHPStan\Reflection\MethodReflection; |
| 11 | +use PHPStan\Type\ArrayType; |
| 12 | +use PHPStan\Type\DynamicMethodReturnTypeExtension; |
| 13 | +use PHPStan\Type\IntegerType; |
| 14 | +use PHPStan\Type\StringType; |
| 15 | +use PHPStan\Type\Type; |
| 16 | +use PHPStan\Type\UnionType; |
| 17 | +use yii\web\HeaderCollection; |
| 18 | + |
| 19 | +class HeaderCollectionDynamicMethodReturnTypeExtension implements DynamicMethodReturnTypeExtension |
| 20 | +{ |
| 21 | + public function getClass(): string |
| 22 | + { |
| 23 | + return HeaderCollection::class; |
| 24 | + } |
| 25 | + |
| 26 | + public function isMethodSupported(MethodReflection $methodReflection): bool |
| 27 | + { |
| 28 | + return $methodReflection->getName() === 'get'; |
| 29 | + } |
| 30 | + |
| 31 | + public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type |
| 32 | + { |
| 33 | + if (count($methodCall->args) < 3) { |
| 34 | + // $first === true (the default) and the get-method returns something of type string |
| 35 | + return new StringType(); |
| 36 | + } |
| 37 | + |
| 38 | + $val = $methodCall->args[2]->value; |
| 39 | + if ($val instanceof ConstFetch) { |
| 40 | + $value = $val->name->parts[0]; |
| 41 | + if ($value === 'true') { |
| 42 | + // $first === true, therefore string |
| 43 | + return new StringType(); |
| 44 | + } |
| 45 | + |
| 46 | + if ($value === 'false') { |
| 47 | + // $first === false, therefore string[] |
| 48 | + return new ArrayType(new IntegerType(), new StringType()); |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + // Unable to figure out value of third parameter $first, therefore it can be of either type |
| 53 | + return new UnionType([new ArrayType(new IntegerType(), new StringType()), new StringType()]); |
| 54 | + } |
| 55 | +} |
0 commit comments