Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / vendor / chi-teck / drupal-code-generator / src / Twig / TwigEnvironment.php
1 <?php
2
3 namespace DrupalCodeGenerator\Twig;
4
5 use DrupalCodeGenerator\Utils;
6 use Twig_Environment;
7 use Twig_LoaderInterface;
8 use Twig_SimpleFilter;
9
10 /**
11  * Stores the Twig configuration.
12  */
13 class TwigEnvironment extends Twig_Environment {
14
15   /**
16    * Constructs Twig environment object.
17    *
18    * @param \Twig_LoaderInterface $loader
19    *   The Twig loader.
20    */
21   public function __construct(Twig_LoaderInterface $loader) {
22     parent::__construct($loader);
23
24     $this->addFilter(new Twig_SimpleFilter('plural', [Utils::class, 'pluralize']), ['deprecated' => TRUE]);
25
26     $this->addFilter(new Twig_SimpleFilter('pluralize', [Utils::class, 'pluralize']));
27
28     $this->addFilter(new Twig_SimpleFilter('article', function ($string) {
29       $article = in_array(strtolower($string[0]), ['a', 'e', 'i', 'o', 'u']) ? 'an' : 'a';
30       return $article . ' ' . $string;
31     }));
32
33     $this->addFilter(new Twig_SimpleFilter('underscore2hyphen', function ($string) {
34       // @codeCoverageIgnoreStart
35       return str_replace('_', '-', $string);
36       // @codeCoverageIgnoreEnd
37     }, ['deprecated' => TRUE]));
38
39     $this->addFilter(new Twig_SimpleFilter('hyphen2underscore', function ($string) {
40       // @codeCoverageIgnoreStart
41       return str_replace('-', '_', $string);
42       // @codeCoverageIgnoreEnd
43     }, ['deprecated' => TRUE]));
44
45     $this->addFilter(new Twig_SimpleFilter('u2h', function ($string) {
46       return str_replace('_', '-', $string);
47     }));
48
49     $this->addFilter(new Twig_SimpleFilter('h2u', function ($string) {
50       return str_replace('-', '_', $string);
51     }));
52
53     $this->addFilter(new Twig_SimpleFilter('camelize', function ($string, $upper_mode = TRUE) {
54       return Utils::camelize($string, $upper_mode);
55     }));
56
57     $this->addTokenParser(new TwigSortTokenParser());
58   }
59
60   /**
61    * {@inheritdoc}
62    */
63   public function tokenize($source, $name = NULL) {
64     if (!$source instanceof \Twig_Source) {
65       $source = new \Twig_Source($source, $name);
66     }
67     // Remove leading whitespaces to preserve indentation.
68     // @see https://github.com/twigphp/Twig/issues/1423
69     $code = $source->getCode();
70     if (strpos($code, '{% verbatim %}') === FALSE) {
71       $code = preg_replace("/\n +\{%/", "\n{%", $source->getCode());
72     }
73     // Twig source has no setters.
74     $source = new \Twig_Source($code, $source->getName(), $source->getPath());
75     return parent::tokenize($source, $name);
76   }
77
78 }