Passed
Push — main ( 07fa9e...2a4081 )
by Michael
04:01 queued 28s
created

Boolean::true()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace MichaelRubel\ValueObjects\Collection\Primitive;
6
7
use MichaelRubel\ValueObjects\ValueObject;
8
9
/**
10
 * @method static static make(bool|int|string $bool)
11
 */
12
class Boolean extends ValueObject
13
{
14
    /**
15
     * Allowed values that are treated as `true`.
16
     *
17
     * @var array
18
     */
19
    protected array $trueValues = [
20
        '1', 'true', 'True', 'TRUE', 1, true,
21
    ];
22
23
    /**
24
     * Allowed values that are treated as `false`.
25
     *
26
     * @var array
27
     */
28
    protected array $falseValues = [
29
        '0', 'false', 'False', 'FALSE', 0, false,
30
    ];
31
32
    /**
33
     * Create a new instance of the value object.
34
     *
35
     * @param  bool|int|string  $bool
36
     */
37 11
    public function __construct(protected bool|int|string $bool)
38
    {
39 9
        $this->bool = match (true) {
40 11
            $this->isTrue()  => true,
41 9
            $this->isFalse() => false,
42 2
            default => throw new \InvalidArgumentException('Invalid boolean'),
43
        };
44
    }
45
46
    /**
47
     * Get the object value.
48
     *
49
     * @return bool
50
     */
51 8
    public function value(): bool
52
    {
53 8
        return (bool) $this->bool;
54
    }
55
56
    /**
57
     * Determine if the passed boolean is a positive value.
58
     *
59
     * @return bool
60
     */
61 11
    protected function isTrue(): bool
62
    {
63 11
        return in_array($this->bool, $this->trueValues, true);
64
    }
65
66
    /**
67
     * Determine if the passed boolean is a negative value.
68
     *
69
     * @return bool
70
     */
71 9
    protected function isFalse(): bool
72
    {
73 9
        return in_array($this->bool, $this->falseValues, true);
74
    }
75
76
    /**
77
     * Get string representation of the value object.
78
     *
79
     * @return string
80
     */
81 1
    public function __toString(): string
82
    {
83 1
        return ! empty($this->value()) ? 'true' : 'false';
84
    }
85
}
86