TwigEnvironmentPass.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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\Compiler\PriorityTaggedServiceTrait;
  13. use Symfony\Component\DependencyInjection\ContainerBuilder;
  14. /**
  15. * Adds tagged twig.extension services to twig service.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. */
  19. class TwigEnvironmentPass implements CompilerPassInterface
  20. {
  21. use PriorityTaggedServiceTrait;
  22. public function process(ContainerBuilder $container)
  23. {
  24. if (false === $container->hasDefinition('twig')) {
  25. return;
  26. }
  27. $definition = $container->getDefinition('twig');
  28. // Extensions must always be registered before everything else.
  29. // For instance, global variable definitions must be registered
  30. // afterward. If not, the globals from the extensions will never
  31. // be registered.
  32. $currentMethodCalls = $definition->getMethodCalls();
  33. $twigBridgeExtensionsMethodCalls = [];
  34. $othersExtensionsMethodCalls = [];
  35. foreach ($this->findAndSortTaggedServices('twig.extension', $container) as $extension) {
  36. $methodCall = ['addExtension', [$extension]];
  37. $extensionClass = $container->getDefinition((string) $extension)->getClass();
  38. if (\is_string($extensionClass) && 0 === strpos($extensionClass, 'Symfony\Bridge\Twig\Extension')) {
  39. $twigBridgeExtensionsMethodCalls[] = $methodCall;
  40. } else {
  41. $othersExtensionsMethodCalls[] = $methodCall;
  42. }
  43. }
  44. if (!empty($twigBridgeExtensionsMethodCalls) || !empty($othersExtensionsMethodCalls)) {
  45. $definition->setMethodCalls(array_merge($twigBridgeExtensionsMethodCalls, $othersExtensionsMethodCalls, $currentMethodCalls));
  46. }
  47. }
  48. }