NormalizeNumber::filterSingle()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 23

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 23
ccs 10
cts 10
cp 1
rs 9.552
c 0
b 0
f 0
cc 3
nc 2
nop 2
crap 3
1
<?php
2
declare(strict_types=1);
3
namespace Sirius\Filtration\Filter;
4
5
class NormalizeNumber extends AbstractFilter
6
{
7
    const OPTION_THOUSANDS_SEPARATOR = 'thousands_separator';
8
9
    const OPTION_DECIMAL_POINT = 'decimal_point';
10
11
    const VALUE_POINT = '.';
12
13
    const VALUE_COMMA = ',';
14
15
    protected $options = [
16
        self::OPTION_THOUSANDS_SEPARATOR => self::VALUE_POINT,
17
        self::OPTION_DECIMAL_POINT => self::VALUE_COMMA
18
    ];
19
20 2
    public function filterSingle($value, string $valueIdentifier = null)
21
    {
22 2
        $value = (string) $value;
23
        // number is already normalized
24 2
        $floatedValue =\floatval($value);
25
        
26
        // check for the string length because:
27
        // 1. floatval('12.456,67') returns 12.456 and
28
        // 2. PHP returns true for '12.456,67' == 12.456
29 2
        if ($floatedValue == $value && strlen((string) $floatedValue) == strlen($value)) {
30 1
            return $floatedValue;
31
        }
32
        
33
        // attempt to normalize it:
34
        // remove spaces and thousands separator
35
        // replace local decimal point with .
36 1
        $value = strtr($value, array(
37 1
            ' ' => '',
38 1
            $this->options[self::OPTION_THOUSANDS_SEPARATOR] => '',
39 1
            $this->options[self::OPTION_DECIMAL_POINT] => '.'
40
        ));
41 1
        return\floatval($value);
42
    }
43
}
44