Completed
Push — master ( f42b62...32046d )
by Fran
04:07
created

Dto::toArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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