Completed
Push — master ( af699b...936638 )
by Maxim
04:45
created

TraitData::__get()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
nop 1
1
<?php
2
3
namespace WebComplete\core\utils\traits;
4
5
use function WebComplete\core\utils\typecast\cast;
6
7
trait TraitData
8
{
9
10
    private $data = [];
11
12
    /**
13
     * @return array
14
     */
15
    abstract public static function fields(): array;
16
17
18
    /**
19
     * @param array $data
20
     * @param bool $update
21
     */
22
    public function mapFromArray(array $data, bool $update = false)
23
    {
24
        if (!$update) {
25
            $this->data = [];
26
        }
27
28
        foreach ($data as $field => $value) {
29
            $this->set($field, $value);
30
        }
31
    }
32
33
    /**
34
     * @return array
35
     */
36
    public function mapToArray(): array
37
    {
38
        $result = [];
39
        $fields = \array_keys(static::fields());
40
        foreach ($fields as $field) {
41
            $result[$field] = $this->get($field);
42
        }
43
44
        return $result;
45
    }
46
47
    /**
48
     * @param $name
49
     *
50
     * @return mixed|null
51
     */
52
    public function __get($name)
53
    {
54
        return $this->get($name);
55
    }
56
57
    /**
58
     * @param $name
59
     * @param $value
60
     */
61
    public function __set($name, $value)
62
    {
63
        $this->set($name, $value);
64
    }
65
66
    /**
67
     * @param $name
68
     *
69
     * @return bool
70
     */
71
    public function __isset($name)
72
    {
73
        return isset($this->data[$name]);
74
    }
75
76
    /**
77
     * @param string $field
78
     * @param $value
79
     */
80
    public function set(string $field, $value)
81
    {
82
        $fields = static::fields();
83
        if (isset($fields[$field])) {
84
            $this->data[$field] = cast($value, $fields[$field]);
85
        }
86
    }
87
88
    /**
89
     * @param string $field
90
     * @param null $default
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $default is correct as it would always require null to be passed?
Loading history...
91
     *
92
     * @return mixed|null
93
     */
94
    public function get(string $field, $default = null)
95
    {
96
        return $this->data[$field] ?? $default;
97
    }
98
99
    /**
100
     * @param string $field
101
     *
102
     * @return bool
103
     */
104
    public function has(string $field): bool
105
    {
106
        return isset(static::fields()[$field]);
107
    }
108
}
109