Passed
Push — master ( 201e0e...28aced )
by Andy
01:40
created

NumberNormalizer   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 38
Duplicated Lines 0 %

Test Coverage

Coverage 78.56%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 13
c 1
b 0
f 0
dl 0
loc 38
ccs 11
cts 14
cp 0.7856
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getNormalizedValue() 0 16 3
A getDecimals() 0 3 1
A setDecimals() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Palmtree\Csv\Normalizer;
6
7
/**
8
 * NumberNormalizer converts numeric strings to integers and floats.
9
 */
10
class NumberNormalizer extends AbstractNormalizer
11
{
12
    private ?int $decimals = null;
13
14
    /**
15
     * Sets the amount of decimal places to round to. Defaults to null which performs no rounding.
16
     */
17 1
    public function setDecimals(?int $decimals = null): self
18
    {
19 1
        $this->decimals = $decimals;
20
21 1
        return $this;
22
    }
23
24
    public function getDecimals(): ?int
25
    {
26
        return $this->decimals;
27
    }
28
29
    /**
30
     * @return float|int
31
     */
32 6
    protected function getNormalizedValue(string $value)
33
    {
34 6
        if (!is_numeric($value)) {
35
            return 0;
36
        }
37
38 6
        $value = trim($value);
39 6
        $value = ltrim($value, '0');
40
41 6
        $numberValue = json_decode($value);
42
43 6
        if ($this->decimals !== null) {
44 1
            $numberValue = round($numberValue, $this->decimals);
45
        }
46
47 6
        return $numberValue;
48
    }
49
}
50