3 namespace DrupalCodeGenerator\Twig;
5 use DrupalCodeGenerator\Utils;
7 use Twig_LoaderInterface;
11 * Stores the Twig configuration.
13 class TwigEnvironment extends Twig_Environment {
16 * Constructs Twig environment object.
18 * @param \Twig_LoaderInterface $loader
21 public function __construct(Twig_LoaderInterface $loader) {
22 parent::__construct($loader);
24 $this->addFilter(new Twig_SimpleFilter('plural', [Utils::class, 'pluralize']), ['deprecated' => TRUE]);
26 $this->addFilter(new Twig_SimpleFilter('pluralize', [Utils::class, 'pluralize']));
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;
33 $this->addFilter(new Twig_SimpleFilter('underscore2hyphen', function ($string) {
34 // @codeCoverageIgnoreStart
35 return str_replace('_', '-', $string);
36 // @codeCoverageIgnoreEnd
37 }, ['deprecated' => TRUE]));
39 $this->addFilter(new Twig_SimpleFilter('hyphen2underscore', function ($string) {
40 // @codeCoverageIgnoreStart
41 return str_replace('-', '_', $string);
42 // @codeCoverageIgnoreEnd
43 }, ['deprecated' => TRUE]));
45 $this->addFilter(new Twig_SimpleFilter('u2h', function ($string) {
46 return str_replace('_', '-', $string);
49 $this->addFilter(new Twig_SimpleFilter('h2u', function ($string) {
50 return str_replace('-', '_', $string);
53 $this->addFilter(new Twig_SimpleFilter('camelize', function ($string, $upper_mode = TRUE) {
54 return Utils::camelize($string, $upper_mode);
57 $this->addTokenParser(new TwigSortTokenParser());
63 public function tokenize($source, $name = NULL) {
64 if (!$source instanceof \Twig_Source) {
65 $source = new \Twig_Source($source, $name);
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());
73 // Twig source has no setters.
74 $source = new \Twig_Source($code, $source->getName(), $source->getPath());
75 return parent::tokenize($source, $name);