Passed
Pull Request — master (#54)
by
unknown
01:37
created

Rule::skipErrorMode()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0625

Importance

Changes 0
Metric Value
eloc 7
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 11
cc 2
rs 10
ccs 6
cts 8
cp 0.75
crap 2.0625
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
    const SKIP_ON_ANY_ERROR = 1;
15
    const SKIP_ON_ATTRIBUTE_ERROR = 2;
16
17
    private ?TranslatorInterface $translator = null;
18
    private ?string $translationDomain = null;
19
    private ?string $translationLocale = null;
20
    private bool $skipOnEmpty = false;
21
    private bool $skipOnError = true;
22
    private int $skipErrorMode = self::SKIP_ON_ATTRIBUTE_ERROR;
23
24
    /**
25
     * Validates the value
26
     *
27
     * @param mixed $value value to be validated
28
     * @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation
29
     * @return Result
30
     */
31 121
    final public function validate($value, DataSetInterface $dataSet = null): Result
32
    {
33 121
        if ($this->skipOnEmpty && $this->isEmpty($value)) {
34
            return new Result();
35
        }
36
37 121
        return $this->validateValue($value, $dataSet);
38
    }
39
40
    /**
41
     * Validates the value. The method should be implemented by concrete validation rules.
42
     *
43
     * @param mixed $value value to be validated
44
     * @param DataSetInterface|null $dataSet optional data set that could be used for contextual validation
45
     * @return Result
46
     */
47
    abstract protected function validateValue($value, DataSetInterface $dataSet = null): Result;
48
49
    public function withTranslator(TranslatorInterface $translator): self
50
    {
51
        $new = clone $this;
52
        $new->translator = $translator;
53
        return $new;
54
    }
55
56
    public function withTranslationDomain(string $translation): self
57
    {
58
        $new = clone $this;
59
        $new->translationDomain = $translation;
60
        return $new;
61
    }
62
63
    public function withTranslationLocale(string $locale): self
64
    {
65
        $new = clone $this;
66
        $new->translationLocale = $locale;
67
        return $new;
68
    }
69
70 101
    public function translateMessage(string $message, array $arguments = []): string
71
    {
72 101
        if ($this->translator === null) {
73 101
            return $this->formatMessage($message, $arguments);
74
        }
75
76
        return $this->translator->translate(
77
            $message,
78
            $arguments,
79
            $this->translationDomain ?? 'validators',
80
            $this->translationLocale
81
        );
82
    }
83
84 8
    public function getSkipOnError(): bool
85
    {
86 8
        return $this->skipOnError;
87
    }
88
89 8
    public function getSkipErrorMode(): int
90
    {
91 8
        return $this->skipErrorMode;
92
    }
93
94 2
    public function skipOnError(bool $value): self
95
    {
96 2
        $new = clone $this;
97 2
        $new->skipOnError = $value;
98 2
        return $new;
99
    }
100
101 1
    public function skipErrorMode(int $mode): self
102
    {
103 1
        $modes = [self::SKIP_ON_ANY_ERROR, self::SKIP_ON_ATTRIBUTE_ERROR];
104 1
        if (!in_array($mode, $modes, true)) {
105
            throw new \InvalidArgumentException(
106
                sprintf('Unknown mode given %s, supported modes %s.', $mode, implode(', ', $modes))
107
            );
108
        }
109 1
        $new = clone $this;
110 1
        $new->skipErrorMode = $mode;
111 1
        return $new;
112
    }
113
114
    /**
115
     * @param bool $value if validation should be skipped if value validated is empty
116
     * @return self
117
     */
118 1
    public function skipOnEmpty(bool $value): self
119
    {
120 1
        $new = clone $this;
121 1
        $new->skipOnEmpty = $value;
122 1
        return $new;
123
    }
124
125 101
    private function formatMessage(string $message, array $arguments = []): string
126
    {
127 101
        $replacements = [];
128 101
        foreach ($arguments as $key => $value) {
129 38
            if (is_array($value)) {
130 1
                $value = 'array';
131 37
            } elseif (is_object($value)) {
132 2
                $value = 'object';
133 35
            } elseif (is_resource($value)) {
134 1
                $value = 'resource';
135
            }
136 38
            $replacements['{' . $key . '}'] = $value;
137
        }
138 101
        return strtr($message, $replacements);
139
    }
140
141
    /**
142
     * Checks if the given value is empty.
143
     * A value is considered empty if it is null, an empty array, or an empty string.
144
     * Note that this method is different from PHP empty(). It will return false when the value is 0.
145
     * @param mixed $value the value to be checked
146
     * @return bool whether the value is empty
147
     */
148 3
    protected function isEmpty($value): bool
149
    {
150 3
        return $value === null || $value === [] || $value === '';
151
    }
152
}
153