Completed
Push — master ( 36e3eb...0b3b40 )
by Maxim
02:35
created

AbstractEntity::setField()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
namespace WebComplete\core\entity;
4
5
use function WebComplete\core\utils\typecast\cast;
0 ignored issues
show
introduced by
The function WebComplete\core\utils\typecast\cast was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
6
7
abstract class AbstractEntity
8
{
9
10
    protected $id;
11
12
    private $data = [];
13
14
    /**
15
     * @return array
16
     */
17
    abstract public static function fields(): array;
18
19
    /**
20
     * @return int|string|null
21
     */
22
    public function getId()
23
    {
24
        return $this->id;
25
    }
26
27
    /**
28
     * @param int|string $id
29
     */
30
    public function setId($id)
31
    {
32
        $this->id = $id;
33
    }
34
35
    /**
36
     * @param array $data
37
     * @param bool $update
38
     */
39
    public function mapFromArray(array $data, bool $update = false)
40
    {
41
        if (!$update) {
42
            $this->data = [];
43
        }
44
45
        foreach ($data as $field => $value) {
46
            $this->setField($field, $value);
47
        }
48
    }
49
50
    /**
51
     * @return array
52
     */
53
    public function mapToArray(): array
54
    {
55
        $result = [
56
            'id' => $this->getId()
57
        ];
58
        $fields = \array_keys(static::fields());
59
        foreach ($fields as $field) {
60
            $result[$field] = $this->getField($field);
61
        }
62
63
        return $result;
64
    }
65
66
    /**
67
     * @param $name
68
     * @param $value
69
     */
70
    protected function setField($name, $value)
71
    {
72
        $fields = static::fields();
73
        if (isset($fields[$name])) {
74
            $this->data[$name] = cast($value, $fields[$name]);
75
        }
76
    }
77
78
    /**
79
     * @param $name
80
     * @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...
81
     *
82
     * @return mixed|null
83
     */
84
    protected function getField($name, $default = null)
85
    {
86
        return $this->data[$name] ?? $default;
87
    }
88
}
89