Object::importPropertiesFrom()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 3
nop 1
1
<?php
2
3
namespace ObjectLiteral;
4
5
/**
6
 * Object.
7
 *
8
 * @author Jose Celano
9
 */
10
class Object extends \stdClass
11
{
12
    public function __construct($value = null)
13
    {
14
        if (is_null($value) || $value == '') {
15
            return;
16
        }
17
18
        if (is_array($value)) {
19
            $object = (object)$value;
20
            $this->importPropertiesFrom($object);
21
            return;
22
        }
23
24
        if (is_string($value)) {
25
            $object = json_decode($value);
26
            if (!is_null($object)) {
27
                $this->importPropertiesFrom($object);
28
                return;
29
            }
30
        }
31
32
        throw new \InvalidArgumentException('Object can not be build from value ' . var_export($value, true));
33
    }
34
35
    public function __call($name, $args)
36
    {
37
        if (!is_callable($this->$name)) {
38
            $this->triggerError("Not callable property: $name", E_ERROR);
39
        }
40
41
        array_unshift($args, $this);
42
        return call_user_func_array($this->$name, $args);
43
    }
44
45
    protected function triggerError($errorMsg, $errorType = E_USER_NOTICE)
46
    {
47
        $this->triggerError($errorMsg, $errorType);
48
    }
49
50
    private function importPropertiesFrom($object)
51
    {
52
        foreach (get_object_vars($object) as $key => $value) {
53
            if (is_scalar($value) || is_callable($value)) {
54
                $this->$key = $value;
55
                continue;
56
            }
57
            $this->$key = new Object($value);
58
        }
59
    }
60
}
61