|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Iris\Validator; |
|
4
|
|
|
|
|
5
|
|
|
use Iris\Transfer\Tracking\AbstractTracking; |
|
6
|
|
|
|
|
7
|
|
|
abstract class AbstractValidator |
|
8
|
|
|
{ |
|
9
|
|
|
/** |
|
10
|
|
|
* @var array |
|
11
|
|
|
*/ |
|
12
|
|
|
protected $errors; |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* @var bool |
|
16
|
|
|
*/ |
|
17
|
|
|
protected $isValid; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var bool |
|
21
|
|
|
*/ |
|
22
|
|
|
protected $isValidCalled; |
|
23
|
|
|
|
|
24
|
35 |
|
public function __construct() |
|
25
|
|
|
{ |
|
26
|
35 |
|
$this->errors = []; |
|
27
|
35 |
|
$this->isValid = false; |
|
28
|
35 |
|
$this->isValidCalled = false; |
|
29
|
35 |
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @param AbstractTracking $transfer |
|
33
|
|
|
* @throws \RuntimeException |
|
34
|
|
|
* @return bool |
|
35
|
|
|
*/ |
|
36
|
30 |
|
public function isValid(AbstractTracking $transfer) |
|
37
|
|
|
{ |
|
38
|
30 |
|
$expectedTransferClass = $this->getExpectedValidatorName($this); |
|
39
|
|
|
|
|
40
|
30 |
|
if (!$transfer instanceof $expectedTransferClass) { |
|
41
|
4 |
|
throw new \RuntimeException(sprintf('Must be %s as parameter', $expectedTransferClass)); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
26 |
|
$this->isValid = $this->validate($transfer); |
|
45
|
26 |
|
$this->isValidCalled = true; |
|
46
|
|
|
|
|
47
|
26 |
|
return $this->isValid; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* The implementation must add the errors into the errors property. For example: |
|
52
|
|
|
* |
|
53
|
|
|
* $this->errors = [ |
|
54
|
|
|
* 0 => 'error 1', |
|
55
|
|
|
* 1 => 'error 2', |
|
56
|
|
|
* ] |
|
57
|
|
|
* |
|
58
|
|
|
* @param $transfer |
|
59
|
|
|
* @return bool |
|
60
|
|
|
*/ |
|
61
|
|
|
protected abstract function validate($transfer); |
|
|
|
|
|
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @return array |
|
65
|
|
|
* @throws \RuntimeException |
|
66
|
|
|
*/ |
|
67
|
30 |
|
public function getErrors() |
|
68
|
|
|
{ |
|
69
|
30 |
|
if (!$this->isValidCalled) { |
|
70
|
4 |
|
throw new \RuntimeException('You must call the isValid first'); |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
26 |
|
return $this->errors; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
/** |
|
77
|
|
|
* @param AbstractValidator $validator |
|
78
|
|
|
* @return string |
|
79
|
|
|
*/ |
|
80
|
30 |
|
protected function getExpectedValidatorName(AbstractValidator $validator) |
|
81
|
|
|
{ |
|
82
|
30 |
|
$validatorClassName = get_class($validator); |
|
83
|
|
|
|
|
84
|
30 |
|
$path = explode('\\', $validatorClassName); |
|
85
|
|
|
|
|
86
|
30 |
|
$className = array_pop($path); |
|
87
|
|
|
|
|
88
|
30 |
|
return '\Iris\Transfer\Tracking\\' . $className; |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|