Skip to content

Commit

Permalink
Set get_post()'s return type
Browse files Browse the repository at this point in the history
  • Loading branch information
szepeviktor committed Jun 25, 2019
1 parent 969e12d commit 9dbf2f8
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 3 deletions.
4 changes: 4 additions & 0 deletions extension.neon
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ services:
class: PHPStan\WordPress\EscSqlDynamicFunctionReturnTypeExtension
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension
-
class: PHPStan\WordPress\GetPostDynamicFunctionReturnTypeExtension
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension
parameters:
autoload_files:
- %rootDir%/../../giacocorsiglia/wordpress-stubs/wordpress-stubs.php
Expand Down
45 changes: 42 additions & 3 deletions src/GetPostDynamicFunctionReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,44 @@
<?php
<?php declare(strict_types = 1);
/**
* Set return type of get_post().
* TODO https://developer.wordpress.org/reference/functions/get_post/
*/
*/

namespace PHPStan\WordPress;

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\Type;
use PHPStan\Type\ArrayType;
use PHPStan\Type\StringType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\NullType;
use PHPStan\Type\TypeCombinator;

class GetPostDynamicFunctionReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return $functionReflection->getName() === 'get_post';
}

public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
$output = 'OBJECT';
$argsCount = count($functionCall->args);
if ($argsCount >= 2 && $functionCall->args[1]->value !== 'OBJECT') {
$output = $functionCall->args[1]->value;
}
if ($output === 'ARRAY_A') {
return TypeCombinator::union(new ArrayType(new StringType(), new MixedType()), new NullType());
}
if ($output === 'ARRAY_N') {
return TypeCombinator::union(new ArrayType(new IntegerType(), new MixedType()), new NullType());
}

return TypeCombinator::union(new ObjectType('WP_Post'), new NullType());
}
}

0 comments on commit 9dbf2f8

Please sign in to comment.