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 Optional 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
|
6 |
|
public function __construct(Rule ...$rules) |
23
|
|
|
{ |
24
|
6 |
|
$this->setRules($rules); |
25
|
6 |
|
} |
26
|
|
|
|
27
|
5 |
|
protected function validateValue($value, ValidationContext $context = null): Result |
28
|
|
|
{ |
29
|
5 |
|
if ($this->checkDoValidate($context)) { |
30
|
4 |
|
return $this->rules->validate($value, $context); |
|
|
|
|
31
|
|
|
} |
32
|
|
|
|
33
|
2 |
|
return new Result(); |
34
|
|
|
} |
35
|
|
|
|
36
|
5 |
|
private function checkDoValidate(?ValidationContext $context): bool |
37
|
|
|
{ |
38
|
5 |
|
if ($context === null || $context->getDataSet() === null || $context->getAttribute() === null) { |
39
|
1 |
|
return true; |
40
|
|
|
} |
41
|
|
|
|
42
|
4 |
|
$dataSet = $context->getDataSet(); |
43
|
4 |
|
$attribute = $context->getAttribute(); |
44
|
|
|
|
45
|
4 |
|
if (!$dataSet->hasAttribute($attribute)) { |
46
|
1 |
|
return false; |
47
|
|
|
} |
48
|
|
|
|
49
|
4 |
|
if ($this->checkEmpty) { |
50
|
3 |
|
$value = $dataSet->getAttributeValue($attribute); |
51
|
3 |
|
return $this->emptyCallback === null |
52
|
2 |
|
? !empty($value) |
53
|
3 |
|
: !($this->emptyCallback)($value); |
54
|
|
|
} |
55
|
|
|
|
56
|
1 |
|
return true; |
57
|
|
|
} |
58
|
|
|
|
59
|
1 |
|
public function rules(Rule ...$rules): self |
60
|
|
|
{ |
61
|
1 |
|
$new = clone $this; |
62
|
1 |
|
$new->setRules($rules); |
63
|
1 |
|
return $new; |
64
|
|
|
} |
65
|
|
|
|
66
|
2 |
|
public function checkEmpty(bool $checkEmpty): self |
67
|
|
|
{ |
68
|
2 |
|
$new = clone $this; |
69
|
2 |
|
$new->checkEmpty = $checkEmpty; |
70
|
2 |
|
return $new; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @param callable|null $callback |
75
|
|
|
* |
76
|
|
|
* @return self |
77
|
|
|
*/ |
78
|
2 |
|
public function emptyCallback(?callable $callback): self |
79
|
|
|
{ |
80
|
2 |
|
$new = clone $this; |
81
|
2 |
|
$new->emptyCallback = $callback; |
82
|
2 |
|
return $new; |
83
|
|
|
} |
84
|
|
|
|
85
|
6 |
|
private function setRules(array $rules): void |
86
|
|
|
{ |
87
|
6 |
|
$this->rules = new Rules($rules); |
88
|
6 |
|
} |
89
|
|
|
} |
90
|
|
|
|
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.