Passed
Push — master ( 58d525...a15eb9 )
by Fran
09:16
created

Dto::__toArray()   B

Complexity

Conditions 6
Paths 11

Size

Total Lines 22
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 0
Metric Value
cc 6
eloc 15
nc 11
nop 0
dl 0
loc 22
ccs 0
cts 13
cp 0
crap 42
rs 8.6737
c 0
b 0
f 0
1
<?php
2
namespace PSFS\base\dto;
3
4
use Propel\Runtime\ActiveRecord\ActiveRecordInterface;
5
use PSFS\base\Logger;
6
use PSFS\base\Singleton;
7
8
/**
9
 * Class Dto
10
 * @package PSFS\base\dto
11
 */
12
class Dto extends Singleton
13
{
14
15
    /**
16
     * ToArray wrapper
17
     * @return array
18
     */
19
    public function toArray()
20
    {
21
        return $this->__toArray();
22
    }
23
24
    /**
25
     * Convert dto to array representation
26
     * @return array
27
     */
28
    public function __toArray()
29
    {
30
        $dto = array();
31
        try {
32
            $reflectionClass = new \ReflectionClass($this);
33
            $properties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC);
34
            if (count($properties) > 0) {
35
                /** @var \ReflectionProperty $property */
36
                foreach ($properties as $property) {
37
                    $value = $property->getValue($this);
38
                    if(is_object($value) && method_exists($value, 'toArray')) {
39
                        $dto[$property->getName()] = $value->toArray();
40
                    } else {
41
                        $dto[$property->getName()] = $property->getValue($this);
42
                    }
43
                }
44
            }
45
        } catch (\Exception $e) {
46
            Logger::log(get_class($this) . ': ' . $e->getMessage(), LOG_ERR);
47
        }
48
        return $dto;
49
    }
50
51
    /**
52
     * Convert to string representation
53
     * @return string
54
     */
55
    public function __toString()
56
    {
57
        return get_class($this);
58
    }
59
60
    /**
61
     * Hydrate object from array
62
     * @param array $object
63
     */
64
    public function fromArray(array $object = array())
65
    {
66
        if (count($object) > 0) {
67
            foreach ($object as $key => $value) {
68
                if (property_exists($this, $key)) {
69
                    $this->$key = $value;
70
                }
71
            }
72
        }
73
    }
74
}