MethodDefinitionCollector.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. class MethodDefinitionCollector extends AbstractCallableDefinitionCollector implements MethodDefinitionCollectorInterface
  13. {
  14. protected static array $container = [];
  15. /**
  16. * Get the method definition from metadata container,
  17. * If the metadata not exist in container, then will
  18. * parse it and save into container, and then return it.
  19. */
  20. public static function getOrParse(string $class, string $method): array
  21. {
  22. $key = $class . '::' . $method;
  23. if (static::has($key)) {
  24. return static::get($key);
  25. }
  26. $parameters = ReflectionManager::reflectMethod($class, $method)->getParameters();
  27. $definitions = [];
  28. foreach ($parameters as $parameter) {
  29. $type = $parameter->getType()->getName();
  30. switch ($type) {
  31. case 'int':
  32. case 'float':
  33. case 'string':
  34. case 'array':
  35. case 'bool':
  36. $definition = [
  37. 'type' => $type,
  38. 'name' => $parameter->getName(),
  39. 'ref' => '',
  40. 'allowsNull' => $parameter->allowsNull(),
  41. ];
  42. if ($parameter->isDefaultValueAvailable()) {
  43. $definition['defaultValue'] = $parameter->getDefaultValue();
  44. }
  45. $definitions[] = $definition;
  46. break;
  47. default:
  48. // Object
  49. $definitions[] = [
  50. 'type' => 'object',
  51. 'name' => $parameter->getName(),
  52. 'ref' => $type ?? null,
  53. 'allowsNull' => $parameter->allowsNull(),
  54. ];
  55. break;
  56. }
  57. }
  58. static::set($key, $definitions);
  59. return $definitions;
  60. }
  61. public function getParameters(string $class, string $method): array
  62. {
  63. $key = $class . '::' . $method . '@params';
  64. if (static::has($key)) {
  65. return static::get($key);
  66. }
  67. $parameters = ReflectionManager::reflectClass($class)->getMethod($method)->getParameters();
  68. $definitions = $this->getDefinitionsFromParameters($parameters);
  69. static::set($key, $definitions);
  70. return $definitions;
  71. }
  72. public function getReturnType(string $class, string $method): ReflectionType
  73. {
  74. $key = $class . '::' . $method . '@return';
  75. if (static::has($key)) {
  76. return static::get($key);
  77. }
  78. $returnType = ReflectionManager::reflectClass($class)->getMethod($method)->getReturnType();
  79. $type = $this->createType('', $returnType, $returnType ? $returnType->allowsNull() : true);
  80. static::set($key, $type);
  81. return $type;
  82. }
  83. }