| Total Complexity | 7 |
| Total Lines | 53 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 9 | trait SanitizesNumbers |
||
| 10 | { |
||
| 11 | /** |
||
| 12 | * @param int|string|float|null $number |
||
| 13 | * |
||
| 14 | * @return string |
||
| 15 | */ |
||
| 16 | 137 | protected function sanitize(int|string|float|null $number): string |
|
| 17 | { |
||
| 18 | 137 | if (is_float($number) && ! $this->isPrecise($number)) { |
|
| 19 | 13 | throw new LengthException('Float precision loss detected.'); |
|
| 20 | } |
||
| 21 | |||
| 22 | 124 | $number = str($number)->replace(',', '.'); |
|
| 23 | |||
| 24 | 124 | $dots = $number->substrCount('.'); |
|
| 25 | |||
| 26 | 124 | if ($dots >= 2) { |
|
| 27 | 10 | $number = $number |
|
| 28 | 10 | ->replaceLast('.', ',') |
|
| 29 | 10 | ->replace('.', '') |
|
| 30 | 10 | ->replaceLast(',', '.'); |
|
| 31 | } |
||
| 32 | |||
| 33 | 124 | return $number |
|
| 34 | 124 | ->replaceMatches('/[^0-9.]/', '') |
|
| 35 | 124 | ->toString(); |
|
| 36 | } |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Determine whether the passed floating point number is precise. |
||
| 40 | * |
||
| 41 | * @param float $number |
||
| 42 | * |
||
| 43 | * @return bool |
||
| 44 | */ |
||
| 45 | 59 | protected function isPrecise(float $number): bool |
|
| 62 | } |
||
| 63 | } |
||
| 64 |