1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Copyright 2017 NanoSector |
4
|
|
|
* |
5
|
|
|
* You should have received a copy of the MIT license with the project. |
6
|
|
|
* See the LICENSE file for more information. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace ValidationClosures; |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
class Ranges |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @param int $minimumLength |
16
|
|
|
* @param int $maximumLength |
17
|
|
|
* |
18
|
|
|
* @return \Closure |
19
|
|
|
*/ |
20
|
1 |
|
public static function stringWithLengthBetween(int $minimumLength, int $maximumLength): \Closure |
21
|
|
|
{ |
22
|
1 |
|
if ($maximumLength < 0 || $maximumLength < 1) |
23
|
1 |
|
throw new \InvalidArgumentException('Minimum length cannot be below 0, maximum length cannot be below 1'); |
24
|
|
|
|
25
|
|
|
return function (string $value) use ($minimumLength, $maximumLength) |
26
|
|
|
{ |
27
|
|
|
return strlen($value) >= $minimumLength && strlen($value) <= $maximumLength; |
28
|
|
|
}; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param int $minimum |
33
|
|
|
* @param int $maximum |
34
|
|
|
* |
35
|
|
|
* @return \Closure |
36
|
|
|
*/ |
37
|
1 |
|
public static function intBetween(int $minimum, int $maximum): \Closure |
38
|
|
|
{ |
39
|
|
|
return function (int $value) use ($minimum, $maximum) |
40
|
|
|
{ |
41
|
1 |
|
return $value >= $minimum && $value <= $maximum; |
42
|
1 |
|
}; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @param array ...$allowedValues |
47
|
|
|
* |
48
|
|
|
* @return \Closure |
49
|
|
|
*/ |
|
|
|
|
50
|
1 |
|
public static function enum(...$allowedValues): \Closure |
51
|
|
|
{ |
52
|
|
|
return function ($value) use ($allowedValues) |
53
|
|
|
{ |
54
|
1 |
|
return in_array($value, $allowedValues, true); |
55
|
1 |
|
}; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param array ...$allowedTypes |
60
|
|
|
* |
61
|
|
|
* @return \Closure |
62
|
|
|
*/ |
|
|
|
|
63
|
1 |
|
public static function typeEnum(...$allowedTypes): \Closure |
64
|
|
|
{ |
65
|
|
|
return function ($value) use ($allowedTypes) |
66
|
|
|
{ |
67
|
1 |
|
return in_array(gettype($value), $allowedTypes, true); |
68
|
1 |
|
}; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
/** |
72
|
|
|
* @param array ...$allowedValues |
73
|
|
|
* |
74
|
|
|
* @return \Closure |
75
|
|
|
*/ |
|
|
|
|
76
|
|
|
public static function stringOneOf(...$allowedValues): \Closure |
77
|
|
|
{ |
78
|
1 |
|
return function (string $value) use ($allowedValues) |
79
|
|
|
{ |
80
|
1 |
|
return in_array($value, $allowedValues); |
81
|
1 |
|
}; |
82
|
|
|
} |
83
|
|
|
} |