Adds functions to Twig.

@param \Twig\Environment $twig The Twig Environment.
@return \Twig\Environment
196934
public function add_timber_functions( $twig ) {
		/* actions and filters */
		$twig->addFunction(new Twig_Function('action', function( $context ) {
					$args = func_get_args();
					array_shift($args);
					$args[] = $context;
					call_user_func_array('do_action', $args);
				}, array('needs_context' => true)));

		$twig->addFunction(new Twig_Function('function', array(&$this, 'exec_function')));
		$twig->addFunction(new Twig_Function('fn', array(&$this, 'exec_function')));

		$twig->addFunction(new Twig_Function('shortcode', 'do_shortcode'));

		/* TimberObjects */
		$twig->addFunction(new Twig_Function('TimberPost', function( $pid, $PostClass = 'Timber\Post' ) {
					if ( is_array($pid) && !Helper::is_array_assoc($pid) ) {
						foreach ( $pid as &$p ) {
							$p = new $PostClass($p);
						}
						return $pid;
					}
					return new $PostClass($pid);
				} ));
		$twig->addFunction(new Twig_Function('TimberImage', function( $pid = false, $ImageClass = 'Timber\Image' ) {
					if ( is_array($pid) && !Helper::is_array_assoc($pid) ) {
						foreach ( $pid as &$p ) {
							$p = new $ImageClass($p);
						}
						return $pid;
					}
					return new $ImageClass($pid);
				} ));

		$twig->addFunction(new Twig_Function('TimberTerm', array($this, 'handle_term_object')));

		$twig->addFunction(new Twig_Function('TimberUser', function( $pid, $UserClass = 'Timber\User' ) {
					if ( is_array($pid) && !Helper::is_array_assoc($pid) ) {
						foreach ( $pid as &$p ) {
							$p = new $UserClass($p);
						}
						return $pid;
					}
					return new $UserClass($pid);
				} ));

		/* TimberObjects Alias */
		$twig->addFunction(new Twig_Function('Post', function( $pid, $PostClass = 'Timber\Post' ) {
					if ( is_array($pid) && !Helper::is_array_assoc($pid) ) {
						foreach ( $pid as &$p ) {
							$p = new $PostClass($p);
						}
						return $pid;
					}
					return new $PostClass($pid);
				} ));
		$twig->addFunction(new Twig_Function('Image', function( $pid, $ImageClass = 'Timber\Image' ) {
					if ( is_array($pid) && !Helper::is_array_assoc($pid) ) {
						foreach ( $pid as &$p ) {
							$p = new $ImageClass($p);
						}
						return $pid;
					}
					return new $ImageClass($pid);
				} ));
		$twig->addFunction(new Twig_Function('Term', array($this, 'handle_term_object')));
		$twig->addFunction(new Twig_Function('User', function( $pid, $UserClass = 'Timber\User' ) {
					if ( is_array($pid) && !Helper::is_array_assoc($pid) ) {
						foreach ( $pid as &$p ) {
							$p = new $UserClass($p);
						}
						return $pid;
					}
					return new $UserClass($pid);
				} ));

		/* bloginfo and translate */
		$twig->addFunction(new Twig_Function('bloginfo', 'bloginfo'));
		$twig->addFunction(new Twig_Function('__', '__'));
		$twig->addFunction(new Twig_Function('translate', 'translate'));
		$twig->addFunction(new Twig_Function('_e', '_e'));
		$twig->addFunction(new Twig_Function('_n', '_n'));
		$twig->addFunction(new Twig_Function('_x', '_x'));
		$twig->addFunction(new Twig_Function('_ex', '_ex'));
		$twig->addFunction(new Twig_Function('_nx', '_nx'));
		$twig->addFunction(new Twig_Function('_n_noop', '_n_noop'));
		$twig->addFunction(new Twig_Function('_nx_noop', '_nx_noop'));
		$twig->addFunction(new Twig_Function('translate_nooped_plural', 'translate_nooped_plural'));

		return $twig;
	}
