tebru / gson-php

Gson implemented in PHP
Other
151 stars 18 forks source link

Integer-keyed Generics Don't Throw Exception on String Key #2

Closed mattjanssen closed 7 years ago

mattjanssen commented 7 years ago

If I have the follow type declaration @Gson\Type("array<int, string>") and I read the following JSON {"foo": "bar"} the JsonDecodeReader converts the "foo" into null because "foo" doesn't get wrapped in quotes before it's passed to json_decode(). This then causes the IntegerTypeAdapter to not throw an exception, because null is a valid value.

The expected behavior would be to throw an UnexpectedJsonTokenException.

This is happening because the ArrayTypeAdapter only checks if $keyType->isString() when deciding if it should wrap the key name in quotes.

A solution would be to also check if !is_numeric($name) when deciding to wrap it in quotes. As booleans and null aren't valid keys in PHP or JSON, we don't need extra checks for those.

natebrunette commented 7 years ago

This was resolved by checking for errors on json_decode and throwing a parse exception if an error is encountered.