Passed
Pull Request — master (#481)
by
unknown
02:48
created

ValidationContext::requireValidator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use RuntimeException;
8
use Yiisoft\Arrays\ArrayHelper;
9
10
/**
11
 * Validation context that might be taken into account when performing validation.
12
 *
13
 * @psalm-import-type RulesType from ValidatorInterface
14
 */
15
final class ValidationContext
16
{
17
    private ?ValidatorInterface $validator = null;
18
19 827
    /**
20
     * @var mixed The raw validated data.
21
     */
22
    private mixed $rawData = null;
23
24
    /**
25
     * @var DataSetInterface|null Data set the attribute belongs to. Null if data set not set.
26
     */
27 43
    private ?DataSetInterface $dataSet = null;
28
29 43
    /**
30
     * @var string|null Validated attribute name. Null if a single value is validated.
31
     */
32
    private ?string $attribute = null;
33
34
    private ?AttributeTranslatorInterface $defaultAttributeTranslator = null;
35 11
36
    /**
37 11
     * @param array $parameters Arbitrary parameters.
38
     */
39
    public function __construct(
40
        private array $parameters = [],
41
        private ?AttributeTranslatorInterface $attributeTranslator = null,
42
    ) {
43 503
    }
44
45 503
    public function setContextDataOnce(
46
        ValidatorInterface $validator,
47
        AttributeTranslatorInterface $attributeTranslator,
48
        mixed $rawData
49
    ): self {
50
        if ($this->validator !== null) {
51 140
            return $this;
52
        }
53 140
54 140
        $this->validator = $validator;
55
        $this->defaultAttributeTranslator = $attributeTranslator;
56
        $this->rawData = $rawData;
57
58
        return $this;
59
    }
60 3
61
    public function setAttributeTranslator(?AttributeTranslatorInterface $attributeTranslator): self
62 3
    {
63
        $this->attributeTranslator = $attributeTranslator;
64
        return $this;
65
    }
66
67
    /**
68
     * Validate data in current context.
69
     *
70
     * @param mixed $data Data set to validate. If {@see RulesProviderInterface} instance provided and rules are
71
     * not specified explicitly, they are read from the {@see RulesProviderInterface::getRules()}.
72
     * @param callable|iterable|object|string|null $rules Rules to apply. If specified, rules are not read from data set
73
     * even if it is an instance of {@see RulesProviderInterface}.
74
     *
75 6
     * @psalm-param RulesType $rules
76
     */
77 6
    public function validate(mixed $data, callable|iterable|object|string|null $rules = null): Result
78
    {
79
        $this->requireValidator();
80 503
81
        $currentDataSet = $this->dataSet;
82 503
        $currentAttribute = $this->attribute;
83
84
        $result = $this->validator->validate($data, $rules, $this);
0 ignored issues
show
Bug introduced by
The method validate() 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

84
        /** @scrutinizer ignore-call */ 
85
        $result = $this->validator->validate($data, $rules, $this);

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...
85 786
86
        $this->dataSet = $currentDataSet;
87 786
        $this->attribute = $currentAttribute;
88
89
        return $result;
90
    }
91
92
    /**
93
     * @return mixed The raw validated data.
94
     */
95
    public function getRawData(): mixed
96
    {
97
        $this->requireValidator();
98
        return $this->rawData;
99
    }
100
101
    /**
102
     * @return DataSetInterface Data set the attribute belongs to.
103
     */
104
    public function getDataSet(): DataSetInterface
105
    {
106
        if ($this->dataSet === null) {
107
            throw new RuntimeException('Data set in validation context is not set.');
108
        }
109
110
        return $this->dataSet;
111
    }
112
113
    /**
114
     * @param DataSetInterface $dataSet Data set the attribute belongs to.
115
     */
116
    public function setDataSet(DataSetInterface $dataSet): self
117
    {
118
        $this->dataSet = $dataSet;
119
        return $this;
120
    }
121
122
    /**
123
     * @return string|null Validated attribute name. Null if a single value is validated.
124
     */
125
    public function getAttribute(): ?string
126
    {
127
        return $this->attribute;
128
    }
129
130
    public function getTranslatedAttribute(): ?string
131
    {
132
        if ($this->attribute === null) {
133
            return null;
134
        }
135
136
        if ($this->attributeTranslator !== null) {
137
            return $this->attributeTranslator->translate($this->attribute);
138
        }
139
140
        if ($this->defaultAttributeTranslator !== null) {
141
            return $this->defaultAttributeTranslator->translate($this->attribute);
142
        }
143
144
        return $this->attribute;
145
    }
146
147
    /**
148
     * @param string|null $attribute Validated attribute name. Null if a single value is validated.
149
     */
150
    public function setAttribute(?string $attribute): self
151
    {
152
        $this->attribute = $attribute;
153
        return $this;
154
    }
155
156
    /**
157
     * Get named parameter.
158
     *
159
     * @param string $key Parameter name.
160
     * @param mixed $default Default value to return in case parameter with a given name does not exist.
161
     *
162
     * @return mixed Parameter value.
163
     *
164
     * @see ArrayHelper::getValue()
165
     */
166
    public function getParameter(string $key, mixed $default = null): mixed
167
    {
168
        return ArrayHelper::getValue($this->parameters, $key, $default);
169
    }
170
171
    public function setParameter(string $key, mixed $value): self
172
    {
173
        $this->parameters[$key] = $value;
174
        return $this;
175
    }
176
177
    public function isAttributeMissing(): bool
178
    {
179
        return $this->attribute !== null && !$this->getDataSet()->hasAttribute($this->attribute);
180
    }
181
182
    /**
183
     * @psalm-assert ValidatorInterface $this->validator
184
     */
185
    private function requireValidator(): void
186
    {
187
        if ($this->validator === null) {
188
            throw new RuntimeException('Validator in validation context is not set.');
189
        }
190
    }
191
}
192