Skip to content

Commit 0b79b59

Browse files
committed
Delegate integer encoding
1 parent 9920b50 commit 0b79b59

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/Encoder/FloatEncoder.php

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -37,19 +37,20 @@ public function encode($value, $depth, array $options, callable $encode)
3737
return $value < 0 ? '-INF' : 'INF';
3838
}
3939

40-
return $this->encodeNumber($value, $options);
40+
return $this->encodeNumber($value, $options, $encode);
4141
}
4242

4343
/**
4444
* Encodes the number as a PHP number representation.
4545
* @param float $float The number to encode
4646
* @param array $options The float encoding options
47+
* @param callable $encode Callback used to encode values
4748
* @return string The PHP code representation for the number
4849
*/
49-
private function encodeNumber($float, array $options)
50+
private function encodeNumber($float, array $options, callable $encode)
5051
{
5152
if ($this->isInteger($float, $options['float.integers'])) {
52-
return number_format($float, 0, '.', '');
53+
return $this->encodeInteger($float, $encode);
5354
} elseif ($float === 0.0) {
5455
return '0.0';
5556
}
@@ -80,6 +81,23 @@ private function isInteger($float, $allowIntegers)
8081
return $allowIntegers === 'all';
8182
}
8283

84+
/**
85+
* Encodes the given float as an integer.
86+
* @param float $float The number to encode
87+
* @param callable $encode Callback used to encode values
88+
* @return string The PHP code representation for the number
89+
*/
90+
private function encodeInteger($float, callable $encode)
91+
{
92+
$minimum = defined('PHP_INT_MIN') ? PHP_INT_MIN : ~PHP_INT_MAX;
93+
94+
if ($float >= $minimum && $float <= PHP_INT_MAX) {
95+
return $encode((int) $float);
96+
}
97+
98+
return number_format($float, 0, '.', '');
99+
}
100+
83101
/**
84102
* Encodes the number using a floating point representation.
85103
* @param float $float The number to encode

tests/tests/EncodingTest.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ public function testFloatIntegers()
135135
$this->assertEncode('-1', -1, $encoder, -1.0);
136136
$this->assertEncode('1337', 1337, $encoder, 1337.0);
137137
$this->assertEncode('-1337', -1337, $encoder, -1337.0);
138+
$this->assertEncode('2000000000', 2000000000, $encoder, 2000000000.0);
138139
}
139140

140141
public function testMaximumFloatIntegers()

0 commit comments

Comments
 (0)