1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the Valdi package. |
5
|
|
|
* |
6
|
|
|
* (c) Philip Lehmann-Böhm <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Valdi\Validator; |
13
|
|
|
|
14
|
|
|
use Valdi\ValidationException; |
15
|
|
|
use Valdi\Validator; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Validator for nested data sets. |
19
|
|
|
*/ |
20
|
|
|
class Nested implements ValidatorInterface { |
21
|
|
|
|
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Holds the invalid values. |
25
|
|
|
*/ |
26
|
|
|
protected $invalidDetails; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Checks whether the given values are of the expected nested data. |
30
|
|
|
* |
31
|
|
|
* @param mixed $value |
32
|
|
|
* the potential nested values to check |
33
|
|
|
* @param Validator $validator |
34
|
|
|
* the validator to check with |
35
|
|
|
* @param array $rules |
36
|
|
|
* the rules which the nested data must fulfill |
37
|
|
|
* |
38
|
|
|
* @return boolean |
39
|
|
|
* true if all the $values are a valid array, else false with the invalid details set |
40
|
|
|
*/ |
41
|
|
|
protected function isValidNested($value, Validator $validator, array $rules) { |
42
|
|
|
if (!is_array($value)) { |
43
|
|
|
$this->invalidDetails = $value; |
44
|
|
|
return false; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$elementValidation = $validator->isValid($rules, $value); |
48
|
|
|
if (!$elementValidation['valid']) { |
49
|
|
|
$this->invalidDetails = $elementValidation['errors']; |
50
|
|
|
return false; |
51
|
|
|
} |
52
|
|
|
return true; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* {@inheritdoc} |
57
|
|
|
*/ |
58
|
|
View Code Duplication |
public function isValid($value, array $parameters) { |
|
|
|
|
59
|
|
|
if (count($parameters) !== 2) { |
60
|
|
|
throw new ValidationException('"nested" expects two parameters.'); |
61
|
|
|
} |
62
|
|
|
if (!($parameters[0] instanceof Validator)) { |
63
|
|
|
throw new ValidationException('"nested" expects the first parameter to be an instance of a Validator.'); |
64
|
|
|
} |
65
|
|
|
return in_array($value, ['', null], true) || |
66
|
|
|
$this->isValidNested($value, $parameters[0], $parameters[1]); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* {@inheritdoc} |
71
|
|
|
*/ |
72
|
|
|
public function getInvalidDetails() { |
73
|
|
|
return ['nested' => $this->invalidDetails]; |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.