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 pathPropertiesValidator.php
112 lines (97 loc) · 2.94 KB
/
PropertiesValidator.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
* Copyright (C) GrizzIT, Inc. All rights reserved.
* See LICENSE for license details.
*/
namespace Ulrack\Validator\Component\Object;
use Ulrack\Validator\Common\ValidatorInterface;
use Ulrack\Validator\Component\Logical\AlwaysValidator;
class PropertiesValidator implements ValidatorInterface
{
/**
* The property configuration that needs to be validated.
*
* @var ValidatorInterface[]
*/
private $properties;
/**
* The additional property configuration that needs to be validated.
*
* @var ValidatorInterface
*/
private $additionalProperties;
/**
* The pattern properties configuration that needs to be validated.
*
* @var ValidatorInterface[]
*/
private $patternProperties;
/**
* The property names validator.
*
* @var ValidatorInterface
*/
private $propertyNames;
/**
* Constructor
*
* @param ValidatorInterface[]|null $properties
* @param ValidatorInterface[]|null $patternProperties
* @param ValidatorInterface|null $propertyNames
* @param ValidatorInterface|null $additionalProperties
*/
public function __construct(
?array $properties,
?array $patternProperties,
?ValidatorInterface $propertyNames,
ValidatorInterface $additionalProperties = null
) {
$this->properties = $properties;
$this->patternProperties = $patternProperties;
$this->propertyNames = $propertyNames;
$this->additionalProperties = $additionalProperties
?? 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_object($data)) {
return true;
}
foreach (get_object_vars($data) as $key => $value) {
$found = false;
if ($this->patternProperties !== null) {
foreach ($this->patternProperties as $pattern => $schema) {
if (preg_match(sprintf('/%s/', $pattern), $key) === 1) {
if (!$schema($value)) {
return false;
}
$found = true;
}
}
}
if ($this->propertyNames !== null) {
if (!($this->propertyNames)($key)) {
return false;
}
}
if ($this->properties !== null && isset($this->properties[$key])) {
if (!$this->properties[$key]($value)) {
return false;
}
$found = true;
} elseif ($found === false) {
if (!($this->additionalProperties)($value)) {
return false;
}
}
}
return true;
}
}