ReflectionMember.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Attribute\Reflection;
  11. /**
  12. * @internal
  13. */
  14. class ReflectionMember
  15. {
  16. public function __construct(
  17. private readonly \ReflectionParameter|\ReflectionProperty $member,
  18. ) {
  19. }
  20. /**
  21. * @template T of object
  22. *
  23. * @param class-string<T> $class
  24. *
  25. * @return T|null
  26. */
  27. public function getAttribute(string $class): ?object
  28. {
  29. return ($this->member->getAttributes($class, \ReflectionAttribute::IS_INSTANCEOF)[0] ?? null)?->newInstance();
  30. }
  31. public function getSourceName(): string
  32. {
  33. if ($this->member instanceof \ReflectionProperty) {
  34. return $this->member->getDeclaringClass()->name;
  35. }
  36. $function = $this->member->getDeclaringFunction();
  37. if ($function instanceof \ReflectionMethod) {
  38. return $function->class.'::'.$function->name.'()';
  39. }
  40. return $function->name.'()';
  41. }
  42. public function getSourceThis(): ?object
  43. {
  44. if ($this->member instanceof \ReflectionParameter) {
  45. return $this->member->getDeclaringFunction()->getClosureThis();
  46. }
  47. return null;
  48. }
  49. public function getType(): ?\ReflectionType
  50. {
  51. return $this->member->getType();
  52. }
  53. public function getName(): string
  54. {
  55. return $this->member->getName();
  56. }
  57. public function hasDefaultValue(): bool
  58. {
  59. if ($this->member instanceof \ReflectionParameter) {
  60. return $this->member->isDefaultValueAvailable();
  61. }
  62. return $this->member->hasDefaultValue();
  63. }
  64. public function getDefaultValue(): mixed
  65. {
  66. $defaultValue = $this->member->getDefaultValue();
  67. if ($defaultValue instanceof \BackedEnum) {
  68. return $defaultValue->value;
  69. }
  70. return $defaultValue;
  71. }
  72. public function isNullable(): bool
  73. {
  74. return (bool) $this->member->getType()?->allowsNull();
  75. }
  76. public function getMemberName(): string
  77. {
  78. return $this->member instanceof \ReflectionParameter ? 'parameter' : 'property';
  79. }
  80. public function isParameter(): bool
  81. {
  82. return $this->member instanceof \ReflectionParameter;
  83. }
  84. public function isProperty(): bool
  85. {
  86. return $this->member instanceof \ReflectionProperty;
  87. }
  88. }