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