You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.5 KiB

3 years ago
  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. } elseif (\is_object($controller) && !$controller instanceof \Closure) {
  27. $reflection = (new \ReflectionObject($controller))->getMethod('__invoke');
  28. } else {
  29. $reflection = new \ReflectionFunction($controller);
  30. }
  31. foreach ($reflection->getParameters() as $param) {
  32. $attributes = [];
  33. if (\PHP_VERSION_ID >= 80000) {
  34. foreach ($param->getAttributes() as $reflectionAttribute) {
  35. if (class_exists($reflectionAttribute->getName())) {
  36. $attributes[] = $reflectionAttribute->newInstance();
  37. }
  38. }
  39. }
  40. $arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param, $reflection), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull(), $attributes);
  41. }
  42. return $arguments;
  43. }
  44. /**
  45. * Returns an associated type to the given parameter if available.
  46. */
  47. private function getType(\ReflectionParameter $parameter, \ReflectionFunctionAbstract $function): ?string
  48. {
  49. if (!$type = $parameter->getType()) {
  50. return null;
  51. }
  52. $name = $type instanceof \ReflectionNamedType ? $type->getName() : (string) $type;
  53. if ($function instanceof \ReflectionMethod) {
  54. $lcName = strtolower($name);
  55. switch ($lcName) {
  56. case 'self':
  57. return $function->getDeclaringClass()->name;
  58. case 'parent':
  59. return ($parent = $function->getDeclaringClass()->getParentClass()) ? $parent->name : null;
  60. }
  61. }
  62. return $name;
  63. }
  64. }