|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/* |
|
4
|
|
|
* This file is part of Respect/Validation. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace Respect\Validation\Rules; |
|
13
|
|
|
|
|
14
|
|
|
use Respect\Validation\Exceptions\ValidationException; |
|
15
|
|
|
use Respect\Validation\Validatable; |
|
16
|
|
|
|
|
17
|
|
|
abstract class AbstractRule implements Validatable |
|
18
|
|
|
{ |
|
19
|
|
|
protected $name; |
|
20
|
|
|
protected $template; |
|
21
|
|
|
|
|
22
|
2 |
|
public function __invoke($input) |
|
23
|
|
|
{ |
|
24
|
2 |
|
return $this->validate($input); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
2 |
|
public function assert($input) |
|
28
|
|
|
{ |
|
29
|
2 |
|
if ($this->validate($input)) { |
|
30
|
1 |
|
return true; |
|
31
|
|
|
} |
|
32
|
1 |
|
throw $this->reportError($input); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
1 |
|
public function check($input) |
|
36
|
|
|
{ |
|
37
|
1 |
|
return $this->assert($input); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
15 |
|
public function getName() |
|
41
|
|
|
{ |
|
42
|
15 |
|
return $this->name; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
public function getTemplate() |
|
46
|
|
|
{ |
|
47
|
|
|
return $this->template; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
2 |
|
public function reportError($input, array $extraParams = []) |
|
51
|
|
|
{ |
|
52
|
2 |
|
$exception = $this->createException(); |
|
53
|
2 |
|
$name = $this->name ?: ValidationException::stringify($input); |
|
54
|
2 |
|
$params = array_merge( |
|
55
|
2 |
|
get_class_vars(__CLASS__), |
|
56
|
2 |
|
get_object_vars($this), |
|
57
|
2 |
|
$extraParams, |
|
58
|
2 |
|
compact('input') |
|
59
|
|
|
); |
|
60
|
2 |
|
$exception->configure($name, $params); |
|
61
|
2 |
|
if (!is_null($this->template)) { |
|
62
|
1 |
|
$exception->setTemplate($this->template); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
2 |
|
return $exception; |
|
66
|
|
|
} |
|
67
|
|
|
|
|
68
|
14 |
|
public function setName($name) |
|
69
|
|
|
{ |
|
70
|
14 |
|
$this->name = $name; |
|
71
|
|
|
|
|
72
|
14 |
|
return $this; |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
2 |
|
public function setTemplate($template) |
|
76
|
|
|
{ |
|
77
|
2 |
|
$this->template = $template; |
|
78
|
|
|
|
|
79
|
2 |
|
return $this; |
|
80
|
|
|
} |
|
81
|
|
|
|
|
82
|
1 |
|
protected function createException() |
|
83
|
|
|
{ |
|
84
|
1 |
|
$currentFqn = get_called_class(); |
|
85
|
1 |
|
$exceptionFqn = str_replace('\\Rules\\', '\\Exceptions\\', $currentFqn); |
|
86
|
1 |
|
$exceptionFqn .= 'Exception'; |
|
87
|
|
|
|
|
88
|
1 |
|
return new $exceptionFqn(); |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
|