1 | <?php |
||
11 | class FloatEncoder implements Encoder |
||
12 | { |
||
13 | /** The maximum value that can be accurately represented by a float */ |
||
14 | const FLOAT_MAX = 9007199254740992.0; |
||
15 | |||
16 | /** @var array Default values for options in the encoder */ |
||
17 | private static $defaultOptions = [ |
||
18 | 'float.integers' => false, |
||
19 | 'float.precision' => 17, |
||
20 | 'float.export' => false, |
||
21 | ]; |
||
22 | |||
23 | 165 | public function getDefaultOptions() |
|
27 | |||
28 | 135 | public function supports($value) |
|
32 | |||
33 | 36 | public function encode($value, $depth, array $options, callable $encode) |
|
43 | |||
44 | /** |
||
45 | * Encodes the number as a PHP number representation. |
||
46 | * @param float $float The number to encode |
||
47 | * @param array $options The float encoding options |
||
48 | * @param callable $encode Callback used to encode values |
||
49 | * @return string The PHP code representation for the number |
||
50 | */ |
||
51 | 30 | private function encodeNumber($float, array $options, callable $encode) |
|
63 | |||
64 | /** |
||
65 | * Tells if the number can be encoded as an integer. |
||
66 | * @param float $float The number to test |
||
67 | * @param bool|string $allowIntegers Whether integers should be allowed |
||
68 | * @return bool True if the number can be encoded as an integer, false if not |
||
69 | */ |
||
70 | 30 | private function isInteger($float, $allowIntegers) |
|
80 | |||
81 | /** |
||
82 | * Encodes the given float as an integer. |
||
83 | * @param float $float The number to encode |
||
84 | * @param callable $encode Callback used to encode values |
||
85 | * @return string The PHP code representation for the number |
||
86 | */ |
||
87 | 9 | private function encodeInteger($float, callable $encode) |
|
97 | |||
98 | /** |
||
99 | * Determines the float precision based on the options. |
||
100 | * @param array $options The float encoding options |
||
101 | * @return int The precision used to encode floats |
||
102 | */ |
||
103 | 24 | private function determinePrecision($options) |
|
113 | |||
114 | /** |
||
115 | * Encodes the number using a floating point representation. |
||
116 | * @param float $float The number to encode |
||
117 | * @param int $precision The maximum precision of encoded floats |
||
118 | * @return string The PHP code representation for the number |
||
119 | */ |
||
120 | 24 | private function encodeFloat($float, $precision) |
|
134 | |||
135 | /** |
||
136 | * Formats the number as a decimal number. |
||
137 | * @param float $float The number to format |
||
138 | * @param int $digits The maximum number of decimal digits |
||
139 | * @return string The number formatted as a decimal number |
||
140 | */ |
||
141 | 24 | private function formatFloat($float, $digits) |
|
148 | } |
||
149 |