SkipOnEmptyNormalizer::normalize()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 30

Importance

Changes 0
Metric Value
cc 5
eloc 7
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 15
ccs 0
cts 0
cp 0
crap 30
rs 9.6111
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