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

NumberNormalizer::setDecimals()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 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