Passed
Push — master ( 24f0b7...5fac61 )
by Andy
01:44
created

BooleanNormalizer::nullable()   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
c 0
b 0
f 0
dl 0
loc 5
ccs 3
cts 3
cp 1
rs 10
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
 * BooleanNormalizer converts a string to boolean true or false, or null.
9
 */
10
class BooleanNormalizer extends AbstractNormalizer
11
{
12
    /**
13
     * @var array Default truthy/falsey pairs.
14
     */
15
    public static array $defaultPairs = [
16
        'true' => 'false',
17
        '1' => '0',
18
        'on' => 'off',
19
        'yes' => 'no',
20
        'enabled' => 'disabled',
21
    ];
22
23
    private array $values = [];
24
    private bool $nullable = false;
25
    private bool $caseSensitive = false;
26
27 3
    public function __construct(?NormalizerInterface $normalizer = null)
28
    {
29 3
        $this->pairs(self::$defaultPairs);
30
31 3
        parent::__construct($normalizer);
32 3
    }
33
34 3
    public function pairs(array $pairs): self
35
    {
36 3
        $this->values = [];
37
38 3
        foreach ($pairs as $truthy => $falsey) {
39 3
            $this->addPair((string)$truthy, $falsey);
40
        }
41
42 3
        return $this;
43
    }
44
45 3
    public function addPair(string $truthy, string $falsey): void
46
    {
47 3
        if (!$this->caseSensitive) {
48 3
            $truthy = strtolower($truthy);
49 3
            $falsey = strtolower($falsey);
50
        }
51
52 3
        $this->values[$truthy] = true;
53 3
        $this->values[$falsey] = false;
54 3
    }
55
56 3
    protected function getNormalizedValue(string $value): ?bool
57
    {
58 3
        $value = trim($value);
59
60 3
        if (!$this->caseSensitive) {
61 3
            $value = strtolower($value);
62
        }
63
64 3
        if (isset($this->values[$value])) {
65 3
            return $this->values[$value];
66
        }
67
68 2
        return $this->nullable ? null : false;
69
    }
70
71
    /**
72
     * Sets whether a case-sensitive comparison should be made. If this is true, 'Enabled' will not match 'enabled'
73
     * and will return false if it is found (or null if isNullable is true). Defaults to false.
74
     */
75
    public function caseSensitive(bool $caseSensitive): self
76
    {
77
        $this->caseSensitive = $caseSensitive;
78
79
        return $this;
80
    }
81
82
    /**
83
     * Sets whether the returned value can be null. Defaults to false, meaning any value present that is
84
     * not found in the truthy values will return false.
85
     */
86 1
    public function nullable(bool $nullable): self
87
    {
88 1
        $this->nullable = $nullable;
89
90 1
        return $this;
91
    }
92
}
93