This repository has been archived by the owner on Apr 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathItemsValidator.php
76 lines (67 loc) · 1.89 KB
/
ItemsValidator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace Ulrack\Validator\Component\Iterable;
use Ulrack\Validator\Common\ValidatorInterface;
use Ulrack\Validator\Component\Logical\AlwaysValidator;
class ItemsValidator implements ValidatorInterface
{
/**
* The maximum size of the array.
*
* @var ValidatorInterface|ValidatorInterface[]|null
*/
private $items;
/**
* The additional items will be validated against this validator.
*
* @var ValidatorInterface
*/
private $additionalItems;
/**
* Constructor
*
* @param ValidatorInterface|ValidatorInterface[]|null $items
* @param ValidatorInterface|null $additionalItems
*/
public function __construct(
$items,
ValidatorInterface $additionalItems = null
) {
$this->items = $items;
$this->additionalItems = $additionalItems ?? new AlwaysValidator(true);
}
/**
* Validate the data against the validator.
*
* @param mixed $data The data that needs to be validated.
*
* @return bool
*/
public function __invoke($data): bool
{
if (!is_array($data)) {
return true;
}
foreach ($data as $key => $value) {
if (is_array($this->items)) {
if (array_key_exists($key, $this->items)) {
if (!$this->items[$key]($value)) {
return false;
}
} else {
if (!($this->additionalItems)($value)) {
return false;
}
}
} elseif ($this->items instanceof ValidatorInterface) {
if (!($this->items)($value)) {
return false;
}
}
}
return true;
}
}