AbstractModel::offsetSet()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 6
ccs 0
cts 0
cp 0
crap 6
rs 10
1
<?php
2
3
namespace Guillermoandrae\Models;
4
5
use Guillermoandrae\Common\DumpableTrait;
6
use Guillermoandrae\Common\AbstractAggregate;
7
8
abstract class AbstractModel implements ModelInterface
9
{
10
    use DumpableTrait;
11 1
12
    /**
13 1
     * @var array
14
     */
15
    protected array $data = [];
16
17
    /**
18
     * Constructor.
19
     *
20
     * @param mixed $data
21
     */
22
    public function __construct(mixed $data = null)
23
    {
24
        if (is_array($data)) {
25
            foreach ($data as $key => $value) {
26
                $this->data[$key] = $value;
27
            }
28
        }
29
    }
30
31
    final public function offsetExists(mixed $offset): bool
32
    {
33
        return isset($this->data[$offset]);
34
    }
35
36
    final public function offsetGet(mixed $offset): mixed
37
    {
38
        return $this->offsetExists($offset) ? $this->data[$offset] : null;
39
    }
40
41
    final public function offsetSet(mixed $offset, mixed $value): void
42
    {
43
        if (is_null($offset)) {
44
            $this->data[] = $value;
45
        } else {
46
            $this->data[$offset] = $value;
47
        }
48
    }
49
50
    final public function offsetUnset(mixed $offset): void
51
    {
52
        unset($this->data[$offset]);
53
    }
54
55
    final public function toJson(): string
56
    {
57
        return json_encode($this->toArray());
58
    }
59
60
    public function toArray(): array
61
    {
62
        return $this->data;
63
    }
64
}
65