|
1
|
|
|
<?php |
|
2
|
|
|
namespace Respect\Validation\Rules; |
|
3
|
|
|
|
|
4
|
|
|
use Respect\Validation\Validatable; |
|
5
|
|
|
use Respect\Validation\Exceptions\ValidationException; |
|
6
|
|
|
|
|
7
|
|
|
abstract class AbstractRule implements Validatable |
|
8
|
|
|
{ |
|
9
|
|
|
protected $name; |
|
10
|
|
|
protected $template = null; |
|
11
|
|
|
|
|
12
|
|
|
public static $translator = null; |
|
13
|
|
|
|
|
14
|
641 |
|
public function __construct() |
|
15
|
|
|
{ |
|
16
|
|
|
//a constructor is required for ReflectionClass::newInstance() |
|
17
|
641 |
|
} |
|
18
|
|
|
|
|
19
|
1014 |
|
public function __invoke($input) |
|
20
|
|
|
{ |
|
21
|
1014 |
|
return !is_a($this, __NAMESPACE__.'\\NotEmpty') |
|
22
|
1014 |
|
&& $input === '' || $this->validate($input); |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
3 |
|
public function addOr() |
|
26
|
|
|
{ |
|
27
|
3 |
|
$rules = func_get_args(); |
|
28
|
3 |
|
array_unshift($rules, $this); |
|
29
|
|
|
|
|
30
|
3 |
|
return new OneOf($rules); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
980 |
|
public function assert($input) |
|
34
|
|
|
{ |
|
35
|
980 |
|
if ($this->__invoke($input)) { |
|
36
|
510 |
|
return true; |
|
37
|
|
|
} |
|
38
|
525 |
|
throw $this->reportError($input); |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
437 |
|
public function check($input) |
|
42
|
|
|
{ |
|
43
|
437 |
|
return $this->assert($input); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
135 |
|
public function getName() |
|
47
|
|
|
{ |
|
48
|
135 |
|
return $this->name; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
538 |
|
public function reportError($input, array $extraParams = array()) |
|
52
|
|
|
{ |
|
53
|
538 |
|
$exception = $this->createException(); |
|
54
|
538 |
|
$input = ValidationException::stringify($input); |
|
55
|
538 |
|
$name = $this->name ?: "\"$input\""; |
|
56
|
538 |
|
$params = array_merge( |
|
57
|
538 |
|
get_class_vars(__CLASS__), |
|
58
|
538 |
|
get_object_vars($this), |
|
59
|
538 |
|
$extraParams, |
|
60
|
538 |
|
compact('input') |
|
61
|
538 |
|
); |
|
62
|
538 |
|
$exception->configure($name, $params); |
|
63
|
538 |
|
if (!is_null($this->template)) { |
|
64
|
|
|
$exception->setTemplate($this->template); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
538 |
|
return $exception; |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
34 |
|
public function setName($name) |
|
71
|
|
|
{ |
|
72
|
34 |
|
$this->name = $name; |
|
73
|
|
|
|
|
74
|
34 |
|
return $this; |
|
75
|
|
|
} |
|
76
|
|
|
|
|
77
|
3 |
|
public function setTemplate($template) |
|
78
|
|
|
{ |
|
79
|
3 |
|
$this->template = $template; |
|
80
|
|
|
|
|
81
|
3 |
|
return $this; |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
538 |
|
protected function createException() |
|
85
|
|
|
{ |
|
86
|
538 |
|
$currentFQN = get_called_class(); |
|
87
|
538 |
|
$exceptionFQN = str_replace('\\Rules\\', '\\Exceptions\\', $currentFQN); |
|
88
|
538 |
|
$exceptionFQN .= 'Exception'; |
|
89
|
|
|
|
|
90
|
538 |
|
return new $exceptionFQN(); |
|
91
|
|
|
} |
|
92
|
|
|
} |
|
93
|
|
|
|