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