Skip to content

Commit b931433

Browse files
committed
Figure out get_taxonomies's return type
1 parent 604376f commit b931433

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

extension.neon

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ services:
2323
class: PHPStan\WordPress\GetPostsDynamicFunctionReturnTypeExtension
2424
tags:
2525
- phpstan.broker.dynamicFunctionReturnTypeExtension
26+
-
27+
class: PHPStan\WordPress\GetTaxonomiesDynamicFunctionReturnTypeExtension
28+
tags:
29+
- phpstan.broker.dynamicFunctionReturnTypeExtension
2630
parameters:
2731
bootstrapFiles:
2832
- ../../php-stubs/wordpress-stubs/wordpress-stubs.php
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
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

Comments
 (0)