Passed
Push — master ( 25c805...999286 )
by Andy
02:56 queued 11s
created

BooleanNormalizer::setPairs()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Palmtree\Csv\Normalizer;
4
5
/**
6
 * BooleanNormalizer formats a CSV cell as a boolean.
7
 */
8
class BooleanNormalizer extends AbstractNormalizer
9
{
10
    /**
11
     * @var array Default truthy/falsey pairs.
12
     */
13
    public static $defaultPairs = [
14
        'true'    => 'false',
15
        '1'       => '0',
16
        'on'      => 'off',
17
        'yes'     => 'no',
18
        'enabled' => 'disabled',
19
    ];
20
21
    /** @var array */
22
    private $values = [];
23
    /** @var bool */
24
    private $nullable = false;
25
    /** @var bool */
26
    private $caseSensitive = false;
27
28 3
    public function __construct(NormalizerInterface $normalizer = null)
29
    {
30 3
        $this->setPairs(self::$defaultPairs);
31
32 3
        parent::__construct($normalizer);
33 3
    }
34
35 3
    public function setPairs(array $pairs): self
36
    {
37 3
        $this->values = [];
38
39 3
        foreach ($pairs as $truthy => $falsey) {
40 3
            $this->addPair($truthy, $falsey);
41
        }
42
43 3
        return $this;
44
    }
45
46 3
    public function addPair(string $truthy, string $falsey): void
47
    {
48 3
        if (!$this->caseSensitive) {
49 3
            $truthy = \strtolower($truthy);
50 3
            $falsey = \strtolower($falsey);
51
        }
52
53 3
        $this->values[$truthy] = true;
54 3
        $this->values[$falsey] = false;
55 3
    }
56
57
    public function getValues(): array
58
    {
59
        return $this->values;
60
    }
61
62
    /**
63
     * @return bool|null
64
     */
65 3
    protected function getNormalizedValue(string $value)
66
    {
67 3
        $value = \trim($value);
68
69 3
        if (!$this->caseSensitive) {
70 3
            $value = \strtolower($value);
71
        }
72
73 3
        if (isset($this->values[$value])) {
74 3
            return $this->values[$value];
75
        }
76
77 2
        return $this->isNullable() ? null : false;
78
    }
79
80
    public function setCaseSensitive(bool $caseSensitive): self
81
    {
82
        $this->caseSensitive = $caseSensitive;
83
84
        return $this;
85
    }
86
87
    public function isCaseSensitive(): bool
88
    {
89
        return $this->caseSensitive;
90
    }
91
92 1
    public function setNullable(bool $nullable): self
93
    {
94 1
        $this->nullable = $nullable;
95
96 1
        return $this;
97
    }
98
99 2
    public function isNullable(): bool
100
    {
101 2
        return $this->nullable;
102
    }
103
}
104