1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\DataSet; |
6
|
|
|
|
7
|
|
|
use Yiisoft\Validator\DataSetInterface; |
|
|
|
|
8
|
|
|
|
9
|
|
|
use Yiisoft\Validator\Helper\DataSetNormalizer; |
10
|
|
|
|
11
|
|
|
use function array_key_exists; |
12
|
|
|
|
13
|
174 |
|
/** |
14
|
|
|
* A data set for storing data as an associative array, where keys are attribute names and values are their |
15
|
|
|
* corresponding values. An example of usage: |
16
|
|
|
* |
17
|
102 |
|
* ```php |
18
|
|
|
* $dataSet = new ArrayDataSet(['name' => 'John', 'age' => 18]); |
19
|
102 |
|
* ``` |
20
|
|
|
* |
21
|
|
|
* When using validator, there is no need to wrap your data manually. Array will be automatically wrapped with |
22
|
113 |
|
* {@see ArrayDataSet} by {@see DataSetNormalizer} during validation. |
23
|
|
|
*/ |
24
|
113 |
|
final class ArrayDataSet implements DataSetInterface |
25
|
|
|
{ |
26
|
|
|
public function __construct( |
27
|
98 |
|
/** |
28
|
|
|
* @var array A mapping between attribute names and their values. |
29
|
98 |
|
*/ |
30
|
|
|
private array $data = [], |
31
|
|
|
) { |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Returns an attribute value by its name. |
36
|
|
|
* |
37
|
|
|
* Note that in case of non-existing attribute a default `null` value is returned. If you need to check the presence |
38
|
|
|
* of attribute or return a different default value, use {@see hasAttribute()} instead. |
39
|
|
|
* |
40
|
|
|
* @param string $attribute Attribute name. |
41
|
|
|
* |
42
|
|
|
* @return mixed Attribute value. |
43
|
|
|
*/ |
44
|
|
|
public function getAttributeValue(string $attribute): mixed |
45
|
|
|
{ |
46
|
|
|
return $this->data[$attribute] ?? null; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* A getter for {@see $data} property. Returns the validated data as a whole in a form of array. |
51
|
|
|
* |
52
|
|
|
* @return array A mapping between attribute names and their values. |
53
|
|
|
*/ |
54
|
|
|
public function getData(): ?array |
55
|
|
|
{ |
56
|
|
|
return $this->data; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
public function getSource(): array |
60
|
|
|
{ |
61
|
|
|
return $this->data; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Whether this data set has the attribute with a given name. Note that this means existence only and attributes |
66
|
|
|
* with empty values are treated as present too. |
67
|
|
|
* |
68
|
|
|
* @param string $attribute Attribute name. |
69
|
|
|
* |
70
|
|
|
* @return bool Whether the attribute exists: `true` - exists and `false` - otherwise. |
71
|
|
|
*/ |
72
|
|
|
public function hasAttribute(string $attribute): bool |
73
|
|
|
{ |
74
|
|
|
return array_key_exists($attribute, $this->data); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|