ApiResource::fill()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace OhDear\PhpSdk\Resources;
4
5
use OhDear\PhpSdk\OhDear;
6
use ReflectionObject;
7
use ReflectionProperty;
8
9
class ApiResource
10
{
11
    public array $attributes = [];
12
13
    protected ?OhDear $ohDear;
14
15
    public function __construct(array $attributes, OhDear $ohDear = null)
16
    {
17
        $this->attributes = $attributes;
18
19
        $this->ohDear = $ohDear;
20
21
        $this->fill();
22
    }
23
24
    protected function fill(): void
25
    {
26
        foreach ($this->attributes as $key => $value) {
27
            $key = $this->camelCase($key);
28
29
            $this->{$key} = $value;
30
        }
31
    }
32
33
    protected function camelCase(string $key): string
34
    {
35
        $parts = explode('_', $key);
36
37
        foreach ($parts as $i => $part) {
38
            if ($i !== 0) {
39
                $parts[$i] = ucfirst($part);
40
            }
41
        }
42
43
        return str_replace(' ', '', implode(' ', $parts));
44
    }
45
46
    public function __sleep()
47
    {
48
        $publicProperties = (new ReflectionObject($this))->getProperties(ReflectionProperty::IS_PUBLIC);
49
50
        $publicPropertyNames = array_map(function (ReflectionProperty $property) {
51
            return $property->getName();
52
        }, $publicProperties);
53
54
        return array_diff($publicPropertyNames, ['ohDear', 'attributes']);
55
    }
56
}
57