FragmentRendererPass.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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\DependencyInjection;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\Compiler\ServiceLocatorTagPass;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
  15. use Symfony\Component\DependencyInjection\Reference;
  16. use Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface;
  17. /**
  18. * Adds services tagged kernel.fragment_renderer as HTTP content rendering strategies.
  19. *
  20. * @author Fabien Potencier <fabien@symfony.com>
  21. */
  22. class FragmentRendererPass implements CompilerPassInterface
  23. {
  24. private $handlerService;
  25. private $rendererTag;
  26. public function __construct(string $handlerService = 'fragment.handler', string $rendererTag = 'kernel.fragment_renderer')
  27. {
  28. $this->handlerService = $handlerService;
  29. $this->rendererTag = $rendererTag;
  30. }
  31. public function process(ContainerBuilder $container)
  32. {
  33. if (!$container->hasDefinition($this->handlerService)) {
  34. return;
  35. }
  36. $definition = $container->getDefinition($this->handlerService);
  37. $renderers = [];
  38. foreach ($container->findTaggedServiceIds($this->rendererTag, true) as $id => $tags) {
  39. $def = $container->getDefinition($id);
  40. $class = $container->getParameterBag()->resolveValue($def->getClass());
  41. if (!$r = $container->getReflectionClass($class)) {
  42. throw new InvalidArgumentException(sprintf('Class "%s" used for service "%s" cannot be found.', $class, $id));
  43. }
  44. if (!$r->isSubclassOf(FragmentRendererInterface::class)) {
  45. throw new InvalidArgumentException(sprintf('Service "%s" must implement interface "%s".', $id, FragmentRendererInterface::class));
  46. }
  47. foreach ($tags as $tag) {
  48. $renderers[$tag['alias']] = new Reference($id);
  49. }
  50. }
  51. $definition->replaceArgument(0, ServiceLocatorTagPass::register($container, $renderers));
  52. }
  53. }