1
|
|
|
<?php |
2
|
|
|
namespace Respect\Validation\Rules; |
3
|
|
|
|
4
|
|
|
use Respect\Validation\Validatable; |
5
|
|
|
use Respect\Validation\Exceptions\ValidationException; |
6
|
|
|
|
7
|
|
|
abstract class AbstractRelated extends AbstractRule |
8
|
|
|
{ |
9
|
|
|
public $mandatory = true; |
10
|
|
|
public $reference = ''; |
11
|
|
|
public $validator; |
12
|
|
|
|
13
|
|
|
abstract public function hasReference($input); |
14
|
|
|
|
15
|
|
|
abstract public function getReferenceValue($input); |
16
|
|
|
|
17
|
27 |
|
public function __construct($reference, Validatable $validator = null, $mandatory = true) |
18
|
|
|
{ |
19
|
27 |
|
$this->setName($reference); |
20
|
27 |
|
$this->reference = $reference; |
21
|
27 |
|
$this->validator = $validator; |
22
|
27 |
|
$this->mandatory = $mandatory; |
23
|
27 |
|
} |
24
|
|
|
|
25
|
21 |
|
private function decision($type, $hasReference, $input) |
26
|
|
|
{ |
27
|
21 |
|
return (!$this->mandatory && !$hasReference) |
28
|
18 |
|
|| (is_null($this->validator) |
29
|
21 |
|
|| $this->validator->$type($this->getReferenceValue($input))); |
30
|
|
|
} |
31
|
|
|
|
32
|
20 |
|
public function assert($input) |
33
|
|
|
{ |
34
|
20 |
|
if ($input === '') { |
35
|
3 |
|
return true; |
36
|
|
|
} |
37
|
|
|
|
38
|
18 |
|
$hasReference = $this->hasReference($input); |
39
|
18 |
|
if ($this->mandatory && !$hasReference) { |
40
|
3 |
|
throw $this->reportError($input, array('hasReference' => false)); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
try { |
44
|
15 |
|
return $this->decision('assert', $hasReference, $input); |
45
|
5 |
|
} catch (ValidationException $e) { |
46
|
5 |
|
throw $this |
47
|
5 |
|
->reportError($this->reference, array('hasReference' => true)) |
48
|
5 |
|
->addRelated($e); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
8 |
|
public function check($input) |
53
|
|
|
{ |
54
|
8 |
|
if ($input === '') { |
55
|
2 |
|
return true; |
56
|
|
|
} |
57
|
|
|
|
58
|
7 |
|
$hasReference = $this->hasReference($input); |
59
|
7 |
|
if ($this->mandatory && !$hasReference) { |
60
|
1 |
|
throw $this->reportError($input, array('hasReference' => false)); |
61
|
|
|
} |
62
|
|
|
|
63
|
6 |
|
return $this->decision('check', $hasReference, $input); |
64
|
|
|
} |
65
|
|
|
|
66
|
14 |
|
public function validate($input) |
67
|
|
|
{ |
68
|
14 |
|
if ($input === '') { |
69
|
1 |
|
return true; |
70
|
|
|
} |
71
|
|
|
|
72
|
13 |
|
$hasReference = $this->hasReference($input); |
73
|
13 |
|
if ($this->mandatory && !$hasReference) { |
74
|
2 |
|
return false; |
75
|
|
|
} |
76
|
|
|
|
77
|
11 |
|
return $this->decision('validate', $hasReference, $input); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|