ArgumentMetadataFactory.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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)
  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. $arguments[] = new ArgumentMetadata($param->getName(), $this->getType($param, $reflection), $param->isVariadic(), $param->isDefaultValueAvailable(), $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null, $param->allowsNull());
  33. }
  34. return $arguments;
  35. }
  36. /**
  37. * Returns an associated type to the given parameter if available.
  38. *
  39. * @param \ReflectionParameter $parameter
  40. *
  41. * @return string|null
  42. */
  43. private function getType(\ReflectionParameter $parameter, \ReflectionFunctionAbstract $function)
  44. {
  45. if (!$type = $parameter->getType()) {
  46. return;
  47. }
  48. $name = $type->getName();
  49. $lcName = strtolower($name);
  50. if ('self' !== $lcName && 'parent' !== $lcName) {
  51. return $name;
  52. }
  53. if (!$function instanceof \ReflectionMethod) {
  54. return;
  55. }
  56. if ('self' === $lcName) {
  57. return $function->getDeclaringClass()->name;
  58. }
  59. if ($parent = $function->getDeclaringClass()->getParentClass()) {
  60. return $parent->name;
  61. }
  62. }
  63. }