Passed
Pull Request — master (#41)
by Alexander
01:57 queued 36s
created

Rule::skipOnEmpty()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
4
namespace Yiisoft\Validator;
5
6
/**
7
 * Rule represents a single value validation rule.
8
 */
9
abstract class Rule
10
{
11
    private bool $skipOnEmpty = false;
12
13
    /**
14
     * @param mixed $value
15
     * @param DataSetInterface|null $dataSet
16
     * @return Result
17
     */
18 115
    final public function validate($value, DataSetInterface $dataSet = null): Result
19
    {
20 115
        if ($this->skipOnEmpty && $this->isEmpty($value)) {
21
            return new Result();
22
        }
23
24 115
        return $this->validateValue($value, $dataSet);
25
    }
26
27
    abstract protected function validateValue($value, DataSetInterface $dataSet = null): Result;
28
29 101
    protected function formatMessage(string $message, array $arguments = []): string
30
    {
31 101
        $replacements = [];
32 101
        foreach ($arguments as $key => $value) {
33 32
            if (is_array($value)) {
34 1
                $value = 'array';
35 31
            } elseif (is_object($value)) {
36 2
                $value = 'object';
37 29
            } elseif (is_resource($value)) {
38 1
                $value = 'resource';
39
            }
40
41 32
            $replacements['{' . $key . '}'] = $value;
42
        }
43
44
        // TODO: move it to upper level and make it configurable?
45 101
        return strtr($message, $replacements);
46
    }
47
48
    /**
49
     * @param bool $value
50
     * @return self
51
     */
52 1
    public function skipOnEmpty(bool $value): self
53
    {
54 1
        $new = clone $this;
55 1
        $new->skipOnEmpty = $value;
56 1
        return $new;
57
    }
58
59
    /**
60
     * Checks if the given value is empty.
61
     * A value is considered empty if it is null, an empty array, or an empty string.
62
     * Note that this method is different from PHP empty(). It will return false when the value is 0.
63
     * @param mixed $value the value to be checked
64
     * @return bool whether the value is empty
65
     */
66 3
    protected function isEmpty($value): bool
67
    {
68 3
        return $value === null || $value === [] || $value === '';
69
    }
70
}
71