phpstan-nette icon indicating copy to clipboard operation
phpstan-nette copied to clipboard

[Types] Add JsonDecodeDynamicReturnTypeExtension

Open TomasVotruba opened this issue 3 years ago • 7 comments

By default, the Nette\Utils\Json::decode() returns mixed, but in some cases we know there is more specific type.

We use this extension internally in private project to separate at array and stdClass, e.g.:

$values = Nette\Utils\Json::decode($values);
echo $values['item'];
// not possible - a stdClass type given

$values = Nette\Utils\Json::decode($values, Nette\Utils\Json::FORCE_ARRAY);
echo $values->item ;
// not possible - an array type given

It might be useful to have in Nette extension itself. What do you think?

cc @staabm @lulco @matthiasnoback

Based on https://twitter.com/VotrubaT/status/1487434178757074952

TomasVotruba avatar Jan 30 '22 09:01 TomasVotruba

I actually tried to add function extension first but PHPStan analysed only non-basic function. Not sure why.

Apart that, is the type resolution in tests here correct?

TomasVotruba avatar Jan 30 '22 11:01 TomasVotruba

Instead of the whole resolveConstantStringType method you just should call this class https://github.com/phpstan/phpstan-src/blob/master/src/Type/ConstantTypeHelper.php, otherwise it looks fine.

ondrejmirtes avatar Jan 30 '22 11:01 ondrejmirtes

Just to reiterate - I still want this to be submitted as a json_decode extension to phpstan-src first. Then we can continue here, keep all the tests but make the extension implementation much simpler, delegating to json_decode logic.

ondrejmirtes avatar Jan 30 '22 14:01 ondrejmirtes

@ondrejmirtes I understand that, I just want to make it work and confirm here, so we don't jump back and forth. Then function extension port to core and update here.

TomasVotruba avatar Jan 30 '22 16:01 TomasVotruba

@ondrejmirtes As for json_decode, is FunctionTypeSpecifyingExtension the right interface to implement?

TomasVotruba avatar Jan 30 '22 21:01 TomasVotruba

No (https://phpstan.org/developing-extensions/dynamic-return-type-extensions):

functions using DynamicFunctionReturnTypeExtension interface and phpstan.broker.dynamicFunctionReturnTypeExtension service tag.

ondrejmirtes avatar Jan 30 '22 21:01 ondrejmirtes

@ondrejmirtes Thanks :+1:

I'm trying to add JsonDecodeDynamicReturnTypeExtension, but the only function that is found is PHPStan\Testing\assertType. The json_decode is never passed.

What I'm doing wrong there?

TomasVotruba avatar Jan 31 '22 10:01 TomasVotruba