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

ReflectionHandler::setProperty()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 15
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.2
c 0
b 0
f 0
cc 4
eloc 11
nc 3
nop 3
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
}