Passed
Pull Request — master (#55)
by Alexander
01:42
created

Rule::when()   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 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 10
ccs 4
cts 4
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use Yiisoft\I18n\TranslatorInterface;
0 ignored issues
show
Bug introduced by
The type Yiisoft\I18n\TranslatorInterface was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
/**
10
 * Rule represents a single value validation rule.
11
 */
12
abstract class Rule
13
{
14
    private ?TranslatorInterface $translator = null;
15
    private ?string $translationDomain = null;
16
    private ?string $translationLocale = null;
17
    private bool $skipOnEmpty = false;
18
    private bool $skipOnError = true;
19
20
    /**
21
     * @var callable|null
22
     */
23
    private $when = null;
24
25
    /**
26
     * Validates the value
27
     *
28
     * @param mixed $value value to be validated
29
     * @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation
30
     * @param bool $previousRulesErrored set to true if rule is part of a group of rules and one of the previous validations failed
31
     * @return Result
32
     */
33 121
    final public function validate($value, DataSetInterface $dataSet = null, bool $previousRulesErrored = false): Result
34
    {
35 121
        if ($this->skipOnEmpty && $this->isEmpty($value)) {
36
            return new Result();
37
        }
38
39
        if (
40 121
          ($this->skipOnError && $previousRulesErrored) ||
41 121
          (is_callable($this->when) && !call_user_func($this->when, $value, $dataSet))
42
        ) {
43 3
            return new Result();
44
        }
45
46 121
        return $this->validateValue($value, $dataSet);
47
    }
48
49
    /**
50
     * Validates the value. The method should be implemented by concrete validation rules.
51
     *
52
     * @param mixed $value value to be validated
53
     * @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation
54
     * @return Result
55
     */
56
    abstract protected function validateValue($value, DataSetInterface $dataSet = null): Result;
57
58
    public function translator(TranslatorInterface $translator): self
59
    {
60
        $new = clone $this;
61
        $new->translator = $translator;
62
        return $new;
63
    }
64
65
    public function translationDomain(string $translation): self
66
    {
67
        $new = clone $this;
68
        $new->translationDomain = $translation;
69
        return $new;
70
    }
71
72
    public function translationLocale(string $locale): self
73
    {
74
        $new = clone $this;
75
        $new->translationLocale = $locale;
76
        return $new;
77
    }
78
79 101
    public function translateMessage(string $message, array $arguments = []): string
80
    {
81 101
        if ($this->translator === null) {
82 101
            return $this->formatMessage($message, $arguments);
83
        }
84
85
        return $this->translator->translate(
86
            $message,
87
            $arguments,
88
            $this->translationDomain ?? 'validators',
89
            $this->translationLocale
90
        );
91
    }
92
93
    /**
94
     * Add a PHP callable whose return value determines whether this rule should be applied.
95
     * By default rule will be always applied.
96
     *
97
     * The signature of the callable should be `function ($value, DataSetInterface $dataSet): bool`, where $value and $dataSet
98
     * refer to the value validated and the data set in which context it is validated. The callable should return
99
     * a boolean value.
100
     *
101
     * The following example will enable the validator only when the country currently selected is USA:
102
     *
103
     * ```php
104
     * function ($value, DataSetInterface $dataSet) {
105
         return $dataSet->getAttributeValue('country') === Country::USA;
106
     }
107
     * ```
108
     *
109
     * @param callable $callback
110
     * @return $this
111
     */
112 1
    public function when(callable $callback): self
113
    {
114 1
        $new = clone $this;
115 1
        $new->when = $callback;
116 1
        return $new;
117
    }
118
119 2
    public function skipOnError(bool $value): self
120
    {
121 2
        $new = clone $this;
122 2
        $new->skipOnError = $value;
123 2
        return $new;
124
    }
125
126
    /**
127
     * @param bool $value if validation should be skipped if value validated is empty
128
     * @return self
129
     */
130 1
    public function skipOnEmpty(bool $value): self
131
    {
132 1
        $new = clone $this;
133 1
        $new->skipOnEmpty = $value;
134 1
        return $new;
135
    }
136
137 101
    private function formatMessage(string $message, array $arguments = []): string
138
    {
139 101
        $replacements = [];
140 101
        foreach ($arguments as $key => $value) {
141 38
            if (is_array($value)) {
142 1
                $value = 'array';
143 37
            } elseif (is_object($value)) {
144 2
                $value = 'object';
145 35
            } elseif (is_resource($value)) {
146 1
                $value = 'resource';
147
            }
148 38
            $replacements['{' . $key . '}'] = $value;
149
        }
150 101
        return strtr($message, $replacements);
151
    }
152
153
    /**
154
     * Checks if the given value is empty.
155
     * A value is considered empty if it is null, an empty array, or an empty string.
156
     * Note that this method is different from PHP empty(). It will return false when the value is 0.
157
     * @param mixed $value the value to be checked
158
     * @return bool whether the value is empty
159
     */
160 3
    protected function isEmpty($value): bool
161
    {
162 3
        return $value === null || $value === [] || $value === '';
163
    }
164
}
165