Skip to content
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

Return type for json_decode based on second parameter #1874

Closed
luxemate opened this issue Feb 5, 2019 · 4 comments
Closed

Return type for json_decode based on second parameter #1874

luxemate opened this issue Feb 5, 2019 · 4 comments

Comments

@luxemate
Copy link

luxemate commented Feb 5, 2019

Summary of a problem or a feature request

json_decode has second parameter to determine if result is an array or \stdClass. It would be nice to catch cases when there's no assoc: true, and code is trying to access the result of json_decode as an array and vice versa.

Code snippet that reproduces the problem

No error for:

<?php declare(strict_types = 1);

$data = json_decode('{"foo": "bar"}');

$foo = $data['foo'];

https://phpstan.org/r/936624ae-ac3f-4f70-afad-e6480a19a6e6

Expected output

Cannot use object of type stdClass as array

https://3v4l.org/KCXIa

@ondrejmirtes
Copy link
Member

Hi, this isn't practical because the return type of json_decode is marked as mixed, for good reasons. There's no guarantee that the string in the first argument is an object, you can do json_decode('1')., therefore assoc=true does not have any effect: https://3v4l.org/f1Xr0

@luxemate
Copy link
Author

luxemate commented Feb 5, 2019

@ondrejmirtes Yea... I remembered of documentation line

Values true, false and null are returned as TRUE, FALSE and NULL respectively.

after creating the issue.

Return type ends up to be:
For assoc: false the return type is \stdClass|bool|null.
For assoc: true the return type is array|bool|null.

And it's not easy to determine which one will be there without actually running the code.

@ondrejmirtes
Copy link
Member

That's too annoying, because it would complain when passing the result somewhere...

array|bool|null -> array (only arrays accepted, bool|null also present)

@luxemate
Copy link
Author

luxemate commented Feb 5, 2019

I agree. :)

@lock lock bot locked as resolved and limited conversation to collaborators Dec 24, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants