swagger-api / swagger-api/swagger-codegen
[PHP] Bug json_encode is casting floats to integers due to missing 'JSON_PRESERVE_ZERO_FRACTION' flag
Nobody has claimed this yet.
- Dominant language
- Mustache
- Stars
- 17.8k
- Forks
- 6k
- PR merge metrics
- No merged PRs in 30d
Description
[PHP] Bug json_encode is casting floats to integers due to missing 'JSON_PRESERVE_ZERO_FRACTION' flag in json_encode __toString methods
Description
When json_encode is called on object which one property is float, it will cast it to integer due to the missing 'JSON_PRESERVE_ZERO_FRACTION' on the json_encode. This leads to denormalization/validation problems when float is expected and integer is received. 'JSON_PRESERVE_ZERO_FRACTION' flag should be added by default to json_encode
Swagger-codegen version
swaggerapi/swagger-codegen-cli-v3:3.0.11
Suggest a fix/enhancement
Since I had multiple problems with my local java and mvn instances I don't know for sure, but I think the file that needs changing is the following:
modules/swagger-codegen/src/main/resources/php/model_generic.mustache
From this:
public function __toString()
{
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
To something like this:
public function __toString()
{
if (defined('JSON_PRESERVE_ZERO_FRACTION') && defined('JSON_PRETTY_PRINT')) { // use JSON preserve zero fraction && JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRESERVE_ZERO_FRACTION|JSON_PRETTY_PRINT
);
}
if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print
return json_encode(
ObjectSerializer::sanitizeForSerialization($this),
JSON_PRETTY_PRINT
);
}
return json_encode(ObjectSerializer::sanitizeForSerialization($this));
}
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with modules/swagger-codegen/src/main/resources/php/model_generic.mustache and inspect the generated PHP model __toString method and its current json_encode flags. Update the template so supported serialization preserves zero-fraction floats while retaining pretty-print behavior; done means generated models no longer turn values such as 1.0 into 1.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- api
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 50/100