NormalizeNumber   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 3
lcom 1
cbo 1
dl 0
loc 39
ccs 10
cts 10
cp 1
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
A filterSingle() 0 23 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