1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\Result; |
8
|
|
|
use Yiisoft\Validator\Rule; |
9
|
|
|
use Yiisoft\Validator\Rules; |
10
|
|
|
use Yiisoft\Validator\ValidationContext; |
11
|
|
|
|
12
|
|
|
final class OptionalRule extends Rule |
13
|
|
|
{ |
14
|
|
|
private ?Rules $rules = null; |
15
|
|
|
private bool $checkEmpty = true; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var callable|null |
19
|
|
|
*/ |
20
|
|
|
private $emptyCallback = null; |
21
|
|
|
|
22
|
4 |
|
protected function validateValue($value, ValidationContext $context = null): Result |
23
|
|
|
{ |
24
|
4 |
|
if ($this->checkDoValidate($context)) { |
25
|
3 |
|
return $this->rules->validate($value, $context); |
|
|
|
|
26
|
|
|
} |
27
|
|
|
|
28
|
3 |
|
return new Result(); |
29
|
|
|
} |
30
|
|
|
|
31
|
4 |
|
private function checkDoValidate(?ValidationContext $context): bool |
32
|
|
|
{ |
33
|
4 |
|
if (!$context || !$context->getDataSet() || !$context->getAttribute()) { |
34
|
|
|
return true; |
35
|
|
|
} |
36
|
|
|
|
37
|
4 |
|
$dataSet = $context->getDataSet(); |
38
|
4 |
|
$attribute = $context->getAttribute(); |
39
|
|
|
|
40
|
4 |
|
if (!$dataSet->hasAttribute($attribute)) { |
41
|
1 |
|
return false; |
42
|
|
|
} |
43
|
|
|
|
44
|
4 |
|
if ($this->checkEmpty) { |
45
|
3 |
|
$value = $dataSet->getAttributeValue($attribute); |
46
|
3 |
|
return $this->emptyCallback === null |
47
|
2 |
|
? !empty($value) |
48
|
3 |
|
: !($this->emptyCallback)($value); |
49
|
|
|
} |
50
|
|
|
|
51
|
1 |
|
return true; |
52
|
|
|
} |
53
|
|
|
|
54
|
4 |
|
public function rules(array $rules): self |
55
|
|
|
{ |
56
|
4 |
|
$new = clone $this; |
57
|
4 |
|
$new->rules = new Rules($rules); |
58
|
4 |
|
return $new; |
59
|
|
|
} |
60
|
|
|
|
61
|
1 |
|
public function checkEmpty(bool $checkEmpty): self |
62
|
|
|
{ |
63
|
1 |
|
$new = clone $this; |
64
|
1 |
|
$new->checkEmpty = $checkEmpty; |
65
|
1 |
|
return $new; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param callable|null $callback |
70
|
|
|
* |
71
|
|
|
* @return self |
72
|
|
|
*/ |
73
|
1 |
|
public function emptyCallback($callback): self |
74
|
|
|
{ |
75
|
1 |
|
$new = clone $this; |
76
|
1 |
|
$new->emptyCallback = $callback; |
77
|
1 |
|
return $new; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.
This is most likely a typographical error or the method has been renamed.