Ei kuvausta

ArgumentMetadataFactory.php 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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\HttpKernel\ControllerMetadata;
  11. /**
  12. * Builds {@see ArgumentMetadata} objects based on the given Controller.
  13. *
  14. * @author Iltar van der Berg <kjarli@gmail.com>
  15. */
  16. final class ArgumentMetadataFactory implements ArgumentMetadataFactoryInterface
  17. {
  18. /**
  19. * {@inheritdoc}
  20. */
  21. public function createArgumentMetadata($controller): array
  22. {
  23. $arguments = [];
  24. if (\is_array($controller)) {
  25. $reflection = new \ReflectionMethod($controller[0], $controller[1]);
  26. $class = $reflection->class;
  27. } elseif (\is_object($controller) && !$controller instanceof \Closure) {
  28. $reflection = new \ReflectionMethod($controller, '__invoke');
  29. $class = $reflection->class;
  30. } else {
  31. $reflection = new \ReflectionFunction($controller);
  32. if ($class = str_contains($reflection->name, '{closure}') ? null : $reflection->getClosureScopeClass()) {
  33. $class = $class->name;
  34. }
  35. }
  36. foreach ($reflection->getParameters() as $param) {
  37. $arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param, $class), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull());
  38. }
  39. return $arguments;
  40. }
  41. /**
  42. * Returns an associated type to the given parameter if available.
  43. */
  44. private function getType(\ReflectionParameter $parameter, ?string $class): ?string
  45. {
  46. if (!$type = $parameter->getType()) {
  47. return null;
  48. }
  49. $name = $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
  50. if (null !== $class) {
  51. switch (strtolower($name)) {
  52. case 'self':
  53. return $class;
  54. case 'parent':
  55. return get_parent_class($class) ?: null;
  56. }
  57. }
  58. return $name;
  59. }
  60. }