Passed
Pull Request — master (#300)
by Sergei
02:36
created

BeforeValidationTrait::getSkipOnEmptyCallback()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 0
crap 1
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\SkipOnEmpty;
10
use Yiisoft\Validator\ValidationContext;
11
12
use function is_callable;
13
14
trait BeforeValidationTrait
15
{
16
    /**
17
     * @var callable|null
18
     */
19
    private $skipOnEmptyCallback = null;
20
21 99
    public function shouldSkipOnEmpty(mixed $validatedValue): bool
22
    {
23 99
        return $this->skipOnEmptyCallback !== null && ($this->skipOnEmptyCallback)($validatedValue);
24
    }
25
26 138
    protected function setSkipOnEmptyCallback(mixed $skipOnEmpty = false): void
27
    {
28 138
        if ($skipOnEmpty === false) {
29 123
            $this->skipOnEmptyCallback = null;
30 123
            return;
31
        }
32
33 19
        if ($skipOnEmpty === true) {
34 6
            $this->skipOnEmptyCallback = new SkipOnEmpty();
35 6
            return;
36
        }
37
38 14
        if (!is_callable($skipOnEmpty)) {
39
            throw new InvalidArgumentException('$skipOnEmpty must be a boolean or a callable.');
40
        }
41
42 14
        $this->skipOnEmptyCallback = $skipOnEmpty;
43
    }
44
45 15
    public function skipOnEmpty(bool|callable $value): self
46
    {
47 15
        $new = clone $this;
48 15
        $new->setSkipOnEmptyCallback($value);
49 15
        return $new;
50
    }
51
52 93
    public function shouldSkipOnError(): bool
53
    {
54 93
        return $this->skipOnError;
55
    }
56
57
    /**
58
     * @psalm-return Closure(mixed, ValidationContext):bool|null
59
     *
60
     * @return Closure|null
61
     */
62 92
    public function getWhen(): ?Closure
63
    {
64 92
        return $this->when;
65
    }
66
}
67