Skip to content

[Types] Add JsonDecodeDynamicReturnTypeExtension #89

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 9 commits into
base: 1.1.x
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
5 changes: 5 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,11 @@ jobs:
if: matrix.php-version == '7.1' || matrix.php-version == '7.2' || matrix.php-version == '7.3'
run: "composer require --dev phpunit/phpunit:^7.5.20 --update-with-dependencies"

# in PHP 7.1, the json_decode() 2nd parameter requires bool, while PHP 7.2 it's null|int
- name: "Downgrade nette/utils"
if: matrix.php-version == '7.1'
run: "composer require --dev nette/utils:^2.3 nette/forms:^2.4 --update-with-dependencies"

- name: "Tests"
run: "make tests"

Expand Down
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
"phpstan/phpstan-php-parser": "^1.1",
"phpstan/phpstan-phpunit": "^1.0",
"phpstan/phpstan-strict-rules": "^1.0",
"phpunit/phpunit": "^9.5"
"phpunit/phpunit": "^9.5",
"tracy/tracy": "^2.9"
},
"config": {
"platform": {
Expand All @@ -50,6 +51,9 @@
}
},
"autoload-dev": {
"psr-4": {
"PHPStan\\": "tests/"
},
"classmap": [
"tests/"
]
Expand Down
124 changes: 124 additions & 0 deletions src/Type/Nette/NetteUtilsJsonDecodeDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Nette;

use Nette\Utils\Json;
use PhpParser\Node\Arg;
use PhpParser\Node\Expr\ClassConstFetch;
use PhpParser\Node\Expr\StaticCall;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ConstantTypeHelper;
use PHPStan\Type\DynamicStaticMethodReturnTypeExtension;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
use stdClass;

final class NetteUtilsJsonDecodeDynamicReturnTypeExtension implements DynamicStaticMethodReturnTypeExtension
{

public function getClass(): string
{
return 'Nette\Utils\Json';
}

public function isStaticMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'decode';
}

public function getTypeFromStaticMethodCall(MethodReflection $methodReflection, StaticCall $methodCall, Scope $scope): Type
{
$args = $methodCall->getArgs();

$isForceArray = $this->isForceArray($args);

$firstArgValue = $args[0]->value;
$firstValueType = $scope->getType($firstArgValue);

if ($firstValueType instanceof ConstantStringType) {
$resolvedType = $this->resolveConstantStringType($firstValueType, $isForceArray);
} else {
$resolvedType = new MixedType();
}

if (! $resolvedType instanceof MixedType) {
return $resolvedType;
}

// fallback type
if ($isForceArray) {
return new UnionType([
new ArrayType(new MixedType(), new MixedType()),
new StringType(),
new FloatType(),
new IntegerType(),
new BooleanType(),
]);
}

// scalar types with stdClass
return new UnionType([
new ObjectType(stdClass::class),
new StringType(),
new FloatType(),
new IntegerType(),
new BooleanType(),
]);
}

/**
* @param Arg[] $args
*/
private function isForceArray(array $args): bool
{
if (!isset($args[1])) {
return false;
}

$secondArg = $args[1];

// is second arg force array?
if ($secondArg->value instanceof ClassConstFetch) {
$classConstFetch = $secondArg->value;

if ($classConstFetch->class instanceof Name) {
if (! $classConstFetch->name instanceof Identifier) {
return false;
}

if ($classConstFetch->class->toString() !== 'Nette\Utils\Json') {
return false;
}

if ($classConstFetch->name->toString() === 'FORCE_ARRAY') {
return true;
}
}
}

return false;
}

private function resolveConstantStringType(ConstantStringType $constantStringType, bool $isForceArray): Type
{
if ($isForceArray) {
$decodedValue = Json::decode($constantStringType->getValue(), Json::FORCE_ARRAY);
} else {
$decodedValue = Json::decode($constantStringType->getValue());
}

return ConstantTypeHelper::getTypeFromValue($decodedValue);
}

}
86 changes: 86 additions & 0 deletions src/Type/Php/JsonDecodeDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Php;

use Nette\Utils\Json;
use PhpParser\Node\Expr\FuncCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\FunctionReflection;
use PHPStan\Type\ArrayType;
use PHPStan\Type\BooleanType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\ConstantTypeHelper;
use PHPStan\Type\DynamicFunctionReturnTypeExtension;
use PHPStan\Type\FloatType;
use PHPStan\Type\IntegerType;
use PHPStan\Type\MixedType;
use PHPStan\Type\ObjectType;
use PHPStan\Type\StringType;
use PHPStan\Type\Type;
use PHPStan\Type\UnionType;
use stdClass;

