1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Arrays\ArrayHelper; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Validation context that rule may take into account when performing validation. |
11
|
|
|
*/ |
12
|
|
|
final class ValidationContext |
13
|
|
|
{ |
14
|
|
|
private ?DataSetInterface $dataSet; |
15
|
|
|
private ?string $attribute = null; |
16
|
|
|
private array $parameters = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param DataSetInterface|null $dataSet Data set the attribute belongs to. Null if a single value is validated. |
20
|
|
|
* @param string|null $attribute Validated attribute name. Null if a single value is validated. |
21
|
|
|
* @param array $parameters Arbitrary parameters. |
22
|
|
|
*/ |
23
|
20 |
|
public function __construct( |
24
|
|
|
?DataSetInterface $dataSet = null, |
25
|
|
|
?string $attribute = null, |
26
|
|
|
array $parameters = [] |
27
|
|
|
) { |
28
|
20 |
|
$this->dataSet = $dataSet; |
29
|
20 |
|
$this->attribute = $attribute; |
30
|
20 |
|
$this->parameters = $parameters; |
31
|
20 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @return DataSetInterface|null Data set the attribute belongs to. Null if a single value is validated. |
35
|
|
|
*/ |
36
|
2 |
|
public function getDataSet(): ?DataSetInterface |
37
|
|
|
{ |
38
|
2 |
|
return $this->dataSet; |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @return string|null Validated attribute name. Null if a single value is validated. |
43
|
|
|
*/ |
44
|
3 |
|
public function getAttribute(): ?string |
45
|
|
|
{ |
46
|
3 |
|
return $this->attribute; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param string|null $attribute Validated attribute name. Null if a single value is validated. |
51
|
|
|
* |
52
|
|
|
* @return self |
53
|
|
|
*/ |
54
|
2 |
|
public function withAttribute(?string $attribute): self |
55
|
|
|
{ |
56
|
2 |
|
$new = clone $this; |
57
|
2 |
|
$new->attribute = $attribute; |
58
|
2 |
|
return $new; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** |
62
|
|
|
* @return array Arbitrary parameters. |
63
|
|
|
*/ |
64
|
3 |
|
public function getParameters(): array |
65
|
|
|
{ |
66
|
3 |
|
return $this->parameters; |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
/** |
70
|
|
|
* Get named parameter. |
71
|
|
|
* |
72
|
|
|
* @param string $key Parameter name. |
73
|
|
|
* @param mixed $default Default value to return in case parameter with a given name does not exist. |
74
|
|
|
* |
75
|
|
|
* @return mixed Parameter value. |
76
|
|
|
* |
77
|
|
|
* @see ArrayHelper::getValue() |
78
|
|
|
*/ |
79
|
15 |
|
public function getParameter(string $key, $default = null) |
80
|
|
|
{ |
81
|
15 |
|
return ArrayHelper::getValue($this->parameters, $key, $default); |
82
|
|
|
} |
83
|
|
|
|
84
|
14 |
|
public function setParameter(string $key, $value): void |
85
|
|
|
{ |
86
|
14 |
|
$this->parameters[$key] = $value; |
87
|
14 |
|
} |
88
|
|
|
} |
89
|
|
|
|