Passed
Push — master ( 955c83...94d693 )
by Alexander
02:18
created

Rule::formatter()   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
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
/**
8
 * Rule represents a single value validation rule.
9
 */
10
abstract class Rule
11
{
12
    private ?FormatterInterface $formatter = null;
13
    private ?string $translationDomain = null;
0 ignored issues
show
introduced by
The private property $translationDomain is not used, and could be removed.
Loading history...
14
    private ?string $translationLocale = null;
0 ignored issues
show
introduced by
The private property $translationLocale is not used, and could be removed.
Loading history...
15
    private bool $skipOnEmpty = false;
16
    private bool $skipOnError = true;
17
18
    /**
19
     * @var callable|null
20
     */
21
    private $when = null;
22
23
    /**
24
     * Validates the value
25
     *
26
     * @param mixed $value value to be validated
27
     * @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation
28
     * @param bool $previousRulesErrored set to true if rule is part of a group of rules and one of the previous validations failed
29
     *
30
     * @return Result
31
     */
32 137
    final public function validate($value, DataSetInterface $dataSet = null, bool $previousRulesErrored = false): Result
33
    {
34 137
        if ($this->skipOnEmpty && $this->isEmpty($value)) {
35
            return new Result();
36
        }
37
38
        if (
39 137
          ($this->skipOnError && $previousRulesErrored) ||
40 137
          (is_callable($this->when) && !($this->when)($value, $dataSet))
41
        ) {
42 6
            return new Result();
43
        }
44
45 137
        return $this->validateValue($value, $dataSet);
46
    }
47
48
    /**
49
     * Validates the value. The method should be implemented by concrete validation rules.
50
     *
51
     * @param mixed $value value to be validated
52
     * @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation
53
     *
54
     * @return Result
55
     */
56
    abstract protected function validateValue($value, DataSetInterface $dataSet = null): Result;
57
58 1
    public function formatter(FormatterInterface $formatter): self
59
    {
60 1
        $new = clone $this;
61 1
        $new->formatter = $formatter;
62 1
        return $new;
63
    }
64
65 169
    protected function formatMessage(string $message, array $parameters = []): string
66
    {
67 169
        if ($this->formatter === null) {
68 168
            $this->formatter = new Formatter();
69
        }
70
71 169
        return $this->formatter->format(
0 ignored issues
show
Bug introduced by
The method format() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

71
        return $this->formatter->/** @scrutinizer ignore-call */ format(

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
72 169
            $message,
73
            $parameters
74
        );
75
    }
76
77
    /**
78
     * Add a PHP callable whose return value determines whether this rule should be applied.
79
     * By default rule will be always applied.
80
     *
81
     * The signature of the callable should be `function ($value, DataSetInterface $dataSet): bool`, where $value and $dataSet
82
     * refer to the value validated and the data set in which context it is validated. The callable should return
83
     * a boolean value.
84
     *
85
     * The following example will enable the validator only when the country currently selected is USA:
86
     *
87
     * ```php
88
     * function ($value, DataSetInterface $dataSet) {
89
         return $dataSet->getAttributeValue('country') === Country::USA;
90
     }
91
     * ```
92
     *
93
     * @param callable $callback
94
     *
95
     * @return $this
96
     */
97 1
    public function when(callable $callback): self
98
    {
99 1
        $new = clone $this;
100 1
        $new->when = $callback;
101 1
        return $new;
102
    }
103
104 3
    public function skipOnError(bool $value): self
105
    {
106 3
        $new = clone $this;
107 3
        $new->skipOnError = $value;
108 3
        return $new;
109
    }
110
111
    /**
112
     * @param bool $value if validation should be skipped if value validated is empty
113
     *
114
     * @return self
115
     */
116 1
    public function skipOnEmpty(bool $value): self
117
    {
118 1
        $new = clone $this;
119 1
        $new->skipOnEmpty = $value;
120 1
        return $new;
121
    }
122
123
    /**
124
     * Checks if the given value is empty.
125
     * A value is considered empty if it is null, an empty array, or an empty string.
126
     * Note that this method is different from PHP empty(). It will return false when the value is 0.
127
     *
128
     * @param mixed $value the value to be checked
129
     *
130
     * @return bool whether the value is empty
131
     */
132 10
    protected function isEmpty($value): bool
133
    {
134 10
        return $value === null || $value === [] || $value === '';
135
    }
136
137
    /**
138
     * Get name of the rule to be used when rule is converted to array.
139
     * By default it returns base name of the class, first letter in lowercase.
140
     *
141
     * @return string
142
     */
143 20
    public function getName(): string
144
    {
145 20
        $className = static::class;
146 20
        return lcfirst(substr($className, strrpos($className, '\\') + 1));
147
    }
148
149
    /**
150
     * Returns rule options as array.
151
     *
152
     * @return array
153
     */
154 57
    public function getOptions(): array
155
    {
156
        return [
157 57
            'skipOnEmpty' => $this->skipOnEmpty,
158 57
            'skipOnError' => $this->skipOnError,
159
        ];
160
    }
161
}
162