1
|
|
|
<?php |
2
|
|
|
namespace Wandu\Validator\Rules; |
3
|
|
|
|
4
|
|
|
use stdClass; |
5
|
|
|
use Wandu\Validator\Exception\InvalidValueException; |
6
|
|
|
use function Wandu\Validator\validator; |
7
|
|
|
|
8
|
|
|
class ObjectValidator extends ValidatorAbstract |
9
|
|
|
{ |
10
|
|
|
const ERROR_TYPE = 'object'; |
11
|
|
|
const ERROR_PROPERTY_TYPE = 'object_property'; |
12
|
|
|
|
13
|
|
|
/** @var \Wandu\Validator\Contracts\ValidatorInterface[] */ |
14
|
|
|
protected $properties = []; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* @param array $properties |
18
|
|
|
*/ |
19
|
5 |
|
public function __construct(array $properties = []) |
20
|
|
|
{ |
21
|
5 |
|
foreach ($properties as $name => $validator) { |
22
|
5 |
|
$this->properties[$name] = validator()->from($validator); |
23
|
5 |
|
} |
24
|
5 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
*/ |
29
|
5 |
|
function test($item) |
|
|
|
|
30
|
|
|
{ |
31
|
5 |
|
return is_object($item); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* {@inheritdoc} |
36
|
|
|
*/ |
37
|
4 |
|
public function assert($item) |
38
|
|
|
{ |
39
|
4 |
|
if (!isset($item)) $item = new stdClass(); |
40
|
|
|
/** @var \Wandu\Validator\Exception\InvalidValueException[] $exceptions */ |
41
|
4 |
|
$exceptions = []; |
42
|
4 |
|
if (!$this->test($item)) { |
43
|
3 |
|
$exceptions['.'] = $this->createException(); |
44
|
3 |
|
} |
45
|
4 |
|
foreach ($this->properties as $name => $validator) { |
46
|
|
|
try { |
47
|
4 |
|
$value = null; |
48
|
4 |
|
if (is_object($item)) { |
49
|
4 |
|
$value = object_get($item, $name); |
50
|
4 |
|
} |
51
|
4 |
|
$validator->assert($value); |
52
|
4 |
|
} catch (InvalidValueException $e) { |
53
|
2 |
|
$exceptions[$name] = $e; |
54
|
|
|
} |
55
|
4 |
|
} |
56
|
4 |
|
if (count($exceptions)) { |
57
|
4 |
|
throw InvalidValueException::merge($exceptions); |
58
|
|
|
} |
59
|
3 |
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* {@inheritdoc} |
63
|
|
|
*/ |
64
|
1 |
|
public function validate($item) |
65
|
|
|
{ |
66
|
1 |
|
if (!isset($item)) $item = new stdClass(); |
67
|
1 |
|
if (!$this->test($item)) return false; |
68
|
|
|
|
69
|
1 |
|
foreach ($this->properties as $name => $validator) { |
70
|
1 |
|
if (!is_object($item) || object_get($item, $name) === null) { |
71
|
1 |
|
return false; |
72
|
|
|
} |
73
|
1 |
|
if (!$validator->validate(object_get($item, $name))) { |
74
|
1 |
|
return false; |
75
|
|
|
} |
76
|
1 |
|
} |
77
|
1 |
|
return true; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.