Skip to content

Commit

Permalink
bug #54146 [HttpClient] Preserve float in JsonMockResponse (Jibbarth)
Browse files Browse the repository at this point in the history
This PR was merged into the 6.4 branch.

Discussion
----------

[HttpClient] Preserve float in JsonMockResponse

| Q             | A
| ------------- | ---
| Branch?       | 6.4
| Bug fix?      | yes
| New feature?  | no <!-- please update src/**/CHANGELOG.md files -->
| Deprecations? | no <!-- please update UPGRADE-*.md and src/**/CHANGELOG.md files -->
| Issues        | Fix #... <!-- prefix each issue number with "Fix #", no need to create an issue if none exists, explain below instead -->
| License       | MIT

Hello,

I am mocking an API Response that can send float in values :

```
{
    "values": 1.0
}
```

Converting this to a php array and giving it to JsonMockResponse return me an int after, because the missing json_encode flag to keep zero fraction, and leds to issue when I want to deserialize it into a float property.

In my mind it's a bugfix, but if it's considered as a new feature, I can target 7.1.

Commits
-------

4d120b8 [HttpClient] Preserve float in JsonMockResponse
  • Loading branch information
derrabus committed Mar 5, 2024
2 parents f5b5e14 + 4d120b8 commit 0523300
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
Expand Up @@ -21,7 +21,7 @@ class JsonMockResponse extends MockResponse
public function __construct(mixed $body = [], array $info = [])
{
try {
$json = json_encode($body, \JSON_THROW_ON_ERROR);
$json = json_encode($body, \JSON_THROW_ON_ERROR | \JSON_PRESERVE_ZERO_FRACTION);
} catch (\JsonException $e) {
throw new InvalidArgumentException('JSON encoding failed: '.$e->getMessage(), $e->getCode(), $e);
}
Expand Down
Expand Up @@ -59,6 +59,22 @@ public function testJsonEncodeString()
$this->assertSame('application/json', $response->getHeaders()['content-type'][0]);
}

public function testJsonEncodeFloat()
{
$client = new MockHttpClient(new JsonMockResponse([
'foo' => 1.23,
'ccc' => 1.0,
'baz' => 10.,
]));
$response = $client->request('GET', 'https://symfony.com');

$this->assertSame([
'foo' => 1.23,
'ccc' => 1.,
'baz' => 10.,
], $response->toArray());
}

/**
* @dataProvider responseHeadersProvider
*/
Expand Down

0 comments on commit 0523300

Please sign in to comment.