TemplateCacheWarmer.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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\CacheWarmer;
  11. use Psr\Container\ContainerInterface;
  12. use Symfony\Component\HttpKernel\CacheWarmer\CacheWarmerInterface;
  13. use Symfony\Contracts\Service\ServiceSubscriberInterface;
  14. use Twig\Environment;
  15. use Twig\Error\Error;
  16. /**
  17. * Generates the Twig cache for all templates.
  18. *
  19. * @author Fabien Potencier <fabien@symfony.com>
  20. */
  21. class TemplateCacheWarmer implements CacheWarmerInterface, ServiceSubscriberInterface
  22. {
  23. private $container;
  24. private $twig;
  25. private $iterator;
  26. public function __construct(ContainerInterface $container, iterable $iterator)
  27. {
  28. // As this cache warmer is optional, dependencies should be lazy-loaded, that's why a container should be injected.
  29. $this->container = $container;
  30. $this->iterator = $iterator;
  31. }
  32. /**
  33. * {@inheritdoc}
  34. *
  35. * @return string[] A list of template files to preload on PHP 7.4+
  36. */
  37. public function warmUp(string $cacheDir)
  38. {
  39. if (null === $this->twig) {
  40. $this->twig = $this->container->get('twig');
  41. }
  42. $files = [];
  43. foreach ($this->iterator as $template) {
  44. try {
  45. $template = $this->twig->load($template);
  46. if (\is_callable([$template, 'unwrap'])) {
  47. $files[] = (new \ReflectionClass($template->unwrap()))->getFileName();
  48. }
  49. } catch (Error $e) {
  50. // problem during compilation, give up
  51. // might be a syntax error or a non-Twig template
  52. }
  53. }
  54. return $files;
  55. }
  56. /**
  57. * {@inheritdoc}
  58. */
  59. public function isOptional()
  60. {
  61. return true;
  62. }
  63. /**
  64. * {@inheritdoc}
  65. */
  66. public static function getSubscribedServices()
  67. {
  68. return [
  69. 'twig' => Environment::class,
  70. ];
  71. }
  72. }