678759
public function add_to_twig( $twig ) {
		$twig->addExtension( new Twig_Extension_StringLoader() );
		$twig->addFilter( new Twig_SimpleFilter( 'myfoo', array( $this, 'myfoo' ) ) );
		return $twig;
	}
1277604
public function compile(\Twig_Compiler $compiler) {
		$compiler->addDebugInfo($this);

		list($msg, $vars) = $this->compileString($this->getNode('body'));

		if (null !== $this->getNode('plural')) {
			list($msg1, $vars1) = $this->compileString($this->getNode('plural'));

			$vars = array_merge($vars, $vars1);
		}

		$function = null === $this->getNode('plural') ? 'Translation::translate' : 'Translation::translate_plural';

		if ($vars) {
			$compiler
				->write('echo strtr('.$function.'(')
				->subcompile($msg)
			;

			if (null !== $this->getNode('plural')) {
				$compiler
					->raw(', ')
					->subcompile($msg1)
					->raw(', abs(')
					->subcompile($this->getNode('count'))
					->raw(')')
				;
			}

			$compiler->raw(', $context[\'env\'][\'translation\']), array(');

			foreach ($vars as $var) {
				if ('count' === $var->getAttribute('name')) {
					$compiler
						->string('%count%')
						->raw(' => abs(')
						->subcompile($this->getNode('count'))
						->raw('), ')
					;
				} else {
					$compiler
						->string('%'.$var->getAttribute('name').'%')
						->raw(' => ')
						->subcompile($var)
						->raw(', ')
					;
				}
			}

			$compiler->raw("));\n");
		} else {
			$compiler
				->write('echo '.$function.'(')
				->subcompile($msg)
			;

			if (null !== $this->getNode('plural')) {
				$compiler
					->raw(', ')
					->subcompile($msg1)
					->raw(', abs(')
					->subcompile($this->getNode('count'))
					->raw(')')
				;
			}

			$compiler->raw(", " . '$context[\'env\'][\'translation\']' . ");\n");
		}
	}
