Passed
Pull Request — main (#34)
by
unknown
03:37
created

SanitizesNumbers::isGoodFloat()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 7
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 4
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\ValueObjects\Concerns;
6
7
use LengthException;
8
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->isGoodFloat($number)) {
19 13
            throw new LengthException();
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
        return $number
34 124
            ->replaceMatches('/[^0-9.]/', '')
35 124
            ->toString();
36
    }
37
38
    /**
39
     * @param  int|string|float|null  $number
40
     * @return bool
41
     */
42 58
    private function isGoodFloat(int|string|float|null $number): bool
43
    {
44 58
        if (is_float($number)) {
45 58
            $string_number = str($number);
46
47 58
            $precision_position = str($string_number->explode('.')->get(1, ''))->length();
48
49 58
            $round_number = round($number, $precision_position);
50
51 58
            if (($round_number == $number && $string_number->length() <= PHP_FLOAT_DIG)) {
52 45
                return true;
53
            }
54
        }
55
56 13
        return false;
57
    }
58
}
59