ServiceValueResolver.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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\Controller\ArgumentResolver;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
  14. use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
  15. /**
  16. * Yields a service keyed by _controller and argument name.
  17. *
  18. * @author Nicolas Grekas <p@tchwork.com>
  19. */
  20. final class ServiceValueResolver implements ArgumentValueResolverInterface
  21. {
  22. private $container;
  23. public function __construct(ContainerInterface $container)
  24. {
  25. $this->container = $container;
  26. }
  27. /**
  28. * {@inheritdoc}
  29. */
  30. public function supports(Request $request, ArgumentMetadata $argument)
  31. {
  32. $controller = $request->attributes->get('_controller');
  33. if (\is_array($controller) && \is_callable($controller, true) && \is_string($controller[0])) {
  34. $controller = $controller[0].'::'.$controller[1];
  35. } elseif (!\is_string($controller) || '' === $controller) {
  36. return false;
  37. }
  38. if ('\\' === $controller[0]) {
  39. $controller = ltrim($controller, '\\');
  40. }
  41. if (!$this->container->has($controller) && false !== $i = strrpos($controller, ':')) {
  42. $controller = substr($controller, 0, $i).strtolower(substr($controller, $i));
  43. }
  44. return $this->container->has($controller) && $this->container->get($controller)->has($argument->getName());
  45. }
  46. /**
  47. * {@inheritdoc}
  48. */
  49. public function resolve(Request $request, ArgumentMetadata $argument)
  50. {
  51. if (\is_array($controller = $request->attributes->get('_controller'))) {
  52. $controller = $controller[0].'::'.$controller[1];
  53. }
  54. if ('\\' === $controller[0]) {
  55. $controller = ltrim($controller, '\\');
  56. }
  57. if (!$this->container->has($controller)) {
  58. $i = strrpos($controller, ':');
  59. $controller = substr($controller, 0, $i).strtolower(substr($controller, $i));
  60. }
  61. yield $this->container->get($controller)->get($argument->getName());
  62. }
  63. }