Skip to content

Add json decode return type extension #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions phpstan-safe-rule.neon
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,7 @@ services:
class: TheCodingMachine\Safe\PHPStan\Type\Php\PregMatchTypeSpecifyingExtension
tags:
- phpstan.typeSpecifier.functionTypeSpecifyingExtension
-
class: TheCodingMachine\Safe\PHPStan\Type\Php\JsonDecodeDynamicReturnTypeExtension
tags:
- phpstan.broker.dynamicFunctionReturnTypeExtension
5 changes: 5 additions & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
Expand Up @@ -25,5 +25,10 @@ parameters:
identifier: phpstanApi.interface
count: 1
path: src/Rules/Error/SafeRuleError.php
-
message: '#^Calling PHPStan\\Type\\Php\\JsonThrowOnErrorDynamicReturnTypeExtension\:\:getTypeFromFunctionCall\(\) is not covered by backward compatibility promise\. The method might change in a minor PHPStan version\.$#'
identifier: phpstanApi.method
count: 1
path: src/Type/Php/JsonDecodeDynamicReturnTypeExtension.php
includes:
- phpstan-safe-rule.neon
46 changes: 46 additions & 0 deletions src/Type/Php/JsonDecodeDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php declare(strict_types=1);


namespace TheCodingMachine\Safe\PHPStan\Type\Php;

use PhpParser\Node\Expr\FuncCall;
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\ReflectionProvider;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\NeverType;
use PHPStan\Type\Php\JsonThrowOnErrorDynamicReturnTypeExtension;
use PHPStan\Type\Type;

/**
* @see \PHPStan\Type\Php\JsonThrowOnErrorDynamicReturnTypeExtension
*/
final class JsonDecodeDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
private FunctionReflection $nativeJsonDecodeReflection;

public function __construct(
private readonly JsonThrowOnErrorDynamicReturnTypeExtension $phpstanCheck,
ReflectionProvider $reflectionProvider,
) {
$this->nativeJsonDecodeReflection = $reflectionProvider->getFunction(new Name('json_decode'), null);
}

public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
return strtolower($functionReflection->getName()) === 'safe\json_decode';
}

public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
$result = $this->phpstanCheck->getTypeFromFunctionCall($this->nativeJsonDecodeReflection, $functionCall, $scope);

// if PHPStan reports null and there is a json error, then an invalid constant string was passed
if ($result->isNull()->yes() && JSON_ERROR_NONE !== json_last_error()) {
return new NeverType();
}

return $result;
}
}
1 change: 1 addition & 0 deletions tests/Type/Php/TypeAssertionsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ public static function dataFileAsserts(): iterable
yield from self::gatherAssertTypes(__DIR__ . '/data/preg_match_unchecked.php');
yield from self::gatherAssertTypes(__DIR__ . '/data/preg_match_checked.php');
yield from self::gatherAssertTypes(__DIR__ . '/data/preg_replace_return.php');
yield from self::gatherAssertTypes(__DIR__ . '/data/json_decode_return.php');
}

/**
Expand Down
35 changes: 35 additions & 0 deletions tests/Type/Php/data/json_decode_return.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php
$value = \Safe\json_decode('null');
\PHPStan\Testing\assertType('null', $value);

$value = \Safe\json_decode('false');
\PHPStan\Testing\assertType('false', $value);

$value = \Safe\json_decode('[]');
\PHPStan\Testing\assertType('array{}', $value);

$value = \Safe\json_decode('{}');
\PHPStan\Testing\assertType('stdClass', $value);

$value = \Safe\json_decode('{}', true);
\PHPStan\Testing\assertType('array{}', $value);

$value = \Safe\json_decode('{}', flags: JSON_OBJECT_AS_ARRAY);
\PHPStan\Testing\assertType('array{}', $value);

$value = \Safe\json_decode('{"foo": "bar"}');
\PHPStan\Testing\assertType('stdClass', $value);

$value = \Safe\json_decode('{"foo": "bar"}', true);
\PHPStan\Testing\assertType("array{foo: 'bar'}", $value);

$value = \Safe\json_decode('{', true);
\PHPStan\Testing\assertType('*NEVER*', $value);

function(string $json): void {
$value = \Safe\json_decode($json);
\PHPStan\Testing\assertType('mixed', $value);

$value = \Safe\json_decode($json, true);
\PHPStan\Testing\assertType('mixed~object', $value);
};
2 changes: 1 addition & 1 deletion tests/Type/Php/data/preg_match_unchecked.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
$string = 'Hello World';

// when return value isn't checked, we may-or-may-not have matches
$type = "array{0?: string, 1?: non-empty-string, 2?: 'o', 3?: 'World'}";
$type = "list{0?: string, 1?: non-empty-string, 2?: 'o', 3?: 'World'}";

// @phpstan-ignore-next-line - use of unsafe is intentional
\preg_match($pattern, $string, $matches);
Expand Down