SkipOnEmptyNormalizer   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 31
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
wmc 5

1 Method

Rating   Name   Duplication   Size   Complexity  
A normalize() 0 15 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Helper;
6
7
use InvalidArgumentException;
8
use Yiisoft\Validator\EmptyCondition\NeverEmpty;
9
use Yiisoft\Validator\EmptyCondition\WhenEmpty;
10
use Yiisoft\Validator\SkipOnEmptyInterface;
11
12
use function is_callable;
13
14
/**
15
 * A helper class used to normalize different types of "skip on empty" values including shortcuts to a callable
16
 * ({@see SkipOnEmptyInterface}).
17
 *
18 834
 * @internal
19
 */
20 834
final class SkipOnEmptyNormalizer
21 801
{
22
    /**
23
     * Normalizes different types of "skip on empty" values including shortcuts to a callable:
24 742
     *
25 9
     * - `null` and `false` values are normalized to {@see NeverEmpty}.
26
     * - `true` value is normalized to {@see WhenEmpty}.
27
     * - A callable is left as is.
28 739
     * - Other types are rejected causing the exception.
29 738
     *
30
     * @param mixed $skipOnEmpty Raw "skip on empty" value of any type.
31
     *
32 1
     * @throws InvalidArgumentException If the type of {@see $skipOnEmpty} is not valid.
33
     *
34
     * @return callable An empty condition as a callable.
35
     */
36
    public static function normalize(mixed $skipOnEmpty): callable
37
    {
38
        if ($skipOnEmpty === false || $skipOnEmpty === null) {
39
            return new NeverEmpty();
40
        }
41
42
        if ($skipOnEmpty === true) {
43
            return new WhenEmpty();
44
        }
45
46
        if (is_callable($skipOnEmpty)) {
47
            return $skipOnEmpty;
48
        }
49
50
        throw new InvalidArgumentException('$skipOnEmpty must be a null, a boolean or a callable.');
51
    }
52
}
53