1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Spiral\Validation\Checker; |
6
|
|
|
|
7
|
|
|
use Spiral\Validation\AbstractChecker; |
8
|
|
|
use Spiral\Validation\ValidationInterface; |
9
|
|
|
|
10
|
|
|
class ArrayChecker extends AbstractChecker |
11
|
|
|
{ |
12
|
|
|
/** |
13
|
|
|
* {@inheritdoc} |
14
|
|
|
*/ |
15
|
|
|
public const MESSAGES = [ |
16
|
|
|
'count' => '[[Number of elements must be exactly {1}.]]', |
17
|
|
|
'longer' => '[[Number of elements must be equal to or greater than {1}.]]', |
18
|
|
|
'shorter' => '[[Number of elements must be equal to or less than {1}.]]', |
19
|
|
|
'range' => '[[Number of elements must be between {1} and {2}.]]', |
20
|
|
|
]; |
21
|
|
|
|
22
|
|
|
/** @var ValidationInterface */ |
23
|
|
|
private $validation; |
24
|
|
|
|
25
|
|
|
public function __construct(ValidationInterface $validation) |
26
|
|
|
{ |
27
|
|
|
$this->validation = $validation; |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
public function of($value, $checker): bool |
31
|
|
|
{ |
32
|
|
|
if (!is_array($value) || empty($value)) { |
33
|
|
|
return false; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
foreach ($value as $item) { |
37
|
|
|
if (!$this->validation->validate(compact('item'), ['item' => [$checker]])->isValid()) { |
38
|
|
|
return false; |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return true; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function count($value, int $length): bool |
46
|
|
|
{ |
47
|
|
|
if (!is_array($value) && !$value instanceof \Countable) { |
48
|
|
|
return false; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return count($value) === $length; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function shorter($value, int $length): bool |
55
|
|
|
{ |
56
|
|
|
if (!is_array($value) && !$value instanceof \Countable) { |
57
|
|
|
return false; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
return count($value) <= $length; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
public function longer($value, int $length): bool |
64
|
|
|
{ |
65
|
|
|
if (!is_array($value) && !$value instanceof \Countable) { |
66
|
|
|
return false; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return count($value) >= $length; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function range($value, int $min, int $max): bool |
73
|
|
|
{ |
74
|
|
|
if (!is_array($value) && !$value instanceof \Countable) { |
75
|
|
|
return false; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
$count = \count($value); |
79
|
|
|
|
80
|
|
|
return $count >= $min && $count <= $max; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|