RuntimeReflectionService.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Doctrine\Persistence\Mapping;
  3. use Doctrine\Persistence\Reflection\RuntimePublicReflectionProperty;
  4. use Doctrine\Persistence\Reflection\TypedNoDefaultReflectionProperty;
  5. use ReflectionClass;
  6. use ReflectionException;
  7. use ReflectionMethod;
  8. use ReflectionProperty;
  9. use function array_key_exists;
  10. use function class_exists;
  11. use function class_parents;
  12. use function phpversion;
  13. use function version_compare;
  14. /**
  15. * PHP Runtime Reflection Service.
  16. */
  17. class RuntimeReflectionService implements ReflectionService
  18. {
  19. /** @var bool */
  20. private $supportsTypedPropertiesWorkaround;
  21. public function __construct()
  22. {
  23. $this->supportsTypedPropertiesWorkaround = version_compare((string) phpversion(), '7.4.0') >= 0;
  24. }
  25. /**
  26. * {@inheritDoc}
  27. */
  28. public function getParentClasses($class)
  29. {
  30. if (! class_exists($class)) {
  31. throw MappingException::nonExistingClass($class);
  32. }
  33. return class_parents($class);
  34. }
  35. /**
  36. * {@inheritDoc}
  37. */
  38. public function getClassShortName($class)
  39. {
  40. $reflectionClass = new ReflectionClass($class);
  41. return $reflectionClass->getShortName();
  42. }
  43. /**
  44. * {@inheritDoc}
  45. */
  46. public function getClassNamespace($class)
  47. {
  48. $reflectionClass = new ReflectionClass($class);
  49. return $reflectionClass->getNamespaceName();
  50. }
  51. /**
  52. * {@inheritDoc}
  53. */
  54. public function getClass($class)
  55. {
  56. return new ReflectionClass($class);
  57. }
  58. /**
  59. * {@inheritDoc}
  60. */
  61. public function getAccessibleProperty($class, $property)
  62. {
  63. $reflectionProperty = new ReflectionProperty($class, $property);
  64. if ($reflectionProperty->isPublic()) {
  65. $reflectionProperty = new RuntimePublicReflectionProperty($class, $property);
  66. } elseif ($this->supportsTypedPropertiesWorkaround && ! array_key_exists($property, $this->getClass($class)->getDefaultProperties())) {
  67. $reflectionProperty = new TypedNoDefaultReflectionProperty($class, $property);
  68. }
  69. $reflectionProperty->setAccessible(true);
  70. return $reflectionProperty;
  71. }
  72. /**
  73. * {@inheritDoc}
  74. */
  75. public function hasPublicMethod($class, $method)
  76. {
  77. try {
  78. $reflectionMethod = new ReflectionMethod($class, $method);
  79. } catch (ReflectionException $e) {
  80. return false;
  81. }
  82. return $reflectionMethod->isPublic();
  83. }
  84. }