You are here

public function TwigEnvironment::__construct in Drupal 8

Same name and namespace in other branches
  1. 9 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_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 63

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, \Twig_LoaderInterface $loader = NULL, array $options = []) {
  $this->state = $state;

  // Ensure that twig.engine is loaded, given that it is needed to render a
  // template because functions like TwigExtension::escapeFilter() are called.
  // @todo remove in Drupal 9.0.0 https://www.drupal.org/node/3011393.
  require_once $root . '/core/themes/engines/twig/twig.engine';
  $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 \Twig_Extension_Sandbox($policy, TRUE);
  $this
    ->addExtension($sandbox);
}