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