TwigLoaderPass.php 2.0 KB

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\Bundle\TwigBundle\DependencyInjection\Compiler;
  11. use Symfony\Component\DependencyInjection\Reference;
  12. use Symfony\Component\DependencyInjection\ContainerBuilder;
  13. use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
  14. use Symfony\Component\DependencyInjection\Exception\LogicException;
  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. // register additional template loaders
  28. $loaderIds = $container->findTaggedServiceIds('twig.loader');
  29. if (count($loaderIds) === 0) {
  30. throw new LogicException('No twig loaders found. You need to tag at least one loader with "twig.loader"');
  31. }
  32. if (count($loaderIds) === 1) {
  33. $container->setAlias('twig.loader', key($loaderIds));
  34. } else {
  35. $chainLoader = $container->getDefinition('twig.loader.chain');
  36. $prioritizedLoaders = array();
  37. foreach ($loaderIds as $id => $tags) {
  38. foreach ($tags as $tag) {
  39. $priority = isset($tag['priority']) ? $tag['priority'] : 0;
  40. $prioritizedLoaders[$priority][] = $id;
  41. }
  42. }
  43. krsort($prioritizedLoaders);
  44. foreach ($prioritizedLoaders as $loaders) {
  45. foreach ($loaders as $loader) {
  46. $chainLoader->addMethodCall('addLoader', array(new Reference($loader)));
  47. }
  48. }
  49. $container->setAlias('twig.loader', 'twig.loader.chain');
  50. }
  51. }
  52. }