You are here

public function TwigEnvironment::__construct in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Template/TwigEnvironment.php \Drupal\Core\Template\TwigEnvironment::__construct()

Constructs a TwigEnvironment object and stores cache and storage internally.

Parameters

string $root: The app root.

\Drupal\Core\Cache\CacheBackendInterface $cache: The cache bin.

string $twig_extension_hash: The Twig extension hash.

\Drupal\Core\State\StateInterface $state: The state service.

\Twig\Loader\LoaderInterface $loader: The Twig loader or loader chain.

array $options: The options for the Twig environment.

File

core/lib/Drupal/Core/Template/TwigEnvironment.php, line 69

Class

TwigEnvironment
A class that defines a Twig environment for Drupal.

Namespace

Drupal\Core\Template

Code

public function __construct($root, CacheBackendInterface $cache, $twig_extension_hash, StateInterface $state, LoaderInterface $loader, array $options = []) {
  $this->state = $state;
  $this->templateClasses = [];
  $options += [
    // @todo Ensure garbage collection of expired files.
    'cache' => TRUE,
    'debug' => FALSE,
    'auto_reload' => NULL,
  ];

  // Ensure autoescaping is always on.
  $options['autoescape'] = 'html';
  if ($options['cache'] === TRUE) {
    $current = $state
      ->get(static::CACHE_PREFIX_METADATA_KEY, [
      'twig_extension_hash' => '',
    ]);
    if ($current['twig_extension_hash'] !== $twig_extension_hash || empty($current['twig_cache_prefix'])) {
      $current = [
        'twig_extension_hash' => $twig_extension_hash,
        // Generate a new prefix which invalidates any existing cached files.
        'twig_cache_prefix' => uniqid(),
      ];
      $state
        ->set(static::CACHE_PREFIX_METADATA_KEY, $current);
    }
    $this->twigCachePrefix = $current['twig_cache_prefix'];
    $options['cache'] = new TwigPhpStorageCache($cache, $this->twigCachePrefix);
  }
  $this
    ->setLoader($loader);
  parent::__construct($this
    ->getLoader(), $options);
  $policy = new TwigSandboxPolicy();
  $sandbox = new SandboxExtension($policy, TRUE);
  $this
    ->addExtension($sandbox);
}