AbstractEntity   A
last analyzed

Complexity

Total Complexity 12

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 47
rs 10
c 0
b 0
f 0
wmc 12

5 Methods

Rating   Name   Duplication   Size   Complexity  
A toArray() 0 14 4
A __construct() 0 4 2
A hydrate() 0 10 4
A jsonSerialize() 0 3 1
A getSetterMethod() 0 3 1
1
<?php
2
3
namespace AllDigitalRewards\WeGift\Entity;
4
5
use DateTime;
6
use JsonSerializable;
7
8
abstract class AbstractEntity implements JsonSerializable
9
{
10
    public function __construct(array $data = null)
11
    {
12
        if (!is_null($data)) {
13
            $this->hydrate($data);
14
        }
15
    }
16
17
    public function toArray(): array
18
    {
19
        $data = call_user_func('get_object_vars', $this);
20
21
        foreach ($data as $key => $value) {
22
            if (is_null($value)) {
23
                continue;
24
            }
25
            if ($value instanceof DateTime) {
26
                $data[$key] = $value->format('Y-m-d H:i:s');
27
            }
28
        }
29
30
        return $data;
31
    }
32
33
    public function hydrate(array $options): void
34
    {
35
        $methods = get_class_methods($this);
36
        foreach ($options as $key => $value) {
37
            if (is_null($value)) {
38
                continue;
39
            }
40
            $method = $this->getSetterMethod($key);
41
            if (in_array($method, $methods)) {
42
                $this->$method($value);
43
            }
44
        }
45
    }
46
47
    public function jsonSerialize(): array
48
    {
49
        return $this->toArray();
50
    }
51
52
    private function getSetterMethod($propertyName): string
53
    {
54
        return "set" . str_replace(' ', '', ucwords(str_replace('_', ' ', $propertyName)));
55
    }
56
}
57