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
|
|
|
|