1134313
public function compile(Twig_Compiler $compiler)
    {
        $compiler->addDebugInfo($this)
                 ->write('ob_start();' . PHP_EOL)
                 ->subcompile($this->getNode('value'))
                 ->write('$content = ob_get_clean();' . PHP_EOL)
                 ->write('preg_match("/^\s*/", $content, $matches);' . PHP_EOL)
                 ->write('$lines = explode("\n", $content);'.PHP_EOL)
                 ->write('$content = preg_replace(\'/^\' . $matches[0]. \'/\', "", $lines);' . PHP_EOL)
                 ->write('$content = implode("\n", $content);' . PHP_EOL)
                 ->write('echo $this->env->getTags()["markdown"]
                                    ->getMarkdown()
                                    ->parse($content);
                '.PHP_EOL);
    }
1046375
public function compile(\Twig_Compiler $compiler)
    {
        $compiler->addDebugInfo($this);

        $compiler
            ->raw('ob_start();' . PHP_EOL)
            ->subcompile($this->getNode('source'))
            ->raw('$source = ob_get_contents();' . PHP_EOL)
            ->raw('ob_clean();' . PHP_EOL)
            ->raw('echo $this->env->getExtension(\'highlight_extension\')->highlight(' . PHP_EOL)
            ->raw('   $source,' . PHP_EOL)
            ->raw('   \'' . $this->getNode('lexer')->getAttribute('name') . '\' ' . PHP_EOL)
            ->raw(');' . PHP_EOL);
    }
1005036
protected function registerTwigParser()
    {
        /*
         * Register system Twig environment
         */
        App::singleton('twig.environment', function ($app) {
            $twig = new Twig_Environment(new TwigLoader, ['auto_reload' => true]);
            $twig->addExtension(new TwigExtension);
            return $twig;
        });

        /*
         * Register .htm extension for Twig views
         */
        App::make('view')->addExtension('htm', 'twig', function () {
            return new TwigEngine(App::make('twig.environment'));
        });
    }
379336
public function getFunctions(): array
    {
        return [
            new TwigFunction('elementExists', function ($name) {
                return $this->view->elementExists($name);
            }),
            new TwigFunction('getVars', function () {
                return $this->view->getVars();
            }),
            new TwigFunction('get', function ($var, $default = null) {
                return $this->view->get($var, $default);
            }),
        ];
    }
1030453
public function addFilter($function, $callback = null, $options = [])
    {
        $filter = $this->filter($function, $callback, $options);

        return $this->twigEnvironment->addFilter($filter);
    }
635762
public function compile(Twig_Compiler $compiler)
    {
        $compiler
            ->addDebugInfo($this)
            // the (array) cast bypasses a PHP 5.2.6 bug
            ->write("\$context['_parent'] = (array) \$context;\n")
            ->write("\$context['_seq'] = twig_ensure_traversable(")
            ->subcompile($this->getNode('seq'))
            ->raw(");\n")
        ;

        if (null !== $this->getNode('else')) {
            $compiler->write("\$context['_iterated'] = false;\n");
        }

        if ($this->getAttribute('with_loop')) {
            $compiler
                ->write("\$context['loop'] = array(\n")
                ->write("  'parent' => \$context['_parent'],\n")
                ->write("  'index0' => 0,\n")
                ->write("  'index'  => 1,\n")
                ->write("  'first'  => true,\n")
                ->write(");\n")
            ;

            if (!$this->getAttribute('ifexpr')) {
                $compiler
                    ->write("if (is_array(\$context['_seq']) || (is_object(\$context['_seq']) && \$context['_seq'] instanceof Countable)) {\n")
                    ->indent()
                    ->write("\$length = count(\$context['_seq']);\n")
                    ->write("\$context['loop']['revindex0'] = \$length - 1;\n")
                    ->write("\$context['loop']['revindex'] = \$length;\n")
                    ->write("\$context['loop']['length'] = \$length;\n")
                    ->write("\$context['loop']['last'] = 1 === \$length;\n")
                    ->outdent()
                    ->write("}\n")
                ;
            }
        }

        $this->loop->setAttribute('else', null !== $this->getNode('else'));
        $this->loop->setAttribute('with_loop', $this->getAttribute('with_loop'));
        $this->loop->setAttribute('ifexpr', $this->getAttribute('ifexpr'));

        $compiler
            ->write("foreach (\$context['_seq'] as ")
            ->subcompile($this->getNode('key_target'))
            ->raw(" => ")
            ->subcompile($this->getNode('value_target'))
            ->raw(") {\n")
            ->indent()
            ->subcompile($this->getNode('body'))
            ->outdent()
            ->write("}\n")
        ;

        if (null !== $this->getNode('else')) {
            $compiler
                ->write("if (!\$context['_iterated']) {\n")
                ->indent()
                ->subcompile($this->getNode('else'))
                ->outdent()
                ->write("}\n")
            ;
        }

        $compiler->write("\$_parent = \$context['_parent'];\n");

        // remove some "private" loop variables (needed for nested loops)
        $compiler->write('unset($context[\'_seq\'], $context[\'_iterated\'], $context[\''.$this->getNode('key_target')->getAttribute('name').'\'], $context[\''.$this->getNode('value_target')->getAttribute('name').'\'], $context[\'_parent\'], $context[\'loop\']);'."\n");

        // keep the values set in the inner context for variables defined in the outer context
        $compiler->write("\$context = array_intersect_key(\$context, \$_parent) + \$_parent;\n");
    }
820924
public function compile(Twig_Compiler $compiler)
    {
        $compiler->addDebugInfo($this);

        list($msg, $vars) = $this->compileString($this->getNode('body'));

        if (null !== $this->getNode('plural')) {
            list($msg1, $vars1) = $this->compileString($this->getNode('plural'));

            $vars = array_merge($vars, $vars1);
        }

        // Modified row to work with WordPress.
        $function = null === $this->getNode('plural') ? '__' : '_n';

        if (null !== $notes = $this->getNode('notes')) {
            $message = trim($notes->getAttribute('data'));

            // line breaks are not allowed cause we want a single line comment
            $message = str_replace(array("\n", "\r"), ' ', $message);
            $compiler->write("// notes: {$message}\n");
        }

        if ($vars) {
            $compiler
                ->write('echo strtr('.$function.'(')
                ->subcompile($msg)
            ;

            if (null !== $this->getNode('plural')) {
                $compiler
                    ->raw(', ')
                    ->subcompile($msg1)
                    ->raw(', abs(')
                    ->subcompile($this->getNode('count'))
                    ->raw(')')
                ;
            }

            $compiler->raw('), array(');

            foreach ($vars as $var) {
                if ('count' === $var->getAttribute('name')) {
                    $compiler
                        ->string('%count%')
                        ->raw(' => abs(')
                        ->subcompile($this->getNode('count'))
                        ->raw('), ')
                    ;
                } else {
                    $compiler
                        ->string('%'.$var->getAttribute('name').'%')
                        ->raw(' => ')
                        ->subcompile($var)
                        ->raw(', ')
                    ;
                }
            }

            $compiler->raw("));\n");
        } else {
            if (null !== $this->getNode('plural')) {
                $compiler
                    ->write('echo sprintf( '.$function.'(')
                    ->subcompile($msg)
                ;

                $compiler
                    ->raw(', ')
                    ->subcompile($msg1)
                    ->raw(', abs(')
                    ->subcompile($this->getNode('count'))
                    ->raw(')')
                ;
            } else {
                $compiler
                    ->write('echo '.$function.'(')
                    ->subcompile($msg)
                ;
            }

            $theme  = wp_get_theme();
            $domain = $theme->get('TextDomain');
            $compiler->raw(', "' . $domain . '"');

            if (null !== $this->getNode('plural')) {
                $compiler->raw(') , ')
                    ->subcompile($this->getNode('count'));
            }

            $compiler->raw(");\n");
        }
    }
1191456
public function enterNode(Twig_NodeInterface $node, Twig_Environment $env)
    {
        if ($node instanceof Twig_Node_Module) {
            if ($env->hasExtension('escaper') && $defaultStrategy = $env->getExtension('escaper')->getDefaultStrategy($node->getAttribute('filename'))) {
                $this->defaultStrategy = $defaultStrategy;
            }
            $this->safeVars = array();
        } elseif ($node instanceof Twig_Node_AutoEscape) {
            $this->statusStack[] = $node->getAttribute('value');
        } elseif ($node instanceof Twig_Node_Block) {
            $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env);
        } elseif ($node instanceof Twig_Node_Import) {
            $this->safeVars[] = $node->getNode('var')->getAttribute('name');
        }

        return $node;
    }
