TwigLoaderPass.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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\Bundle\TwigBundle\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Exception\LogicException;
  14. use Symfony\Component\DependencyInjection\Reference;
  15. /**
  16. * Adds services tagged twig.loader as Twig loaders.
  17. *
  18. * @author Daniel Leech <daniel@dantleech.com>
  19. */
  20. class TwigLoaderPass implements CompilerPassInterface
  21. {
  22. public function process(ContainerBuilder $container)
  23. {
  24. if (false === $container->hasDefinition('twig')) {
  25. return;
  26. }
  27. $prioritizedLoaders = [];
  28. $found = 0;
  29. foreach ($container->findTaggedServiceIds('twig.loader', true) as $id => $attributes) {
  30. $priority = $attributes[0]['priority'] ?? 0;
  31. $prioritizedLoaders[$priority][] = $id;
  32. ++$found;
  33. }
  34. if (!$found) {
  35. throw new LogicException('No twig loaders found. You need to tag at least one loader with "twig.loader".');
  36. }
  37. if (1 === $found) {
  38. $container->setAlias('twig.loader', $id);
  39. } else {
  40. $chainLoader = $container->getDefinition('twig.loader.chain');
  41. krsort($prioritizedLoaders);
  42. foreach ($prioritizedLoaders as $loaders) {
  43. foreach ($loaders as $loader) {
  44. $chainLoader->addMethodCall('addLoader', [new Reference($loader)]);
  45. }
  46. }
  47. $container->setAlias('twig.loader', 'twig.loader.chain');
  48. }
  49. }
  50. }