Completed
Pull Request — master (#56)
by Simone
02:29
created

MagicResource   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 4
Bugs 0 Features 1
Metric Value
wmc 27
c 4
b 0
f 1
lcom 1
cbo 1
dl 0
loc 144
rs 10

9 Methods

Rating   Name   Duplication   Size   Complexity  
A __call() 0 18 3
C __construct() 0 28 7
B __callStatic() 0 25 3
A hasProperty() 0 6 1
B get() 0 22 4
A defaults() 0 4 1
A hasNotProperty() 0 4 1
A hasProperties() 0 10 3
A properties() 0 14 4
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
use Sensorario\Resources\Validators\ResourcesValidator;
16
17
abstract class MagicResource
18
{
19
    protected $properties = [];
20
21
    public function __call($functionName, $arguments)
22
    {
23
        $propertyName = strtolower($functionName);
24
25
        if ($this->hasProperty($propertyName)) {
26
            return $this->get($propertyName);
27
        }
28
29
        if (isset($this->defaults()[$propertyName])) {
30
            return $this->defaults()[$propertyName];
31
        }
32
33
        throw new RuntimeException(
34
            'Method `' . get_class($this)
35
            . '::' . $functionName 
36
            . '()` is not yet implemented'
37
        );
38
    }
39
40
    public function __construct(
41
        array $properties,
42
        ResourcesValidator $validator,
43
        $validationRequired = true
44
    ) {
45
        $this->properties = $properties;
46
47
        foreach ($properties as $k => $v) {
48
            if ('object' === gettype($v) && !isset($this->rules()[$k])) {
0 ignored issues
show
Documentation Bug introduced by
The method rules does not exist on object<Sensorario\Resources\MagicResource>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
49
                throw new RuntimeException(
50
                    'When property `' . $k . '` is an object class, must be defined in Resources::rules()'
51
                );
52
            }
53
        }
54
55
        /** @warning this convert utf8 in utf8 */
56
        foreach ($properties as $name => $value) {
57
            if ('object' !== gettype($value)) {
58
                $properties[$name] = utf8_encode(
59
                    $value
60
                );
61
            }
62
        }
63
64
        if ($validationRequired) {
65
            $validator->validate($this);
1 ignored issue
show
Compatibility introduced by
$this of type object<Sensorario\Resources\MagicResource> is not a sub-type of object<Sensorario\Resources\Resource>. It seems like you assume a child class of the class Sensorario\Resources\MagicResource to be always present.

This check looks for parameters that are defined as one type in their type hint or doc comment but seem to be used as a narrower type, i.e an implementation of an interface or a subclass.

Consider changing the type of the parameter or doing an instanceof check before assuming your parameter is of the expected type.

Loading history...
66
        }
67
    }
68
69
    public static function __callStatic($methodName, array $args)
70
    {
71
        $methodWhiteList = [
72
            'box',
73
            'allowedValues'
74
        ];
75
76
        $isMethodAllowed = in_array(
77
            $methodName,
78
            $methodWhiteList
79
        );
80
81
        if ($isMethodAllowed) {
82
            return new static(
83
                isset($args[0])
84
                ? $args[0]
85
                : [],
86
                new ResourcesValidator()
87
            );
88
        }
89
90
        throw new RuntimeException(
91
            'Invalid factory method `' . $methodName . '`'
92
        );
93
    }
94
95
    final public function hasProperty($propertyName)
96
    {
97
        return isset(
98
            $this->properties[$propertyName]
99
        );
100
    }
101
102
    final public function get($propertyName)
103
    {
104
        if ('' == $propertyName) {
105
            throw new RuntimeException(
106
                'Oops! Property name requested is empty string!!'
107
            );
108
        }
109
110
        if ($this->hasNotProperty($propertyName)) {
111
            if (isset($this->defaults()[$propertyName])) {
112
                return $this->defaults()[$propertyName];
113
            }
114
115
            throw new RuntimeException(
116
                'No value nor method `'
117
                . $propertyName
118
                . '` found in this resource'
119
            );
120
        }
121
122
        return $this->properties[$propertyName];
123
    }
124
125
    public static function defaults()
126
    {
127
        return [];
128
    }
129
130
    final public function hasNotProperty($propertyName)
131
    {
132
        return !$this->hasProperty($propertyName);
133
    }
134
135
    final public function hasProperties(array $properties)
136
    {
137
        foreach ($properties as $property) {
138
            if ($this->hasNotProperty($property)) {
139
                return false;
140
            }
141
        }
142
143
        return true;
144
    }
145
146
    final public function properties()
147
    {
148
        $properties = $this->properties;
149
150
        foreach ($properties as $k => $v) {
151
            if ('object' === gettype($v)) {
152
                if ($this->rules()[$k]['object'] === '\\Sensorario\\Resources\\Resource') {
0 ignored issues
show
Documentation Bug introduced by
The method rules does not exist on object<Sensorario\Resources\MagicResource>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
153
                    $properties[$k] = $v->properties();
154
                }
155
            }
156
        }
157
158
        return $properties;
159
    }
160
}
161