Skip to content

Commit

Permalink
json_decode with force array flag: subtract all objects, not just std…
Browse files Browse the repository at this point in the history
…Class
  • Loading branch information
rajyan committed May 8, 2024
1 parent 149a1e7 commit 4e5020d
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 11 deletions.
13 changes: 6 additions & 7 deletions src/Type/Php/JsonThrowOnErrorDynamicReturnTypeExtension.php
Expand Up @@ -14,10 +14,9 @@
use PHPStan\Type\ConstantScalarType;
use PHPStan\Type\ConstantTypeHelper;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\ObjectWithoutClassType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use stdClass;
use function is_bool;
use function json_decode;

Expand Down Expand Up @@ -76,18 +75,18 @@ public function getTypeFromFunctionCall(
private function narrowTypeForJsonDecode(FuncCall $funcCall, Scope $scope, Type $fallbackType): Type
{
$args = $funcCall->getArgs();
$isArrayWithoutStdClass = $this->isForceArrayWithoutStdClass($funcCall, $scope);
$isForceArray = $this->isForceArray($funcCall, $scope);
if (!isset($args[0])) {
return $fallbackType;
}

$firstValueType = $scope->getType($args[0]->value);
if ($firstValueType instanceof ConstantStringType) {
return $this->resolveConstantStringType($firstValueType, $isArrayWithoutStdClass);
return $this->resolveConstantStringType($firstValueType, $isForceArray);
}

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

return $fallbackType;
Expand All @@ -96,7 +95,7 @@ private function narrowTypeForJsonDecode(FuncCall $funcCall, Scope $scope, Type
/**
* Is "json_decode(..., true)"?
*/
private function isForceArrayWithoutStdClass(FuncCall $funcCall, Scope $scope): bool
private function isForceArray(FuncCall $funcCall, Scope $scope): bool
{
$args = $funcCall->getArgs();
if (!isset($args[1])) {
Expand Down
Expand Up @@ -7,19 +7,19 @@
// @see https://3v4l.org/YFlHF
function ($mixed) {
$value = json_decode($mixed, null, 512, JSON_OBJECT_AS_ARRAY);
assertType('mixed~stdClass', $value);
assertType('mixed~object', $value);
};

function ($mixed) {
$flagsAsVariable = JSON_OBJECT_AS_ARRAY;

$value = json_decode($mixed, null, 512, $flagsAsVariable);
assertType('mixed~stdClass', $value);
assertType('mixed~object', $value);
};

function ($mixed) {
$value = json_decode($mixed, null, 512, JSON_OBJECT_AS_ARRAY | JSON_BIGINT_AS_STRING);
assertType('mixed~stdClass', $value);
assertType('mixed~object', $value);
};

function ($mixed) {
Expand Down
Expand Up @@ -24,5 +24,5 @@

function ($mixed) {
$value = json_decode($mixed, true);
assertType('mixed~stdClass', $value);
assertType('mixed~object', $value);
};

0 comments on commit 4e5020d

Please sign in to comment.