Completed
Pull Request — master (#61)
by Alex
03:53
created

ReflectionHandler   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Importance

Changes 0
Metric Value
wmc 6
lcom 0
cbo 0
dl 0
loc 40
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A getProperty() 0 12 2
A setProperty() 0 15 4
1
<?php
2
3
namespace POData\Common;
4
5
class ReflectionHandler
6
{
7
8
    /**
9
     * @param $entryObject
10
     * @param $property
11
     * @return mixed
12
     */
13
    public static function getProperty(&$entryObject, $property)
14
    {
15
        // If magic method exists, try that first, else try property directly
16
        if (method_exists($entryObject, '__get')) {
17
            $value = $entryObject->$property;
18
        } else {
19
            $reflectionProperty = new \ReflectionProperty(get_class($entryObject), $property);
20
            $reflectionProperty->setAccessible(true);
21
            $value = $reflectionProperty->getValue($entryObject);
22
        }
23
        return $value;
24
    }
25
26
    /**
27
     * @param string $property
28
     */
29
    public static function setProperty(&$entity, $property, $value)
30
    {
31
        // If magic method exists, try that first, else try property directly
32
        if (method_exists($entity, '__set')) {
33
            $entity->$property = $value;
34
        } elseif (is_object($entity) && property_exists($entity, $property)) {
35
            $entity->$property = $value;
36
        } else {
37
            $reflect = new \ReflectionProperty($entity, $property);
38
            $oldAccess = $reflect->isPublic();
39
            $reflect->setAccessible(true);
40
            $reflect->setValue($entity, $value);
41
            $reflect->setAccessible($oldAccess);
42
        }
43
    }
44
}