|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Set return type of get_post(). |
| 5 | + */ |
| 6 | + |
| 7 | +declare(strict_types=1); |
| 8 | + |
| 9 | +namespace PHPStan\WordPress; |
| 10 | + |
| 11 | +use PhpParser\Node\Expr\FuncCall; |
| 12 | +use PHPStan\Analyser\Scope; |
| 13 | +use PHPStan\Reflection\FunctionReflection; |
| 14 | +use PHPStan\Reflection\ParametersAcceptorSelector; |
| 15 | +use PHPStan\Type\Type; |
| 16 | +use PHPStan\Type\ArrayType; |
| 17 | +use PHPStan\Type\IntegerType; |
| 18 | +use PHPStan\Type\ObjectType; |
| 19 | +use PHPStan\Type\StringType; |
| 20 | +use PHPStan\Type\Constant\ConstantStringType; |
| 21 | + |
| 22 | +class GetTaxonomiesDynamicFunctionReturnTypeExtension implements \PHPStan\Type\DynamicFunctionReturnTypeExtension |
| 23 | +{ |
| 24 | + public function isFunctionSupported(FunctionReflection $functionReflection): bool |
| 25 | + { |
| 26 | + return in_array($functionReflection->getName(), ['get_taxonomies'], true); |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * @see https://developer.wordpress.org/reference/functions/get_taxonomies/ |
| 31 | + */ |
| 32 | + public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type |
| 33 | + { |
| 34 | + // Called without second $output arguments |
| 35 | + if (count($functionCall->args) <= 1) { |
| 36 | + return new ArrayType(new IntegerType(), new ObjectType('WP_Taxonomy')); |
| 37 | + } |
| 38 | + |
| 39 | + $argumentType = $scope->getType($functionCall->args[1]->value); |
| 40 | + |
| 41 | + // When called with a non-string $output, return default return type |
| 42 | + if (! $argumentType instanceof ConstantStringType) { |
| 43 | + return ParametersAcceptorSelector::selectFromArgs( |
| 44 | + $scope, |
| 45 | + $functionCall->args, |
| 46 | + $functionReflection->getVariants() |
| 47 | + )->getReturnType(); |
| 48 | + } |
| 49 | + |
| 50 | + // Called with a string $output |
| 51 | + switch ($argumentType->getValue()) { |
| 52 | + case 'names': |
| 53 | + return new ArrayType(new IntegerType(), new StringType()); |
| 54 | + case 'objects': |
| 55 | + default: |
| 56 | + return new ArrayType(new IntegerType(), new ObjectType('WP_Taxonomy')); |
| 57 | + } |
| 58 | + } |
| 59 | +} |
0 commit comments