ReflectionHelper.php 2.1 KB

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