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 2 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\\BitwiseFlagHelper::bitwiseOrContainsConstant\(\) 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
108 changes: 108 additions & 0 deletions src/Type/Php/JsonDecodeDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
<?php declare(strict_types=1);


namespace TheCodingMachine\Safe\PHPStan\Type\Php;

use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\BitwiseFlagHelper;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ConstantScalarType;
use PHPStan\Type\ConstantTypeHelper;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\NeverType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use Safe\Exceptions\JsonException;

/**
* @see \PHPStan\Type\Php\JsonThrowOnErrorDynamicReturnTypeExtension
*/
final class JsonDecodeDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
public function __construct(
private readonly BitwiseFlagHelper $bitwiseFlagAnalyser,
) {
}

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

public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $functionCall, Scope $scope): Type
{
$defaultReturnType = ParametersAcceptorSelector::selectFromArgs(
$scope,
$functionCall->getArgs(),
$functionReflection->getVariants(),
)->getReturnType();

return $this->narrowTypeForJsonDecode($functionCall, $scope, $defaultReturnType);
}

private function narrowTypeForJsonDecode(FuncCall $funcCall, Scope $scope, Type $fallbackType): Type
{
$args = $funcCall->getArgs();
$isForceArray = $this->isForceArray($funcCall, $scope);
if (!isset($args[0])) {
return $fallbackType;
}

$firstValueType = $scope->getType($args[0]->value);
if ([] !== $firstValueType->getConstantStrings()) {
$types = [];

foreach ($firstValueType->getConstantStrings() as $constantString) {
$types[] = $this->resolveConstantStringType($constantString, $isForceArray);
}

return TypeCombinator::union(...$types);
}

if ($isForceArray) {
return TypeCombinator::remove($fallbackType, new ObjectWithoutClassType());
}

return $fallbackType;
}

/**
* Is "json_decode(..., true)"?
*/
private function isForceArray(FuncCall $funcCall, Scope $scope): bool
{
$args = $funcCall->getArgs();
if (!isset($args[1])) {
return false;
}

$secondArgType = $scope->getType($args[1]->value);
$secondArgValue = 1 === \count($secondArgType->getConstantScalarValues()) ? $secondArgType->getConstantScalarValues()[0] : null;

if (is_bool($secondArgValue)) {
return $secondArgValue;
}

if ($secondArgValue !== null || !isset($args[3])) {
return false;
}

// depends on used constants, @see https://www.php.net/manual/en/json.constants.php#constant.json-object-as-array
return $this->bitwiseFlagAnalyser->bitwiseOrContainsConstant($args[3]->value, $scope, 'JSON_OBJECT_AS_ARRAY')->yes();
}

private function resolveConstantStringType(ConstantStringType $constantStringType, bool $isForceArray): Type
{
try {
$decodedValue = \Safe\json_decode($constantStringType->getValue(), $isForceArray);
} catch (JsonException) {
return new NeverType();
}

return ConstantTypeHelper::getTypeFromValue($decodedValue);
}
}
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
44 changes: 44 additions & 0 deletions tests/Type/Php/data/json_decode_return.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?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);
};

function(string $json): void {
/** @var '{}'|'null' $json */
$value = \Safe\json_decode($json);
\PHPStan\Testing\assertType('stdClass|null', $value);

$value = \Safe\json_decode($json, true);
\PHPStan\Testing\assertType('array{}|null', $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