Test Failed
Pull Request — main (#34)
by
unknown
03:38
created

SanitizesNumbers   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 52
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 12
Bugs 1 Features 0
Metric Value
eloc 22
c 12
b 1
f 0
dl 0
loc 52
ccs 10
cts 10
cp 1
rs 10
wmc 8

2 Methods

Rating   Name   Duplication   Size   Complexity  
A sanitize() 0 20 4
A is_good_float() 0 19 4
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 80
     * @return string
15
     */
16 80
    protected function sanitize(int|string|float|null $number): string
17
    {
18 80
        if (is_float($number) && ! $this->is_good_float($number)) {
19
            throw new LengthException();
20 80
        }
21 10
22 10
        $number = str((string) $number)->replace(',', '.');
23 10
24 10
        $dots = $number->substrCount('.');
25
26
        if ($dots >= 2) {
27
            $number = $number
28 80
                ->replaceLast('.', ',')
29 80
                ->replace('.', '')
30
                ->replaceLast(',', '.');
31
        }
32
33
        return $number
34
            ->replaceMatches('/[^0-9.]/', '')
35
            ->toString();
36
    }
37
38
    /**
39
     * @param  int|string|float|null  $number
40
     * @return bool
41
     */
42
    private function is_good_float(int|string|float|null $number): bool
43
    {
44
        if (is_float($number)) {
45
            $separate = str($number)->explode('.')->sep;
46
47
            $precision_position = str($separate->get(1, ''))->length();
48
49
            $round_number = round($number, $precision_position);
50
51
            $sum_digits = $separate->sum(function ($item) {
52
                return str($item)->length();
53
            });
54
55
            if (($round_number == $number && $sum_digits <= PHP_FLOAT_DIG - 1)) {
56
                return true;
57
            }
58
        }
59
60
        return false;
61
    }
62
}
63