Skip to content

Commit 1736892

Browse files
committed
replace instanceof checks in JsonThrowOnErrorDynamicReturnTypeExtension
1 parent 1f150cc commit 1736892

File tree

2 files changed

+19
-4
lines changed

2 files changed

+19
-4
lines changed

src/Type/Php/JsonThrowOnErrorDynamicReturnTypeExtension.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,12 @@
1212
use PHPStan\Type\BitwiseFlagHelper;
1313
use PHPStan\Type\Constant\ConstantBooleanType;
1414
use PHPStan\Type\Constant\ConstantStringType;
15-
use PHPStan\Type\ConstantScalarType;
1615
use PHPStan\Type\ConstantTypeHelper;
1716
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
1817
use PHPStan\Type\ObjectWithoutClassType;
1918
use PHPStan\Type\Type;
2019
use PHPStan\Type\TypeCombinator;
20+
use function count;
2121
use function is_bool;
2222
use function json_decode;
2323

@@ -87,8 +87,14 @@ private function narrowTypeForJsonDecode(FuncCall $funcCall, Scope $scope, Type
8787
}
8888

8989
$firstValueType = $scope->getType($args[0]->value);
90-
if ($firstValueType instanceof ConstantStringType) {
91-
return $this->resolveConstantStringType($firstValueType, $isForceArray);
90+
if ($firstValueType->getConstantStrings() !== []) {
91+
$types = [];
92+
93+
foreach ($firstValueType->getConstantStrings() as $constantString) {
94+
$types[] = $this->resolveConstantStringType($constantString, $isForceArray);
95+
}
96+
97+
return TypeCombinator::union(...$types);
9298
}
9399

94100
if ($isForceArray) {
@@ -109,7 +115,7 @@ private function isForceArray(FuncCall $funcCall, Scope $scope): bool
109115
}
110116

111117
$secondArgType = $scope->getType($args[1]->value);
112-
$secondArgValue = $secondArgType instanceof ConstantScalarType ? $secondArgType->getValue() : null;
118+
$secondArgValue = count($secondArgType->getConstantScalarValues()) === 1 ? $secondArgType->getConstantScalarValues()[0] : null;
113119

114120
if (is_bool($secondArgValue)) {
115121
return $secondArgValue;

tests/PHPStan/Analyser/nsrt/json-decode/narrow_type.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,3 +32,12 @@ function ($mixed) {
3232
$value = json_decode($mixed, false);
3333
assertType('mixed', $value);
3434
};
35+
36+
function(string $json): void {
37+
/** @var '{}'|'null' $json */
38+
$value = json_decode($json);
39+
assertType('stdClass|null', $value);
40+
41+
$value = json_decode($json, true);
42+
assertType('array{}|null', $value);
43+
};

0 commit comments

Comments
 (0)