1066076
public function getFunctions()
    {
        return array_merge(parent::getFunctions(), [
            new \Twig_SimpleFunction('getBlockElementsHtml', [$this, 'getBlockElementsHtml'], ['is_safe' => ['html']]),
            new \Twig_SimpleFunction('getElementHtml', [$this, 'getElementHtml'], ['is_safe' => ['html']]),
            new \Twig_SimpleFunction('getCollectionPages', [$this, 'getCollectionPages']),
            new \Twig_SimpleFunction('getGallery', [$this, 'getGallery']),
        ]);
    }
192237
public function compile(Twig_Compiler $compiler)
    {
        $getExtension = sprintf('$this->env->getExtension(\'%s\')', ZichtFrameworkExtraExtension::class);
        $compiler
            ->addDebugInfo($this)
            ->write('echo $this->env->getExtension(\'actions\')->renderAction(')
            ->subcompile($this->wrapped->getNode('expr'))
            ->raw(', ')
            ->raw(sprintf('%s->embed(', $getExtension))
            ->subcompile($this->wrapped->getNode('attributes'))
            ->raw(')')
            ->raw(', ')
            ->subcompile($this->wrapped->getNode('options'))
            ->raw(");\n");
    }
780071
protected function createTwigLintCommand() {
    $twig = new Environment(new FilesystemLoader());

    $repo_root = $this->getConfigValue('repo.root');
    $extension_file_contents = file_get_contents($repo_root . '/docroot/core/lib/Drupal/Core/Template/TwigExtension.php');

    // Get any custom defined Twig filters to be ignored by linter.
    $twig_filters = (array) $this->getConfigValue('validate.twig.filters');

    // Add Twig filters from Drupal TwigExtension to be ignored.
    $drupal_filters = [];
    if ($matches_count = preg_match_all("#new \\\\Twig_SimpleFilter\('([^']+)',#", $extension_file_contents, $matches)) {
      $drupal_filters = $matches[1];
    }
    $twig_filters = array_merge($twig_filters, $drupal_filters);
    foreach ($twig_filters as $filter) {
      // Add two default arguments and set to variadic so that filters with
      // named arguments will be whitelisted.
      // @see \TwigNode_Expression_Call::getArguments
      // @see \TwigNode_Expression_Call::call()
      $twig->addFilter(new \Twig_SimpleFilter($filter, function ($node = '', array $args = []) {}, [
        'is_variadic' => TRUE,
      ]));
    }

    // Get any custom defined Twig functions to be ignored by linter.
    $twig_functions = (array) $this->getConfigValue('validate.twig.functions');

    // Add Twig functions from Drupal TwigExtension to be ignored.
    $drupal_functions = [];
    if ($matches_count = preg_match_all("#new \\\\Twig_SimpleFunction\('([^']+)',#", $extension_file_contents, $matches)) {
      $drupal_functions = $matches[1];
    }
    $twig_functions = array_merge($twig_functions, $drupal_functions);
    foreach ($twig_functions as $function) {
      // Add default argument and set to variadic so that functions with named
      // arguments will be whitelisted.
      // @see \TwigNode_Expression_Call::getArguments
      // @see \TwigNode_Expression_Call::call()
      $twig->addFunction(new \Twig_SimpleFunction($function, function (array $args = []) {}, [
        'is_variadic' => TRUE,
      ]));
    }

    // Add Drupal Twig parser to include trans tag.
    $token_parser_filename = $repo_root . '/docroot/core/lib/Drupal/Core/Template/TwigTransTokenParser.php';
    if (file_exists($token_parser_filename)) {
      require_once $token_parser_filename;
      $twig->addTokenParser(new TwigTransTokenParser());
    }

    $command = new TwigLintCommand();
    $command->setTwigEnvironment($twig);

    return $command;
  }
