|
1
|
|
|
<?php |
|
2
|
|
|
namespace Wandu\Validator; |
|
3
|
|
|
|
|
4
|
|
|
use Wandu\Validator\Contracts\RuleDefinitionInterface; |
|
5
|
|
|
use Wandu\Validator\Contracts\RuleInterface; |
|
6
|
|
|
|
|
7
|
|
|
class AssertRuleDefinition implements RuleDefinitionInterface |
|
8
|
|
|
{ |
|
9
|
|
|
/** @var \Wandu\Validator\ErrorBag */ |
|
10
|
|
|
protected $errors; |
|
11
|
|
|
|
|
12
|
|
|
/** @var mixed $data */ |
|
13
|
|
|
protected $data; |
|
14
|
|
|
|
|
15
|
3 |
|
public function __construct(ErrorBag $errors, $data) |
|
16
|
|
|
{ |
|
17
|
3 |
|
$this->errors = $errors; |
|
18
|
3 |
|
$this->data = $data; |
|
19
|
3 |
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* {@inheritdoc} |
|
23
|
|
|
*/ |
|
24
|
3 |
|
public function prop(string $target, $rules = null) |
|
25
|
|
|
{ |
|
26
|
3 |
|
$rules = ($rules ? $rules : []); |
|
27
|
3 |
|
$rules = is_array($rules) ? $rules : [$rules]; |
|
28
|
|
|
|
|
29
|
3 |
|
$targetName = $target; |
|
30
|
3 |
|
$iterable = 0; |
|
31
|
3 |
|
$optional = false; |
|
32
|
|
|
|
|
33
|
3 |
|
if (strpos($targetName, '?') !== false) { |
|
34
|
3 |
|
$targetName = trim($targetName, '?'); |
|
35
|
3 |
|
$optional = true; |
|
36
|
|
|
} |
|
37
|
3 |
|
while (strpos($targetName, "[]") !== false) { |
|
38
|
1 |
|
$targetName = str_replace("[]", "", $targetName); |
|
39
|
1 |
|
$iterable++; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
3 |
|
if ($optional && !isset($this->data[$targetName])) return; |
|
43
|
3 |
|
if (!isset($this->data[$targetName])) { |
|
44
|
2 |
|
$this->errors->throw("required", [$targetName]); |
|
45
|
2 |
|
return; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
3 |
|
if ($iterable && !is_array($this->data[$targetName])) { |
|
49
|
|
|
$this->errors->throw("array", [$targetName]); |
|
50
|
|
|
return; |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
3 |
|
$this->errors->pushPrefix($targetName); |
|
54
|
3 |
|
if ($iterable) { |
|
55
|
1 |
|
foreach ($this->data[$targetName] as $index => $subData) { |
|
56
|
1 |
|
$this->errors->pushPrefix($index); |
|
57
|
1 |
|
foreach ($rules as $rule) { |
|
58
|
1 |
|
if ($rule instanceof RuleInterface) { |
|
59
|
1 |
|
$rule->define(new AssertRuleDefinition($this->errors, $subData)); |
|
60
|
|
|
} else { |
|
61
|
|
|
if (!tester($rule)->test($subData)) { |
|
62
|
1 |
|
$this->errors->throw($rule); |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
} |
|
66
|
1 |
|
$this->errors->popPrefix(); |
|
67
|
|
|
} |
|
68
|
|
|
} else { |
|
69
|
3 |
|
foreach ($rules as $rule) { |
|
70
|
3 |
|
if ($rule instanceof RuleInterface) { |
|
71
|
1 |
|
$rule->define(new AssertRuleDefinition($this->errors, $this->data[$targetName])); |
|
72
|
|
|
} else { |
|
73
|
3 |
|
if (!tester($rule)->test($this->data[$targetName])) { |
|
74
|
3 |
|
$this->errors->throw($rule); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
3 |
|
$this->errors->popPrefix(); |
|
80
|
3 |
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|