AbstractCallableDefinitionCollector.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 ReflectionNamedType;
  13. use ReflectionParameter;
  14. use ReflectionUnionType;
  15. abstract class AbstractCallableDefinitionCollector extends MetadataCollector
  16. {
  17. /**
  18. * @param array<ReflectionParameter> $parameters
  19. */
  20. protected function getDefinitionsFromParameters(array $parameters): array
  21. {
  22. $definitions = [];
  23. foreach ($parameters as $parameter) {
  24. $definitions[] = $this->createType(
  25. $parameter->getName(),
  26. $parameter->getType(),
  27. $parameter->allowsNull(),
  28. $parameter->isDefaultValueAvailable(),
  29. $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null
  30. );
  31. }
  32. return $definitions;
  33. }
  34. /**
  35. * @param mixed $defaultValue
  36. */
  37. protected function createType(string $name, ?\ReflectionType $type, bool $allowsNull, bool $hasDefault = false, $defaultValue = null): ReflectionType
  38. {
  39. // TODO: Support ReflectionUnionType.
  40. $typeName = match (true) {
  41. $type instanceof ReflectionNamedType => $type->getName(),
  42. $type instanceof ReflectionUnionType => $type->getTypes()[0]->getName(),
  43. default => 'mixed'
  44. };
  45. return new ReflectionType($typeName, $allowsNull, [
  46. 'defaultValueAvailable' => $hasDefault,
  47. 'defaultValue' => $defaultValue,
  48. 'name' => $name,
  49. ]);
  50. }
  51. }