1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\Rule\Trait; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use InvalidArgumentException; |
9
|
|
|
use Yiisoft\Validator\SkipOnEmptyCallback\SkipNone; |
10
|
|
|
use Yiisoft\Validator\SkipOnEmptyCallback\SkipOnEmpty; |
11
|
|
|
use Yiisoft\Validator\ValidationContext; |
12
|
|
|
|
13
|
|
|
use function is_callable; |
14
|
|
|
|
15
|
|
|
trait BeforeValidationTrait |
16
|
|
|
{ |
17
|
24 |
|
public function getSkipOnEmpty(): bool |
18
|
|
|
{ |
19
|
24 |
|
return $this->skipOnEmpty; |
20
|
|
|
} |
21
|
|
|
|
22
|
24 |
|
public function getSkipOnEmptyCallback(): callable |
23
|
|
|
{ |
24
|
24 |
|
return $this->skipOnEmptyCallback; |
25
|
|
|
} |
26
|
|
|
|
27
|
79 |
|
public function shouldSkipOnEmpty(mixed $validatedValue): bool |
28
|
|
|
{ |
29
|
79 |
|
return ($this->skipOnEmptyCallback)($validatedValue); |
30
|
|
|
} |
31
|
|
|
|
32
|
138 |
|
protected function initSkipOnEmptyProperties(bool $skipOnEmpty = false, ?callable $skipOnEmptyCallback = null): void |
33
|
|
|
{ |
34
|
138 |
|
$this->skipOnEmpty = $skipOnEmpty; |
|
|
|
|
35
|
138 |
|
$this->skipOnEmptyCallback = $skipOnEmptyCallback; |
|
|
|
|
36
|
|
|
|
37
|
138 |
|
if ($this->skipOnEmptyCallback) { |
38
|
35 |
|
if (!is_callable($this->skipOnEmptyCallback)) { |
39
|
|
|
throw new InvalidArgumentException('$skipOnEmptyCallback must be a callable.'); |
40
|
|
|
} |
41
|
|
|
|
42
|
35 |
|
$this->skipOnEmpty = true; |
43
|
|
|
|
44
|
35 |
|
return; |
45
|
|
|
} |
46
|
|
|
|
47
|
138 |
|
$this->skipOnEmptyCallback = $this->skipOnEmpty === false ? new SkipNone() : new SkipOnEmpty(); |
48
|
|
|
} |
49
|
|
|
|
50
|
35 |
|
public function skipOnEmpty(bool $value): self |
51
|
|
|
{ |
52
|
35 |
|
$new = clone $this; |
53
|
35 |
|
$new->skipOnEmpty = $value; |
|
|
|
|
54
|
35 |
|
$new->initSkipOnEmptyProperties($new->skipOnEmpty); |
55
|
|
|
|
56
|
35 |
|
return $new; |
57
|
|
|
} |
58
|
|
|
|
59
|
35 |
|
public function skipOnEmptyCallback(?callable $value): self |
60
|
|
|
{ |
61
|
35 |
|
$new = clone $this; |
62
|
35 |
|
$new->skipOnEmptyCallback = $value; |
|
|
|
|
63
|
35 |
|
$new->initSkipOnEmptyProperties(false, $value); |
64
|
|
|
|
65
|
35 |
|
return $new; |
66
|
|
|
} |
67
|
|
|
|
68
|
77 |
|
public function shouldSkipOnError(): bool |
69
|
|
|
{ |
70
|
77 |
|
return $this->skipOnError; |
|
|
|
|
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @psalm-return Closure(mixed, ValidationContext):bool|null |
75
|
|
|
* |
76
|
|
|
* @return Closure|null |
77
|
|
|
*/ |
78
|
76 |
|
public function getWhen(): ?Closure |
79
|
|
|
{ |
80
|
76 |
|
return $this->when; |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|