Boolean::__invoke()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 19
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 9
nc 4
nop 2
dl 0
loc 19
ccs 10
cts 10
cp 1
crap 4
rs 9.9666
c 0
b 0
f 0
1
<?php
2
3
namespace Mbright\Validation\Rule\Sanitize;
4
5
use Mbright\Validation\Rule\AbstractBooleanCase;
6
7
class Boolean extends AbstractBooleanCase implements SanitizeRuleInterface
8
{
9
    /** @var bool|mixed */
10
    protected $trueValue;
11
12
    /** @var bool|mixed */
13
    protected $falseValue;
14
15
    /**
16
     * @param bool $true Use this value for `true`.
17
     * @param bool $false Use this value for `false`.
18
     */
19 114
    public function __construct($true = true, $false = false)
20
    {
21 114
        $this->trueValue = $true;
22 114
        $this->falseValue = $false;
23 114
    }
24
25
    /**
26
     * Sanitize the value to a boolean, or a pseudo-boolean.
27
     *
28
     * @param object $subject The subject to be filtered.
29
     * @param string $field The subject field name.
30
     * @param mixed $true Use this value for `true`.
31
     * @param mixed $false Use this value for `false`.
32
     *
33
     * @return bool Always true.
34
     */
35 108
    public function __invoke($subject, string $field): bool
36
    {
37 108
        $value = $subject->$field;
38
39 108
        if ($this->isTrue($value)) {
40 54
            $subject->$field = $this->trueValue;
41
42 54
            return true;
43
        }
44
45 54
        if ($this->isFalse($value)) {
46 48
            $subject->$field = $this->falseValue;
47
48 48
            return true;
49
        }
50
51 6
        $subject->$field = $value ? $this->trueValue : $this->falseValue;
52
53 6
        return true;
54
    }
55
}
56