Completed
Push — master ( d07d9f...7851e5 )
by Freek
01:19
created

ApiResource   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 7
lcom 1
cbo 0
dl 0
loc 54
rs 10
c 0
b 0
f 0

4 Methods

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