Completed
Push — master ( 73d774...c4c4fb )
by Rick
01:40
created

Ranges   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 11
lcom 0
cbo 0
dl 0
loc 68
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A stringWithLength() 0 10 4
A intBetween() 0 7 2
A enum() 0 16 4
A stringOneOf() 0 7 1
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
	public static function stringWithLength(int $minimumLength, int $maximumLength): \Closure
21
	{
22
		if ($maximumLength < 0 || $maximumLength < 1)
23
			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
	public static function intBetween(int $minimum, int $maximum): \Closure
38
	{
39
		return function (int $value) use ($minimum, $maximum)
40
		{
41
			return $value >= $minimum && $value <= $maximum;
42
		};
43
	}
44
45
	/**
46
	 * @param array ...$allowedValues
47
	 *
48
	 * @return \Closure
49
	 */
50
	public static function enum(...$allowedValues): \Closure
51
	{
52
		return function ($value) use ($allowedValues)
53
		{
54
			if (is_object($value))
55
			{
56
				foreach ($allowedValues as $allowedValue)
57
					if (is_a($value, $allowedValue))
58
						return true;
59
60
				return false;
61
			}
62
63
			return in_array(gettype($value), $allowedValues);
64
		};
65
	}
66
67
	/**
68
	 * @param array ...$allowedValues
69
	 *
70
	 * @return \Closure
71
	 */
72
	public static function stringOneOf(...$allowedValues): \Closure
73
	{
74
		return function (string $value) use ($allowedValues)
75
		{
76
			return in_array($value, $allowedValues);
77
		};
78
	}
79
}