Skip to content

Commit

Permalink
Merge pull request #41 from systopia/JsonConverter_do-not-convert-flo…
Browse files Browse the repository at this point in the history
…at-to-int

JsonConverter: Do not convert floats with zero fraction to ints
  • Loading branch information
dontub authored Jul 2, 2024
2 parents 2a32ec5 + 9c2b832 commit 55b26f9
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
4 changes: 2 additions & 2 deletions Civi/RemoteTools/Util/JsonConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ final class JsonConverter {
* @throws \JsonException
*/
public static function toArray(\stdClass $data): array {
$result = \json_decode(\json_encode($data, JSON_THROW_ON_ERROR), TRUE);
$result = \json_decode(\json_encode($data, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION), TRUE);
Assert::isArray($result);

return $result;
Expand All @@ -45,7 +45,7 @@ public static function toStdClass(array $data): \stdClass {
return new \stdClass();
}

$result = \json_decode(\json_encode($data, JSON_THROW_ON_ERROR));
$result = \json_decode(\json_encode($data, JSON_THROW_ON_ERROR | JSON_PRESERVE_ZERO_FRACTION));
Assert::isInstanceOf($result, \stdClass::class);

return $result;
Expand Down
6 changes: 4 additions & 2 deletions tests/phpunit/Civi/RemoteTools/Util/JsonConverterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,17 @@ final class JsonConverterTest extends TestCase {
public function testToArray(): void {
$object = new \stdClass();
$object->foo = 'bar';
$object->bar = 2.0;

static::assertSame(['foo' => 'bar'], JsonConverter::toArray($object));
static::assertSame(['foo' => 'bar', 'bar' => 2.0], JsonConverter::toArray($object));
}

public function testToStdClass(): void {
$array = ['foo' => 'bar'];
$array = ['foo' => 'bar', 'bar' => 2.0];
$object = JsonConverter::toStdClass($array);

static::assertSame('bar', $object->foo);
static::assertSame(2.0, $object->bar);
}

public function testToStdClassEmptyArray(): void {
Expand Down

0 comments on commit 55b26f9

Please sign in to comment.