Serializable::hydrate()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 8
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 12
ccs 9
cts 9
cp 1
crap 4
rs 10
1
<?php
2
3
namespace PierInfor\Gears\Entity;
4
5
/**
6
 * Entity manager for json marshalling unmarshalling
7
 *
8
 */
9
class Serializable
10
{
11
    const _ENTITY_NS_PREFIX = 'PierInfor\\Gears\\Entity\\';
12
    const _SETTER_PREFIX = 'set';
13
    const _GETTER_PREFIX = 'get';
14
15
    /**
16
     * ctor
17
     */
18
    public function __construct()
19
    {
20
    }
21
22
    /**
23
     * json encoder
24
     */
25 1
    public function __toString()
26
    {
27 1
        return json_encode($this);
28
    }
29
30
    /**
31
     * hydrate an object from \stdClass
32
     */
33 4
    public function hydrate(\stdClass $instance): Serializable
34
    {
35 4
        foreach ($instance as $key => $value) {
36 4
            $setter = self::_SETTER_PREFIX . ucfirst($key);
37 4
            $callee = [$this, $setter];
38 4
            if (is_callable($callee)) {
39 4
                $className = self::_ENTITY_NS_PREFIX . ucfirst($key);
40 4
                $arg = (is_object($value)) ? (new $className())->hydrate($value) : $value;
41 4
                call_user_func_array($callee, [$arg]);
42
            }
43
        }
44 4
        return $this;
45
    }
46
}
47