final class JsonDecodeDynamicReturnTypeExtension implements DynamicFunctionReturnTypeExtension
{
public function isFunctionSupported(FunctionReflection $functionReflection): bool
{
// @todo - finds only "assertType", but not "json_decode" :/
dump($functionReflection->getName());

return $functionReflection->getName() === 'json_decode';
}
Comment on lines +25 to +31
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here the json_decode is never passed :/

Copy link
Contributor Author

@TomasVotruba TomasVotruba Jan 31, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To reproduce localy, run PHPUnit:

vendor/bin/phpunit tests/Type/Php/JsonDecodeDynamicReturnTypeExtensionTest.php

image

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Because there's already JsonThrowOnErrorDynamicReturnTypeExtension in phpstan-src whcih changes the result based on JSON_THROW_ON_ERROR. You need to modify it first.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll try it


public function getTypeFromFunctionCall(FunctionReflection $functionReflection, FuncCall $funcCall, Scope $scope): Type
{
$args = $funcCall->getArgs();

dump('___');
die;

$isForceArray = $this->isForceArray($funcCall);

$firstArgValue = $args[0]->value;
$firstValueType = $scope->getType($firstArgValue);

if ($firstValueType instanceof ConstantStringType) {
$resolvedType = $this->resolveConstantStringType($firstValueType, $isForceArray);
} else {
$resolvedType = new MixedType();
}

if (! $resolvedType instanceof MixedType) {
return $resolvedType;
}

// fallback type
if ($isForceArray) {
return new UnionType([
new ArrayType(new MixedType(), new MixedType()),
new StringType(),
new FloatType(),
new IntegerType(),
new BooleanType(),
]);
}

// scalar types with stdClass
return new UnionType([
new ObjectType(stdClass::class),
new StringType(),
new FloatType(),
new IntegerType(),
new BooleanType(),
]);
}

private function resolveConstantStringType(ConstantStringType $constantStringType, bool $isForceArray): Type
{
if ($isForceArray) {
$decodedValue = Json::decode($constantStringType->getValue(), Json::FORCE_ARRAY);
} else {
$decodedValue = Json::decode($constantStringType->getValue());
}

return ConstantTypeHelper::getTypeFromValue($decodedValue);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\Nette;

use PHPStan\Testing\TypeInferenceTestCase;

final class NetteUtilsJsonDecodeDynamicReturnTypeExtensionTest extends TypeInferenceTestCase
{

/**
* @return iterable<mixed>
*/
public function dataAsserts(): iterable
{
yield from $this->gatherAssertTypes(__DIR__ . '/data/json_decode.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/json_decode_force_array.php');

yield from $this->gatherAssertTypes(__DIR__ . '/data/json_decode_unknown_type.php');
yield from $this->gatherAssertTypes(__DIR__ . '/data/json_decode_force_array_unknown_type.php');
}

/**
* @dataProvider dataAsserts()
* @param string $assertType
* @param string $file
* @param mixed ...$args
*/
public function testAsserts(string $assertType, string $file, ...$args): void
{
$this->assertFileAsserts($assertType, $file, ...$args);
}

/**
* @return string[]
*/
public static function getAdditionalConfigFiles(): array
{
return [__DIR__ . '/config/nette_json_decode_extension.neon'];
}

}
5 changes: 5 additions & 0 deletions tests/Type/Nette/config/nette_json_decode_extension.neon
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
services:
-
class: PHPStan\Type\Nette\NetteUtilsJsonDecodeDynamicReturnTypeExtension
tags:
- phpstan.broker.dynamicStaticMethodReturnTypeExtension
22 changes: 22 additions & 0 deletions tests/Type/Nette/data/json_decode.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

use Nette\Utils\Json;
use function PHPStan\Testing\assertType;

$value = Json::decode('true');
assertType('true', $value);

$value = Json::decode('1');
assertType('1', $value);

$value = Json::decode('1.5');
assertType('1.5', $value);

$value = Json::decode('false');
assertType('false', $value);

$value = Json::decode('{}');
assertType('stdClass', $value);

$value = Json::decode('[1, 2, 3]');
assertType('array{1, 2, 3}', $value);
22 changes: 22 additions & 0 deletions tests/Type/Nette/data/json_decode_force_array.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

use Nette\Utils\Json;
use function PHPStan\Testing\assertType;

$value = Json::decode('true', Json::FORCE_ARRAY);
assertType('true', $value);

$value = Json::decode('1', Json::FORCE_ARRAY);
assertType('1', $value);

$value = Json::decode('1.5', Json::FORCE_ARRAY);
assertType('1.5', $value);

$value = Json::decode('false', Json::FORCE_ARRAY);
assertType('false', $value);

$value = Json::decode('{}', Json::FORCE_ARRAY);
assertType('array{}', $value);

$value = Json::decode('[1, 2, 3]', Json::FORCE_ARRAY);
assertType('array{1, 2, 3}', $value);
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

use Nette\Utils\Json;
use function PHPStan\Testing\assertType;

function unknownType($mixed) {
$value = Json::decode($mixed, Json::FORCE_ARRAY);
assertType('array|bool|float|int|string', $value);
}
9 changes: 9 additions & 0 deletions tests/Type/Nette/data/json_decode_unknown_type.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

use Nette\Utils\Json;
use function PHPStan\Testing\assertType;

function unknownType($mixed) {
$value = Json::decode($mixed);
assertType('bool|float|int|stdClass|string', $value);
}
Loading