Completed
Push — master ( b1d0ff...f51f35 )
by Toni
04:43
created

AbstractResource::isCastable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 2
nc 2
nop 1
1
<?php
2
3
4
namespace ClashOfClans\Api;
5
6
7
use ClashOfClans\Api\Clan\Clan;
8
use ClashOfClans\Api\Location\Location;
9
10
abstract class AbstractResource
11
{
12
    protected $data = [];
13
    protected $casts = [
14
        'location' => Location::class
15
    ];
16
17
    protected function __construct()
18
    {
19
20
    }
21
22
    /**
23
     * @param array $properties
24
     * @return static
25
     */
26
    public static function makeFromArray(array $properties)
27
    {
28
        $instance = new static;
29
30
        $instance->parseProperties($properties);
31
32
        return $instance;
33
    }
34
35
    protected function parseProperties(array $properties)
36
    {
37
        foreach ($properties as $key => $value) {
38
            $this->parse($key, $value);
39
        }
40
    }
41
42
    protected function parse($key, $value)
43
    {
44
        if ($this->isCastable($key)) {
45
            return $this->cast($key, $value);
46
        }
47
48
        return $this->setRawProperty($key, $value);
49
    }
50
51
    /**
52
     * @param $key
53
     * @return bool
54
     */
55
    protected function isCastable($key)
56
    {
57
        return array_key_exists($key, $this->casts) || is_int($key);
58
    }
59
60
    /**
61
     * @param $key
62
     * @param $value
63
     * @return Clan
64
     */
65
    protected function cast($key, $value)
66
    {
67
        $class = is_int($key) ? $this->casts['all'] : $this->casts[$key];
68
69
        return $this->setRawProperty($key, $class::makeFromArray($value));
70
    }
71
72
    /**
73
     * @param $key
74
     * @param $value
75
     * @return Clan
76
     */
77
    protected function setRawProperty($key, $value)
78
    {
79
        $this->data[$key] = $value;
80
81
        return $this;
82
    }
83
84
    protected function get($key = null)
85
    {
86
        if($key === null)
87
        {
88
            return $this->data;
89
        }
90
91
        return isset($this->data[$key]) ? $this->data[$key] : null;
92
    }
93
94
    public function __call($name, $arguments)
95
    {
96
        if($data = $this->get($name))
97
        {
98
            return $data;
99
        }
100
    }
101
}
102