|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TraderInteractive\Filter; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* A collection of filters for booleans. |
|
7
|
|
|
*/ |
|
8
|
|
|
final class Booleans |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* Filters $value to a boolean strictly. |
|
12
|
|
|
* |
|
13
|
|
|
* $value must be a bool or 'true' or 'false' disregarding case and whitespace. |
|
14
|
|
|
* |
|
15
|
|
|
* The return value is the bool, as expected by the \TraderInteractive\Filterer class. |
|
16
|
|
|
* |
|
17
|
|
|
* @param string|bool $value the value to filter to a boolean |
|
18
|
|
|
* @param bool $allowNull Set to true if NULL values are allowed. The filtered result of a NULL value is NULL |
|
19
|
|
|
* @param array $trueValues Array of values which represent the boolean true value. Values should be lower cased |
|
20
|
|
|
* @param array $falseValues Array of values which represent the boolean false value. Values should be lower cased |
|
21
|
|
|
* |
|
22
|
|
|
* @return bool|null the filtered $value |
|
23
|
|
|
* |
|
24
|
|
|
* @throws Exception if $value is not a string |
|
25
|
|
|
* @throws Exception if $value is not 'true' or 'false' disregarding case and whitespace |
|
26
|
|
|
*/ |
|
27
|
|
|
public static function filter( |
|
28
|
|
|
$value, |
|
29
|
|
|
bool $allowNull = false, |
|
30
|
|
|
array $trueValues = ['true'], |
|
31
|
|
|
array $falseValues = ['false'] |
|
32
|
|
|
) { |
|
33
|
|
|
if ($allowNull === true && $value === null) { |
|
34
|
|
|
return null; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
if (is_bool($value)) { |
|
38
|
|
|
return $value; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
if (!is_string($value)) { |
|
42
|
|
|
throw new Exception('"' . var_export($value, true) . '" $value is not a string'); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
$value = trim($value); |
|
46
|
|
|
|
|
47
|
|
|
$value = strtolower($value); |
|
48
|
|
|
|
|
49
|
|
|
if (in_array($value, $trueValues, true)) { |
|
50
|
|
|
return true; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
if (in_array($value, $falseValues, true)) { |
|
54
|
|
|
return false; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
throw new Exception( |
|
58
|
|
|
sprintf( |
|
59
|
|
|
"%s is not '%s' disregarding case and whitespace", |
|
60
|
|
|
$value, |
|
61
|
|
|
implode("' or '", array_merge($trueValues, $falseValues)) |
|
62
|
|
|
) |
|
63
|
|
|
); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Filters the boolean $value to the given $true and $false cases |
|
68
|
|
|
* |
|
69
|
|
|
* @param boolean $value The boolean value to convert. |
|
70
|
|
|
* @param mixed $true The value to return on the true case. |
|
71
|
|
|
* @param mixed $false The value to return on the false case. |
|
72
|
|
|
* |
|
73
|
|
|
* @return mixed |
|
74
|
|
|
*/ |
|
75
|
|
|
public static function convert(bool $value, $true = 'true', $false = 'false') |
|
76
|
|
|
{ |
|
77
|
|
|
return $value ? $true : $false; |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|