ArgumentMetadataFactory.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. public function createArgumentMetadata(string|object|array $controller, ?\ReflectionFunctionAbstract $reflector = null): array
  19. {
  20. $arguments = [];
  21. $reflector ??= new \ReflectionFunction($controller(...));
  22. foreach ($reflector->getParameters() as $param) {
  23. $attributes = [];
  24. foreach ($param->getAttributes() as $reflectionAttribute) {
  25. if (class_exists($reflectionAttribute->getName())) {
  26. $attributes[] = $reflectionAttribute->newInstance();
  27. }
  28. }
  29. $arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull(), $attributes);
  30. }
  31. return $arguments;
  32. }
  33. /**
  34. * Returns an associated type to the given parameter if available.
  35. */
  36. private function getType(\ReflectionParameter $parameter): ?string
  37. {
  38. if (!$type = $parameter->getType()) {
  39. return null;
  40. }
  41. $name = $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
  42. return match (strtolower($name)) {
  43. 'self' => $parameter->getDeclaringClass()?->name,
  44. 'parent' => get_parent_class($parameter->getDeclaringClass()?->name ?? '') ?: null,
  45. default => $name,
  46. };
  47. }
  48. }