AbstractCallableDefinitionCollector.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Di;
  12. use ReflectionAttribute;
  13. use ReflectionNamedType;
  14. use ReflectionParameter;
  15. use ReflectionUnionType;
  16. abstract class AbstractCallableDefinitionCollector extends MetadataCollector
  17. {
  18. /**
  19. * @param array<ReflectionParameter> $parameters
  20. */
  21. protected function getDefinitionsFromParameters(array $parameters): array
  22. {
  23. $definitions = [];
  24. foreach ($parameters as $parameter) {
  25. $definitions[] = $this->createType(
  26. $parameter->getName(),
  27. $parameter->getType(),
  28. $parameter->allowsNull(),
  29. $parameter->isDefaultValueAvailable(),
  30. $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
  31. $parameter->getAttributes()
  32. );
  33. }
  34. return $definitions;
  35. }
  36. /**
  37. * @param ReflectionAttribute[] $attributes
  38. */
  39. protected function createType(string $name, ?\ReflectionType $type, bool $allowsNull, bool $hasDefault = false, mixed $defaultValue = null, array $attributes = []): ReflectionType
  40. {
  41. // TODO: Support ReflectionUnionType.
  42. $typeName = match (true) {
  43. $type instanceof ReflectionNamedType => $type->getName(),
  44. $type instanceof ReflectionUnionType => $type->getTypes()[0]->getName(),
  45. default => 'mixed'
  46. };
  47. return new ReflectionType($typeName, $allowsNull, [
  48. 'defaultValueAvailable' => $hasDefault,
  49. 'defaultValue' => $defaultValue,
  50. 'name' => $name,
  51. 'attributes' => $attributes,
  52. ]);
  53. }
  54. }