|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Set return type of get_sites(). |
| 5 | + */ |
| 6 | + |
| 7 | +declare(strict_types=1); |
| 8 | + |
| 9 | +namespace SzepeViktor\PHPStan\WordPress; |
| 10 | + |
| 11 | +use PhpParser\Node\Expr\FuncCall; |
| 12 | +use PHPStan\Analyser\Scope; |
| 13 | +use PHPStan\Reflection\FunctionReflection; |
| 14 | +use PHPStan\Type\Type; |
| 15 | +use PHPStan\Type\ArrayType; |
| 16 | +use PHPStan\Type\IntegerType; |
| 17 | +use PHPStan\Type\ObjectType; |
| 18 | +use PHPStan\Type\Constant\ConstantArrayType; |
| 19 | +use PHPStan\Type\Constant\ConstantStringType; |
| 20 | + |
| 21 | +class GetSitesDynamicFunctionReturnTypeExtension implements \PHPStan\Type\DynamicFunctionReturnTypeExtension |
| 22 | +{ |
| 23 | + public function isFunctionSupported(FunctionReflection $functionReflection): bool |
| 24 | + { |
| 25 | + return $functionReflection->getName() === 'get_sites'; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * @see https://developer.wordpress.org/reference/classes/wp_query/#return-fields-parameter |
| 30 | + */ |
| 31 | + // phpcs:ignore SlevomatCodingStandard.Functions.UnusedParameter |
| 32 | + public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type |
| 33 | + { |
| 34 | + $args = $functionCall->getArgs(); |
| 35 | + |
| 36 | + // Called without arguments |
| 37 | + if (count($args) === 0) { |
| 38 | + return new ArrayType(new IntegerType(), new ObjectType('WP_Site')); |
| 39 | + } |
| 40 | + |
| 41 | + $fields = ''; |
| 42 | + |
| 43 | + $argumentType = $scope->getType($args[0]->value); |
| 44 | + |
| 45 | + // Called with an array argument |
| 46 | + if ($argumentType instanceof ConstantArrayType) { |
| 47 | + foreach ($argumentType->getKeyTypes() as $index => $key) { |
| 48 | + if (! $key instanceof ConstantStringType || $key->getValue() !== 'fields') { |
| 49 | + continue; |
| 50 | + } |
| 51 | + |
| 52 | + $fieldsType = $argumentType->getValueTypes()[$index]; |
| 53 | + if ($fieldsType instanceof ConstantStringType) { |
| 54 | + $fields = $fieldsType->getValue(); |
| 55 | + } |
| 56 | + break; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // Called with a string argument |
| 61 | + if ($argumentType instanceof ConstantStringType) { |
| 62 | + parse_str($argumentType->getValue(), $variables); |
| 63 | + $fields = $variables['fields'] ?? 'all'; |
| 64 | + } |
| 65 | + |
| 66 | + switch ($fields) { |
| 67 | + case 'count': |
| 68 | + return new IntegerType(); |
| 69 | + case 'ids': |
| 70 | + return new ArrayType(new IntegerType(), new IntegerType()); |
| 71 | + default: |
| 72 | + return new ArrayType(new IntegerType(), new ObjectType('WP_Site')); |
| 73 | + } |
| 74 | + } |
| 75 | +} |
0 commit comments