1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Yiisoft\Validator\EmptyCondition; |
||
6 | |||
7 | use function is_string; |
||
8 | |||
9 | /** |
||
10 | * Empty condition is a callable returning `true` if a value must be considered empty. |
||
11 | * |
||
12 | * With `WhenEmpty`, a value is considered empty only when it is either: |
||
13 | * |
||
14 | * - Not passed at all. |
||
15 | * - `null`. |
||
16 | * - An empty string (not trimmed by default). |
||
17 | * - An empty iterable. |
||
18 | * |
||
19 | * With regard to validation process, a corresponding rule is skipped only if this condition is met and `WhenEmpty` is |
||
20 | * set: |
||
21 | * |
||
22 | * - At a rule level via `$skipOnEmpty` property, but only for rules implementing {@see SkipOnEmptyTrait} / including |
||
23 | * {@see SkipOnEmptyTrait}. |
||
24 | * - At validator level ({@see Validator::$defaultSkipOnEmptyCondition}). |
||
25 | * |
||
26 | * A shortcut for `new WhenEmpty()` is `true` (string is not trimmed). If you want a string to be trimmed before |
||
27 | * checking, use `new WhenEmpty(trimString: false)`. |
||
28 | */ |
||
29 | final class WhenEmpty |
||
30 | { |
||
31 | public function __construct( |
||
32 | /* |
||
33 | * @var bool Whether to trim string (both from the start and from the end) before checking. Defaults to `false` |
||
0 ignored issues
–
show
Coding Style
introduced
by
![]() |
|||
34 | * meaning no trimming is done. |
||
0 ignored issues
–
show
|
|||
35 | */ |
||
0 ignored issues
–
show
|
|||
36 | private bool $trimString = false, |
||
37 | ) { |
||
38 | } |
||
39 | |||
40 | /** |
||
41 | * @param mixed $value The validated value. |
||
42 | * @param bool $isAttributeMissing A flag defining whether the attribute is missing (not used / not passed at all). |
||
43 | * |
||
44 | * @return bool Whether the validated value is considered empty. |
||
45 | */ |
||
46 | public function __invoke(mixed $value, bool $isAttributeMissing): bool |
||
47 | { |
||
48 | if ($isAttributeMissing || $value === null) { |
||
49 | return true; |
||
50 | } |
||
51 | |||
52 | if (is_string($value)) { |
||
53 | if ($this->trimString) { |
||
54 | $value = trim($value); |
||
55 | } |
||
56 | |||
57 | return $value === ''; |
||
58 | } |
||
59 | |||
60 | if (is_iterable($value)) { |
||
61 | foreach ($value as $_item) { |
||
62 | return false; |
||
63 | } |
||
64 | |||
65 | return true; |
||
66 | } |
||
67 | |||
68 | return false; |
||
69 | } |
||
70 | } |
||
71 |