Completed
Push — 1.x ( 770e50...c04239 )
by Théo
02:28 queued 01:12
created

ReflectionHelper::getProperty()   B

Complexity

Conditions 5
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 11
nc 6
nop 2
dl 0
loc 20
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
namespace DeepCopy\Reflection;
4
5
use DeepCopy\Exception\PropertyException;
6
use ReflectionClass;
7
use ReflectionException;
8
use ReflectionObject;
9
use ReflectionProperty;
10
11
class ReflectionHelper
12
{
13
    /**
14
     * Retrieves all properties (including private ones), from object and all its ancestors.
15
     *
16
     * Standard \ReflectionClass->getProperties() does not return private properties from ancestor classes.
17
     *
18
     * @author [email protected]
19
     * @see http://php.net/manual/en/reflectionclass.getproperties.php
20
     *
21
     * @param ReflectionClass $ref
22
     *
23
     * @return ReflectionProperty[]
24
     */
25
    public static function getProperties(ReflectionClass $ref)
26
    {
27
        $props = $ref->getProperties();
28
        $propsArr = array();
29
30
        foreach ($props as $prop) {
31
            $propertyName = $prop->getName();
32
            $propsArr[$propertyName] = $prop;
33
        }
34
35
        if ($parentClass = $ref->getParentClass()) {
36
            $parentPropsArr = self::getProperties($parentClass);
37
            foreach ($propsArr as $key => $property) {
38
                $parentPropsArr[$key] = $property;
39
            }
40
41
            return $parentPropsArr;
42
        }
43
44
        return $propsArr;
45
    }
46
47
    /**
48
     * Retrieves property by name from object and all its ancestors.
49
     *
50
     * @param object|string $object
51
     * @param string $name
52
     *
53
     * @throws PropertyException
54
     * @throws ReflectionException
55
     *
56
     * @return ReflectionProperty
57
     */
58
    public static function getProperty($object, $name)
59
    {
60
        $reflection = is_object($object) ? new ReflectionObject($object) : new ReflectionClass($object);
61
62
        if ($reflection->hasProperty($name)) {
63
            return $reflection->getProperty($name);
64
        }
65
66
        if ($parentClass = $reflection->getParentClass()) {
67
            return self::getProperty($parentClass->getName(), $name);
68
        }
69
70
        throw new PropertyException(
71
            sprintf(
72
                'The class "%s" doesn\'t have a property with the given name: "%s".',
73
                is_object($object) ? get_class($object) : $object,
74
                $name
75
            )
76
        );
77
    }
78
}
79