Skip to content

Commit 9dbf2f8

Browse files
committed
Set get_post()'s return type
1 parent 969e12d commit 9dbf2f8

File tree

2 files changed

+46
-3
lines changed

2 files changed

+46
-3
lines changed

extension.neon

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,10 @@ services:
1515
class: PHPStan\WordPress\EscSqlDynamicFunctionReturnTypeExtension
1616
tags:
1717
- phpstan.broker.dynamicFunctionReturnTypeExtension
18+
-
19+
class: PHPStan\WordPress\GetPostDynamicFunctionReturnTypeExtension
20+
tags:
21+
- phpstan.broker.dynamicFunctionReturnTypeExtension
1822
parameters:
1923
autoload_files:
2024
- %rootDir%/../../giacocorsiglia/wordpress-stubs/wordpress-stubs.php
Lines changed: 42 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,44 @@
1-
<?php
1+
<?php declare(strict_types = 1);
22
/**
33
* Set return type of get_post().
4-
* TODO https://developer.wordpress.org/reference/functions/get_post/
5-
*/
4+
*/
5+
6+
namespace PHPStan\WordPress;
7+
8+
use PhpParser\Node\Expr\FuncCall;
9+
use PHPStan\Analyser\Scope;
10+
use PHPStan\Reflection\FunctionReflection;
11+
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
12+
use PHPStan\Type\Type;
13+
use PHPStan\Type\ArrayType;
14+
use PHPStan\Type\StringType;
15+
use PHPStan\Type\IntegerType;
16+
use PHPStan\Type\MixedType;
17+
use PHPStan\Type\ObjectType;
18+
use PHPStan\Type\NullType;
19+
use PHPStan\Type\TypeCombinator;
20+
21+
class GetPostDynamicFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
22+
{
23+
public function isFunctionSupported(FunctionReflection $functionReflection): bool
24+
{
25+
return $functionReflection->getName() === 'get_post';
26+
}
27+
28+
public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
29+
{
30+
$output = 'OBJECT';
31+
$argsCount = count($functionCall->args);
32+
if ($argsCount >= 2 && $functionCall->args[1]->value !== 'OBJECT') {
33+
$output = $functionCall->args[1]->value;
34+
}
35+
if ($output === 'ARRAY_A') {
36+
return TypeCombinator::union(new ArrayType(new StringType(), new MixedType()), new NullType());
37+
}
38+
if ($output === 'ARRAY_N') {
39+
return TypeCombinator::union(new ArrayType(new IntegerType(), new MixedType()), new NullType());
40+
}
41+
42+
return TypeCombinator::union(new ObjectType('WP_Post'), new NullType());
43+
}
44+
}

0 commit comments

Comments
 (0)