1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
|
4
|
|
|
namespace Yiisoft\Validator; |
5
|
|
|
|
6
|
|
|
/** |
7
|
|
|
* Rule represents a single value validation rule. |
8
|
|
|
*/ |
9
|
|
|
abstract class Rule |
10
|
|
|
{ |
11
|
|
|
private bool $skipOnEmpty = false; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Validates the value |
15
|
|
|
* |
16
|
|
|
* @param mixed $value value to be validated |
17
|
|
|
* @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation |
18
|
|
|
* @return Result |
19
|
|
|
*/ |
20
|
117 |
|
final public function validate($value, DataSetInterface $dataSet = null): Result |
21
|
|
|
{ |
22
|
117 |
|
if ($this->skipOnEmpty && $this->isEmpty($value)) { |
23
|
|
|
return new Result(); |
24
|
|
|
} |
25
|
|
|
|
26
|
117 |
|
return $this->validateValue($value, $dataSet); |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Validates the value. The method should be implemented by concrete validation rules. |
31
|
|
|
* |
32
|
|
|
* @param mixed $value value to be validated |
33
|
|
|
* @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation |
34
|
|
|
* @return Result |
35
|
|
|
*/ |
36
|
|
|
abstract protected function validateValue($value, DataSetInterface $dataSet = null): Result; |
37
|
|
|
|
38
|
98 |
|
protected function formatMessage(string $message, array $arguments = []): string |
39
|
|
|
{ |
40
|
98 |
|
$replacements = []; |
41
|
98 |
|
foreach ($arguments as $key => $value) { |
42
|
35 |
|
if (is_array($value)) { |
43
|
1 |
|
$value = 'array'; |
44
|
34 |
|
} elseif (is_object($value)) { |
45
|
2 |
|
$value = 'object'; |
46
|
32 |
|
} elseif (is_resource($value)) { |
47
|
1 |
|
$value = 'resource'; |
48
|
|
|
} |
49
|
|
|
|
50
|
35 |
|
$replacements['{' . $key . '}'] = $value; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
// TODO: move it to upper level and make it configurable? |
54
|
98 |
|
return strtr($message, $replacements); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* @param bool $value if validation should be skipped if value validated is empty |
59
|
|
|
* @return self |
60
|
|
|
*/ |
61
|
1 |
|
public function skipOnEmpty(bool $value): self |
62
|
|
|
{ |
63
|
1 |
|
$new = clone $this; |
64
|
1 |
|
$new->skipOnEmpty = $value; |
65
|
1 |
|
return $new; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* Checks if the given value is empty. |
70
|
|
|
* A value is considered empty if it is null, an empty array, or an empty string. |
71
|
|
|
* Note that this method is different from PHP empty(). It will return false when the value is 0. |
72
|
|
|
* @param mixed $value the value to be checked |
73
|
|
|
* @return bool whether the value is empty |
74
|
|
|
*/ |
75
|
3 |
|
protected function isEmpty($value): bool |
76
|
|
|
{ |
77
|
3 |
|
return $value === null || $value === [] || $value === ''; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|