279702
public function getFunctions()
    {
        return array(
            new Twig_SimpleFunction('max', 'max'),
            new Twig_SimpleFunction('min', 'min'),
            new Twig_SimpleFunction('range', 'range'),
            new Twig_SimpleFunction('constant', 'twig_constant'),
            new Twig_SimpleFunction('cycle', 'twig_cycle'),
            new Twig_SimpleFunction('random', 'twig_random', array('needs_environment' => true)),
            new Twig_SimpleFunction('date', 'twig_date_converter', array('needs_environment' => true)),
            new Twig_SimpleFunction('include', 'twig_include', array('needs_environment' => true, 'needs_context' => true, 'is_safe' => array('all'))),
            new Twig_SimpleFunction('source', 'twig_source', array('needs_environment' => true, 'is_safe' => array('all'))),
        );
    }
803306
public function getFunctions()
    {
        return [
            new \Twig_Function('begin_form',  [$this, 'beginForm']),
            new \Twig_Function('end_form',    [$this, 'endForm']),
            new \Twig_Function('form_field',  [$this, 'addFormField']),
            new \Twig_Function('text_area',   [$this, 'addTextArea']),
            new \Twig_Function('select_list', [$this, 'addSelectList']),
            new \Twig_Function('button',      [$this, 'addButton']),
            new \Twig_Function('csrf_token',  [$this, 'generateCsrfToken']),
        ];
    }
1162792
public function addTwigAssets()
    {
        if (!$this->twig instanceof \Twig_Environment) {
            throw new \LogicException('Twig environment not set');
        }
        $finder     = new Finder();
        $viewfinder = $this->viewfinder;
        if (count($viewfinder->getPaths()) > 0) {
            $iterator = $finder->files()->in($viewfinder->getPaths());
            foreach ($iterator as $file) {
                $resource = new TwigResource($this->loader, $file->getRelativePathname());
                $this->lam->addResource($resource, 'twig');
            }
        }
    }