Passed
Pull Request — master (#464)
by Alexander
02:35
created

ArrayDataSet   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
dl 0
loc 51
ccs 3
cts 3
cp 1
rs 10
c 1
b 0
f 0
wmc 5

5 Methods

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