1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Particle. |
4
|
|
|
* |
5
|
|
|
* @link http://github.com/particle-php for the canonical source repository |
6
|
|
|
* @copyright Copyright (c) 2005-2016 Particle (http://particle-php.com) |
7
|
|
|
* @license https://github.com/particle-php/validator/blob/master/LICENSE New BSD License |
8
|
|
|
*/ |
9
|
|
|
namespace Particle\Validator\Rule; |
10
|
|
|
|
11
|
|
|
use Particle\Validator\Rule; |
12
|
|
|
use Particle\Validator\ValidationResult; |
13
|
|
|
use Particle\Validator\Validator; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* This rule is for validating nested arrays. |
17
|
|
|
* |
18
|
|
|
* @package Particle\Validator\Rule |
19
|
|
|
*/ |
20
|
|
|
class Inner extends Rule |
21
|
|
|
{ |
22
|
|
|
const NOT_AN_ARRAY = 'Inner::NOT_AN_ARRAY'; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* The message templates which can be returned by this validator. |
26
|
|
|
* |
27
|
|
|
* @var array |
28
|
|
|
*/ |
29
|
|
|
protected $messageTemplates = [ |
30
|
|
|
self::NOT_AN_ARRAY => '{{ name }} must be an array', |
31
|
|
|
]; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @var callable |
35
|
|
|
*/ |
36
|
|
|
protected $callback; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param callable $callback |
40
|
|
|
*/ |
41
|
|
|
public function __construct(callable $callback) |
42
|
|
|
{ |
43
|
|
|
$this->callback = $callback; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Validates if $value is array, validate inner array of $value, and return result. |
48
|
|
|
* |
49
|
|
|
* @param mixed $value |
50
|
|
|
* @return bool |
51
|
|
|
*/ |
52
|
|
|
public function validate($value) |
53
|
|
|
{ |
54
|
|
|
if (!is_array($value)) { |
55
|
|
|
return $this->error(self::NOT_AN_ARRAY); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$validator = new Validator(); |
59
|
|
|
|
60
|
|
|
call_user_func($this->callback, $validator, $value); |
61
|
|
|
|
62
|
|
|
$result = $validator->validate($value); |
63
|
|
|
|
64
|
|
|
if (!$result->isValid()) { |
65
|
|
|
$this->handleError($result); |
66
|
|
|
return false; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
return true; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* @param ValidationResult $result |
74
|
|
|
*/ |
75
|
|
View Code Duplication |
protected function handleError($result) |
|
|
|
|
76
|
|
|
{ |
77
|
|
|
foreach ($result->getFailures() as $failure) { |
78
|
|
|
$failure->overwriteKey( |
79
|
|
|
sprintf('%s.%s', $this->key, $failure->getKey()) |
80
|
|
|
); |
81
|
|
|
|
82
|
|
|
$this->messageStack->append($failure); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|
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.