|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace hanneskod\clean; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* Validate arrays of input data |
|
7
|
|
|
*/ |
|
8
|
|
|
class ArrayValidator extends Validator |
|
9
|
|
|
{ |
|
10
|
|
|
/** |
|
11
|
|
|
* @var Validator[] Map of field names to validators |
|
12
|
|
|
*/ |
|
13
|
|
|
private $validators = []; |
|
14
|
|
|
|
|
15
|
|
|
/** |
|
16
|
|
|
* @var boolean Flag if unknown array items should be ignored when validating |
|
17
|
|
|
*/ |
|
18
|
|
|
private $ignoreUnknown = false; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Register validators |
|
22
|
|
|
* |
|
23
|
|
|
* @param Validator[] $validators Map of field names to validators |
|
24
|
|
|
*/ |
|
25
|
|
|
public function __construct(array $validators = []) |
|
26
|
|
|
{ |
|
27
|
|
|
foreach ($validators as $name => $validator) { |
|
28
|
|
|
$this->addValidator($name, $validator); |
|
29
|
|
|
} |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
/** |
|
33
|
|
|
* Add a validator |
|
34
|
|
|
* |
|
35
|
|
|
* @param string $name Name of field to validate |
|
36
|
|
|
* @param Validator $validator The validator |
|
37
|
|
|
* @return self Instance for chaining |
|
38
|
|
|
*/ |
|
39
|
|
|
public function addValidator($name, Validator $validator) |
|
40
|
|
|
{ |
|
41
|
|
|
$this->validators[$name] = $validator; |
|
42
|
|
|
return $this; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Set flag if unknown items should be ignored when validating |
|
47
|
|
|
* |
|
48
|
|
|
* @param boolean $ignoreUnknown |
|
49
|
|
|
* @return self Instance for chaining |
|
50
|
|
|
*/ |
|
51
|
|
|
public function ignoreUnknown($ignoreUnknown = true) |
|
52
|
|
|
{ |
|
53
|
|
|
$this->ignoreUnknown = $ignoreUnknown; |
|
54
|
|
|
return $this; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
/** |
|
58
|
|
|
* Validate tainted data |
|
59
|
|
|
* |
|
60
|
|
|
* {@inheritdoc} |
|
61
|
|
|
*/ |
|
62
|
|
|
public function validate($tainted) |
|
63
|
|
|
{ |
|
64
|
|
|
if (!is_array($tainted)) { |
|
65
|
|
|
throw new Exception("expecting array input"); |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
|
|
$clean = []; |
|
69
|
|
|
|
|
70
|
|
|
foreach ($this->validators as $name => $validator) { |
|
71
|
|
|
try { |
|
72
|
|
|
$clean[$name] = $validator->validate( |
|
73
|
|
|
isset($tainted[$name]) ? $tainted[$name] : null |
|
74
|
|
|
); |
|
75
|
|
|
} catch (Exception $exception) { |
|
76
|
|
|
$exception->pushValidatorName($name); |
|
77
|
|
|
$this->fireException($exception); |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
if (!$this->ignoreUnknown && $diff = array_diff_key($tainted, $this->validators)) { |
|
82
|
|
|
$this->fireException( |
|
83
|
|
|
new Exception('Unknown input item(s): ' . implode(array_keys($diff), ', ')) |
|
84
|
|
|
); |
|
85
|
|
|
} |
|
86
|
|
|
|
|
87
|
|
|
return $clean; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|