FragmentRendererPass.php 2.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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\ServiceLocatorTagPass;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  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 = array();
  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. }