ServiceValueResolver.php 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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\DependencyInjection\Exception\RuntimeException;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
  15. use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadata;
  16. /**
  17. * Yields a service keyed by _controller and argument name.
  18. *
  19. * @author Nicolas Grekas <p@tchwork.com>
  20. */
  21. final class ServiceValueResolver implements ArgumentValueResolverInterface
  22. {
  23. private $container;
  24. public function __construct(ContainerInterface $container)
  25. {
  26. $this->container = $container;
  27. }
  28. /**
  29. * {@inheritdoc}
  30. */
  31. public function supports(Request $request, ArgumentMetadata $argument)
  32. {
  33. $controller = $request->attributes->get('_controller');
  34. if (\is_array($controller) && \is_callable($controller, true) && \is_string($controller[0])) {
  35. $controller = $controller[0].'::'.$controller[1];
  36. } elseif (!\is_string($controller) || '' === $controller) {
  37. return false;
  38. }
  39. if ('\\' === $controller[0]) {
  40. $controller = ltrim($controller, '\\');
  41. }
  42. return $this->container->has($controller) && $this->container->get($controller)->has($argument->getName());
  43. }
  44. /**
  45. * {@inheritdoc}
  46. */
  47. public function resolve(Request $request, ArgumentMetadata $argument)
  48. {
  49. if (\is_array($controller = $request->attributes->get('_controller'))) {
  50. $controller = $controller[0].'::'.$controller[1];
  51. }
  52. if ('\\' === $controller[0]) {
  53. $controller = ltrim($controller, '\\');
  54. }
  55. try {
  56. yield $this->container->get($controller)->get($argument->getName());
  57. } catch (RuntimeException $e) {
  58. $what = sprintf('argument $%s of "%s()"', $argument->getName(), $controller);
  59. $message = preg_replace('/service "service_locator\.[^"]++"/', $what, $e->getMessage());
  60. if ($e->getMessage() === $message) {
  61. $message = sprintf('Cannot resolve %s: %s', $what, $message);
  62. }
  63. $r = new \ReflectionProperty($e, 'message');
  64. $r->setAccessible(true);
  65. $r->setValue($e, $message);
  66. throw $e;
  67. }
  68. }
  69. }