Passed
Branch master (9671df)
by Andy
02:10
created

BooleanFormatter::removeBinary()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 0
cp 0
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Palmtree\Csv\Formatter;
4
5
/**
6
 * BooleanFormatter formats a CSV cell as a boolean
7
 */
8
class BooleanFormatter extends AbstractFormatter
9
{
10
    protected $nullable = false;
11
12
    protected $binaries = [
13
        '1'       => '0',
14
        'true'    => 'false',
15
        'on'      => 'off',
16
        'yes'     => 'no',
17
        'enabled' => 'disabled',
18
    ];
19
20
    /**
21
     * BooleanFormatter constructor.
22
     *
23
     * @param null|FormatterInterface $formatter
24
     * @param bool                    $nullable
25
     * @param array|null              $binaries
26
     */
27 3
    public function __construct($formatter = null, $nullable = false, $binaries = null)
28
    {
29 3
        $this->setNullable($nullable);
30
31 3
        if (is_array($binaries)) {
32
            $this->setBinaries($binaries);
33
        }
34
35 3
        parent::__construct($formatter);
36 3
    }
37
38
    /**
39
     * @return bool
40
     */
41 2
    public function isNullable()
42
    {
43 2
        return $this->nullable;
44
    }
45
46
    /**
47
     * @param bool $nullable
48
     *
49
     * @return BooleanFormatter
50
     */
51 3
    public function setNullable($nullable)
52
    {
53 3
        $this->nullable = (bool)$nullable;
54
55 3
        return $this;
56
    }
57
58
    /**
59
     * @param array $binaries
60
     *
61
     * @return BooleanFormatter
62
     */
63 2
    public function setBinaries(array $binaries)
64
    {
65 2
        $this->binaries = $binaries;
66
67 2
        return $this;
68
    }
69
70
    /**
71
     * @param string $truthy
72
     * @param string $falsey
73
     */
74
    public function addBinary($truthy, $falsey)
75
    {
76
        $this->binaries[$truthy] = $falsey;
77
    }
78
79
    /**
80
     * @param $key
81
     */
82
    public function removeBinary($key)
83
    {
84
        unset($this->binaries[$key]);
85
    }
86
87
    /**
88
     * @return array
89
     */
90 3
    public function getBinaries()
91
    {
92 3
        return $this->binaries;
93
    }
94
95 3
    protected function getFormattedValue($value)
96
    {
97 3
        $value = trim($value);
98
99 3
        foreach ($this->getBinaries() as $truthy => $falsey) {
100 3
            if (strcasecmp(trim($truthy), $value) === 0) {
101 2
                return true;
102
            }
103
104 3
            if (strcasecmp(trim($falsey), $value) === 0) {
105 3
                return false;
106
            }
107
        }
108
109 2
        return $this->isNullable() ? null : false;
110
    }
111
}
112