Completed
Push — master ( 63e254...443ded )
by Simone
02:28
created

Resource::properties()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 14
rs 9.2
cc 4
eloc 7
nc 4
nop 0
1
<?php
2
3
/**
4
 * This file is part of sensorario/resources repository
5
 *
6
 * (c) Simone Gentili <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sensorario\Resources;
13
14
use RuntimeException;
15
16
abstract class Resource
17
    extends MagicResource
0 ignored issues
show
Coding Style introduced by
The extends keyword must be on the same line as the class name
Loading history...
18
{
19
    public static function mandatory()
20
    {
21
        return [];
22
    }
23
24
    public static function allowed()
25
    {
26
        return [];
27
    }
28
29
    public static function allowedValues()
30
    {
31
        return [];
32
    }
33
34
    public static function rules()
35
    {
36
        return [];
37
    }
38
39
    public static function defaults()
40
    {
41
        return [];
42
    }
43
44
    final public function hasProperty($propertyName)
45
    {
46
        return isset(
47
            $this->properties[$propertyName]
48
        );
49
    }
50
51
    final public function hasProperties(array $properties)
52
    {
53
        foreach ($properties as $property) {
54
            if ($this->hasNotProperty($property)) {
55
                return false;
56
            }
57
        }
58
59
        return true;
60
    }
61
62
    final public function hasNotProperty($propertyName)
63
    {
64
        return !$this->hasProperty($propertyName);
65
    }
66
67
    final public function get($propertyName)
68
    {
69
        if ('' == $propertyName) {
70
            throw new RuntimeException(
71
                'Oops! Property name requested is empty string!!'
72
            );
73
        }
74
75
        if ($this->hasNotProperty($propertyName)) {
76
            if (isset($this->defaults()[$propertyName])) {
77
                return $this->defaults()[$propertyName];
78
            }
79
80
            throw new RuntimeException(
81
                'No value nor method `'
82
                . $propertyName
83
                . '` found in this resource'
84
            );
85
        }
86
87
        return $this->properties[$propertyName];
88
    }
89
90
    final public function properties()
91
    {
92
        $properties = $this->properties;
93
94
        foreach ($properties as $k => $v) {
95
            if ('object' === gettype($v)) {
96
                if ($this->rules()[$k]['object'] === '\\Sensorario\\Resources\\Resource') {
97
                    $properties[$k] = $v->properties();
98
                }
99
            }
100
        }
101
102
        return $properties;
103
    }
104
}
105