Adds escapers to Twig.

@param \Twig\Environment $twig The Twig Environment.
@return \Twig\Environment
508410
public function add_timber_escapers( $twig ) {

		$twig->getExtension('Twig_Extension_Core')->setEscaper('esc_url', function( \Twig_Environment $env, $string ) {
			return esc_url($string);
		});
		$twig->getExtension('Twig_Extension_Core')->setEscaper('wp_kses_post', function( \Twig_Environment $env, $string ) {
			return wp_kses_post($string);
		});

		$twig->getExtension('Twig_Extension_Core')->setEscaper('esc_html', function( \Twig_Environment $env, $string ) {
			return esc_html($string);
		});

		$twig->getExtension('Twig_Extension_Core')->setEscaper('esc_js', function( \Twig_Environment $env, $string ) {
			return esc_js($string);
		});

		return $twig;

	}
1253650
protected function initTwigEnvironment()
    {
        $this->loader = new TwigLoader;

        $useCache = !Config::get('cms.twigNoCache');
        $isDebugMode = Config::get('app.debug', false);
        $strictVariables = Config::get('cms.enableTwigStrictVariables', false);
        $strictVariables = $strictVariables ?? $isDebugMode;
        $forceBytecode = Config::get('cms.forceBytecodeInvalidation', false);

        $options = [
            'auto_reload' => true,
            'debug' => $isDebugMode,
            'strict_variables' => $strictVariables,
        ];

        if ($useCache) {
            $options['cache'] = new Twig_Cache_Filesystem(
                storage_path().'/cms/twig',
                $forceBytecode ? Twig_Cache_Filesystem::FORCE_BYTECODE_INVALIDATION : 0
            );
        }

        $this->twig = new Twig_Environment($this->loader, $options);
        $this->twig->addExtension(new CmsTwigExtension($this));
        $this->twig->addExtension(new SystemTwigExtension);

        if ($isDebugMode) {
            $this->twig->addExtension(new DebugExtension($this));
        }
    }
937471
public function renderStripeScripts(Twig_Environment $environment)
    {
        $environment->display($this->scriptsTemplate, [
            'public_key' => $this->publicKey,
            'currency' => $this->paymentBridgeInterface->getCurrency(),
        ]);
    }
925452
public function compile(Twig_Compiler $compiler)
    {
        $compiler
            ->addDebugInfo($this)
            ->write(sprintf("public function block_%s(\$context, array \$blocks = array())\n", $this->getAttribute('name')), "{\n")
            ->indent()
        ;

        $compiler
            ->subcompile($this->getNode('body'))
            ->outdent()
            ->write("}\n\n")
        ;
    }
1271419
public function compile(\Twig_Compiler $compiler)
    {
        $compiler->addDebugInfo($this);
		
        $compiler->write("try {\n")->indent();		
		
        $compiler
             ->write("\Cetera\Application::getInstance()->getWidget(")
             ->subcompile($this->getNode('expr'));
			 
		if ($this->getNode('variables'))
		{
			 $compiler
				 ->raw(', ')
				 ->subcompile($this->getNode('variables'));
		}
				 
        $compiler->raw(")->display();\n");	

        $compiler
                ->outdent()
                ->write("} catch (\\Exception \$e) {\n")
                ->indent()
                //->write("echo '<div class=\"callout alert\">'.\$e->getMessage().'</div>';\n")
				->write("echo '<!-- '.\$e->getMessage().' -->';\n")
                ->outdent()
                ->write("}\n\n")
        ;		 

    }
722267
public function addTwigAssets()
    {
        if (!$this->twig instanceof \Twig_Environment) {
            throw new \LogicException('Twig environment not set');
        }

        $twigNamespaces = $this->loader->getNamespaces();

        foreach ($twigNamespaces as $ns) {

            if ( count($this->loader->getPaths($ns)) > 0 ) {
                $iterator = Finder::create()->files()->in($this->loader->getPaths($ns));

                foreach ($iterator as $file) {
                    $resource = new TwigResource($this->loader, '@' . $ns . '/' . $file->getRelativePathname());
                    $this->lam->addResource($resource, 'twig');
                }
            }
        }
    }
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;
	}
1155194
private function registerExtension(\Twig_Environment $twig)
    {
        $extensions = $this->getExtensions();
        if (count($extensions)) {
            foreach ($extensions as $key => $extension) {
                $this->load($twig, $key, $extension);
            }
        }
    }
566274
public function renderBuildForm(\Twig_Environment $environment, $template = 'DarvinImageBundle:Archive/widget:build_form.html.twig')
    {
        if (empty($this->archiveFormFactory)) {
            return '';
        }

        return $environment->render($template, [
            'form' => $this->archiveFormFactory->createBuildFormView(),
        ]);
    }
1066555
public function compile(Twig_Compiler $compiler)
    {
        $compiler
            ->addDebugInfo($this)
            ->write('if(!isset($withStack)) {' . "\n")
            ->indent()
            ->write('$withStack = array();' . "\n")
            ->outdent()
            ->write('}' . "\n")
            ->write("\n")
            ->write('array_push($withStack, $context);' . "\n");

        $compiler->write('$values = array_merge(' . "\n")->indent();
        $i = 0;
        foreach ($this->getAttribute('items') as $argument) {
            if ($i ++ > 0) {
                $compiler->raw(',' . "\n");
            }
            $this->compileArgument($compiler, $argument);
        }
        $compiler->raw("\n")->outdent()->write(");\n");

        if (!$this->hasOption('always')) {
            $compiler->write(
                'if (count(array_filter($values, function($o) {
                    if ($o instanceof \Countable) {
                        return count($o) > 0;
                    } else {
                        return !empty($o);
                    }
                }))) {'
            );
        }

        if ($this->hasOption('merged')) {
            $compiler->write('$values += $context;' . "\n");
        } else {
            $compiler->write('$values += array(\'_parent\' => $context);');
        }

        $compiler
            ->write('$context = $values;')
            ->subcompile($this->getNode('body'));

        if (!$this->hasOption('always')) {
            $compiler->write('}');
        }
        $compiler->write('$context = array_pop($withStack);' . "\n");
    }
635910
public function prependTwigLoader(\Twig_LoaderInterface $twig_loader)
    {
      // Give precedence to the passed in loader
        $this->twig_loader = new \Twig_Loader_Chain(array($twig_loader, $this->twig_loader));
        return $this;
    }
895954
public function install(Environment $twig): Environment
    {
        $twig = clone $twig;

        $extension = new Extension($this->pipeline);
        $twig->addExtension($extension);

        $compiler = new PatchingCompiler($twig);
        $twig->setCompiler($compiler);

        return $twig;
    }
525477
protected function getTwig()
    {
        if (null === $this->twig) {
            $this->twig = new \Twig_Environment(new \Twig_Loader_Filesystem(self::TEMPLATE_DIR), [
                'debug'            => true,
                'cache'            => false,
                'strict_variables' => true,
                'autoescape'       => false,
            ]);

            $this->twig->addExtension(new StringExtension());

            $class = sprintf(
                '\Gdbots\Pbjc\Generator\Twig\%sGeneratorExtension',
                StringUtils::toCamelFromSlug(static::LANGUAGE)
            );

            $this->twig->addExtension(new $class($this->compileOptions, $this));
        }

        return $this->twig;
    }
719610
protected function getTwig()
    {
        $options = [
            'cache' => false,
            'strict_variables' => true,
        ];

        $loader = new \Twig_Loader_Filesystem();
        $loader->setPaths($this->skeletonDirs);

        return new \Twig_Environment($loader, $options);
    }
871195
public function filter_twig( $twig ) {
		$twig->addFilter( new Twig_SimpleFilter( 'get_timber_image', 'get_timber_image' ) );
		$twig->addFilter( new Twig_SimpleFilter( 'get_timber_image_src', 'get_timber_image_src' ) );
		$twig->addFilter( new Twig_SimpleFilter( 'get_timber_image_responsive', 'get_timber_image_responsive' ) );
		$twig->addFilter( new Twig_SimpleFilter( 'get_timber_image_responsive_src', 'get_timber_image_responsive_src' ) );

		$twig->addFilter( new Twig_SimpleFilter( 'lazy', 'make_timber_image_lazy' ) );

		$twig->addFunction( new \Twig_SimpleFunction( 'get_timber_image_responsive_acf', 'get_timber_image_responsive_acf' ) );

		return $twig;
	}
1279292
public function getTwig(array $options = array())
    {
        if (is_null($this->twig)) {
            $page = Page::html();
            foreach (array('content', 'plugins', 'themes') as $dir) {
                if (!is_dir($this->blog->folder.$dir)) {
                    mkdir($this->blog->folder.$dir, 0755, true);
                }
            }
            $loader = new \Twig_Loader_Filesystem($page->dir['page'], $page->dir['page']);
            $loader->addPath($this->blog->folder.'plugins/', 'plugin');
            $this->twig = new \Twig_Environment($loader, array_merge(array(
                'cache' => $this->blog->folder.'cache/twig/',
                'auto_reload' => true,
                'autoescape' => false,
            ), $options));
            $this->twig->addExtension(new MarkdownExtension(new Markdown($this)));
            $this->twig->addFilter(new \Twig_SimpleFilter('asset', array($this, 'asset')));
            $this->twig->addFunction(new \Twig_SimpleFunction('dir', array($this, 'dir')));
            $this->twig->addFunction(new \Twig_SimpleFunction('this', array($this, 'this')));
            $this->twig->addFunction(new \Twig_SimpleFunction('dump', array($this, 'dump'), array('is_safe' => 'html')));
            $this->twig->registerUndefinedFunctionCallback(function ($name) {
                switch ($name) {
                    // Array Functions
                    case 'array_change_key_case': // Changes the case of all keys in an array
                    case 'array_chunk': // Split an array into chunks
                    case 'array_column': // Return the values from a single column in the input array
                    case 'array_combine': // Creates an array by using one array for keys and another for its values
                    case 'array_count_values': // Counts all the values of an array
                    case 'array_diff_assoc': // Computes the difference of arrays with additional index check
                    case 'array_diff_key': // Computes the difference of arrays using keys for comparison
                    case 'array_diff': // Computes the difference of arrays
                    case 'array_fill_keys': // Fill an array with values, specifying keys
                    case 'array_fill': // Fill an array with values
                    case 'array_filter': // Filters elements of an array using a callback function
                    case 'array_flip': // Exchanges all keys with their associated values in an array
                    case 'array_intersect_assoc': // Computes the intersection of arrays with additional index check
                    case 'array_intersect_key': // Computes the intersection of arrays using keys for comparison
                    case 'array_intersect': // Computes the intersection of arrays
                    case 'array_key_exists': // Checks if the given key or index exists in the array
                    case 'array_keys': // Return all the keys or a subset of the keys of an array
                    case 'array_map': // Applies the callback to the elements of the given arrays
                    case 'array_merge_recursive': // Merge two or more arrays recursively
                    case 'array_merge': // Merge one or more arrays
                    case 'array_pad': // Pad array to the specified length with a value
                    case 'array_product': // Calculate the product of values in an array
                    case 'array_rand': // Pick one or more random entries out of an array
                    case 'array_replace_recursive': // Replaces elements from passed arrays into the first array recursively
                    case 'array_replace': // Replaces elements from passed arrays into the first array
                    case 'array_reverse': // Return an array with elements in reverse order
                    case 'array_search': // Searches the array for a given value and returns the first corresponding key if successful
                    case 'array_slice': // Extract a slice of the array
                    case 'array_sum': // Calculate the sum of values in an array
                    case 'array_unique': // Removes duplicate values from an array
                    case 'array_values': // Return all the values of an array
                    case 'count': // Count all elements in an array, or something in an object
                    case 'in_array': // Checks if a value exists in an array

                    // Date/Time Functions
                    case 'date_parse': // Returns associative array with detailed info about given date
                    case 'date_sun_info': // Returns an array with information about sunset/sunrise and twilight begin/end
                    case 'getdate': // Get date/time information
                    case 'gettimeofday': // Get current time
                    case 'gmdate': // Format a GMT/UTC date/time
                    case 'gmmktime': // Get Unix timestamp for a GMT date
                    case 'microtime': // Return current Unix timestamp with microseconds
                    case 'mktime': // Get Unix timestamp for a date
                    case 'strtotime': // Parse about any English textual datetime description into a Unix timestamp
                    case 'time': // Return current Unix timestamp

                    // JSON Functions
                    case 'json_decode': // Decodes a JSON string
                    case 'json_encode': // Returns the JSON representation of a value

                    // Mail Functions
                    case 'mail': // Send mail

                    // Math Functions
                    case 'abs': // Absolute value
                    case 'acos': // Arc cosine
                    case 'acosh': // Inverse hyperbolic cosine
                    case 'asin': // Arc sine
                    case 'asinh': // Inverse hyperbolic sine
                    case 'atan2': // Arc tangent of two variables
                    case 'atan': // Arc tangent
                    case 'atanh': // Inverse hyperbolic tangent
                    case 'base_convert': // Convert a number between arbitrary bases
                    case 'bindec': // Binary to decimal
                    case 'ceil': // Round fractions up
                    case 'cos': // Cosine
                    case 'cosh': // Hyperbolic cosine
                    case 'decbin': // Decimal to binary
                    case 'dechex': // Decimal to hexadecimal
                    case 'decoct': // Decimal to octal
                    case 'deg2rad': // Converts the number in degrees to the radian equivalent
                    case 'exp': // Calculates the exponent of e
                    case 'expm1': // Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero
                    case 'floor': // Round fractions down
                    case 'fmod': // Returns the floating point remainder (modulo) of the division of the arguments
                    case 'getrandmax': // Show largest possible random value
                    case 'hexdec': // Hexadecimal to decimal
                    case 'hypot': // Calculate the length of the hypotenuse of a right-angle triangle
                    case 'is_finite': // Finds whether a value is a legal finite number
                    case 'is_infinite': // Finds whether a value is infinite
                    case 'is_nan': // Finds whether a value is not a number
                    case 'lcg_value': // Combined linear congruential generator
                    case 'log10': // Base-10 logarithm
                    case 'log1p': // Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero
                    case 'log': // Natural logarithm
                    case 'mt_getrandmax': // Show largest possible random value
                    case 'mt_rand': // Generate a better random value
                    case 'mt_srand': // Seed the better random number generator
                    case 'octdec': // Octal to decimal
                    case 'pi': // Get value of pi
                    case 'pow': // Exponential expression
                    case 'rad2deg': // Converts the radian number to the equivalent number in degrees
                    case 'rand': // Generate a random integer
                    case 'round': // Rounds a float
                    case 'sin': // Sine
                    case 'sinh': // Hyperbolic sine
                    case 'sqrt': // Square root
                    case 'srand': // Seed the random number generator
                    case 'tan': // Tangent
                    case 'tanh': // Hyperbolic tangent

                    // Misc Functions
                    case 'pack': //  Pack data into binary string
                    case 'unpack': // Unpack data from binary string

                    // Multibyte String Functions
                    case 'mb_convert_case': // Perform case folding on a string
                    case 'mb_convert_encoding': // Convert character encoding
                    case 'mb_strimwidth': // Get truncated string with specified width
                    case 'mb_stripos': // Finds position of first occurrence of a string within another, case insensitive
                    case 'mb_stristr': // Finds first occurrence of a string within another, case insensitive
                    case 'mb_strlen': // Get string length
                    case 'mb_strpos': // Find position of first occurrence of string in a string
                    case 'mb_strrchr': // Finds the last occurrence of a character in a string within another
                    case 'mb_strrichr': // Finds the last occurrence of a character in a string within another, case insensitive
                    case 'mb_strripos': // Finds position of last occurrence of a string within another, case insensitive
                    case 'mb_strrpos': // Find position of last occurrence of a string in a string
                    case 'mb_strstr': // Finds first occurrence of a string within another
                    case 'mb_strtolower': // Make a string lowercase
                    case 'mb_strtoupper': // Make a string uppercase
                    case 'mb_strwidth': // Return width of string
                    case 'mb_substr_count': // Count the number of substring occurrences
                    case 'mb_substr': // Get part of string

                    // String Functions
                    case 'addcslashes': // Quote string with slashes in a C style
                    case 'addslashes': // Quote string with slashes
                    case 'bin2hex': // Convert binary data into hexadecimal representation
                    case 'chr': // Return a specific character - complements ord()
                    case 'chunk_split': // Split a string into smaller chunks
                    case 'explode': // Split a string by string
                    case 'hex2bin': // Decodes a hexadecimally encoded binary string
                    case 'htmlspecialchars': // Convert special characters to HTML entities
                    case 'implode': // Join array elements with a string
                    case 'lcfirst': // Make a string's first character lowercase
                    case 'ltrim': // Strip whitespace (or other characters) from the beginning of a string
                    case 'nl2br': // Inserts HTML line breaks before all newlines in a string
                    case 'number_format': // Format a number with grouped thousands
                    case 'ord': // Return ASCII value of character - complements chr()
                    case 'rtrim': // Strip whitespace (or other characters) from the end of a string
                    case 'str_ireplace': // Case-insensitive version of str_replace()
                    case 'str_pad': // Pad a string to a certain length with another string
                    case 'str_repeat': // Repeat a string
                    case 'str_replace': // Replace all occurrences of the search string with the replacement string
                    case 'str_rot13': // Perform the rot13 transform on a string
                    case 'str_shuffle': // Randomly shuffles a string
                    case 'str_split': // Convert a string to an array
                    case 'str_word_count': // Return information about words used in a string
                    case 'strip_tags': // Strip HTML and PHP tags from a string
                    case 'stripos': // Find the position of the first occurrence of a case-insensitive substring in a string
                    case 'stristr': // Case-insensitive strstr()
                    case 'strlen': // Get string length
                    case 'strpos': // Find the position of the first occurrence of a substring in a string
                    case 'strrchr': // Find the last occurrence of a character in a string
                    case 'strrev': // Reverse a string
                    case 'strripos': // Find the position of the last occurrence of a case-insensitive substring in a string
                    case 'strrpos': // Find the position of the last occurrence of a substring in a string
                    case 'strstr': // Find the first occurrence of a string
                    case 'strtok': // Tokenize string
                    case 'strtolower': // Make a string lowercase
                    case 'strtoupper': // Make a string uppercase
                    case 'strtr': // Translate characters or replace substrings
                    case 'substr_count': // Count the number of substring occurrences
                    case 'substr': // Return part of a string
                    case 'trim': // Strip whitespace (or other characters) from the beginning and end of a string
                    case 'ucfirst': // Make a string's first character uppercase
                    case 'ucwords': // Uppercase the first character of each word in a string
                    case 'wordwrap': // Wraps a string to a given number of characters

                    // Variable handling Functions
                    case 'gettype': // Get the type of a variable
                    case 'is_array': // Finds whether a variable is an array
                    case 'is_bool': // Finds out whether a variable is a boolean
                    case 'is_float': // Finds whether the type of a variable is float
                    case 'is_int': // Find whether the type of a variable is integer
                    case 'is_null': // Finds whether a variable is NULL
                    case 'is_numeric': // Finds whether a variable is a number or a numeric string
                    case 'is_string': // Find whether the type of a variable is string
                    case 'serialize': // Generates a storable representation of a value
                    case 'unserialize': // Creates a PHP value from a stored representation
                        return new \Twig_SimpleFunction($name, $name);
                        break;

                    // Return by reference, so we return directly
                    case 'array_pop': // Pop the element off the end of array
                    case 'array_shift': // Shift an element off the beginning of array
                    case 'array_splice': // Remove a portion of the array and replace it with something else
                    case 'arsort': // Sort an array in reverse order and maintain index association
                    case 'asort': // Sort an array and maintain index association
                    case 'krsort': // Sort an array by key in reverse order
                    case 'ksort': // Sort an array by key
                    case 'natcasesort': // Sort an array using a case insensitive "natural order" algorithm
                    case 'natsort': // Sort an array using a "natural order" algorithm
                    case 'rsort': // Sort an array in reverse order
                    case 'shuffle': // Shuffle an array
                    case 'sort': // Sort an array
                    case 'settype': // Set the type of a variable
                        return new \Twig_SimpleFunction($name, function () use ($name) {
                            $args = func_get_args();
                            $reference = array_shift($args);
                            switch (count($args)) {
                                case 0: $name($reference); break;
                                case 1: $name($reference, array_shift($args)); break;
                                case 2: $name($reference, array_shift($args), array_shift($args)); break;
                                default: $name($reference, array_shift($args), array_shift($args), array_shift($args)); break;
                            }

                            return $reference;
                        });
                        break;

                    // PCRE Functions
                    case 'preg_filter': // Perform a regular expression search and replace - 4
                    case 'preg_grep': // Return array entries that match the pattern
                    case 'preg_match_all': // Perform a global regular expression match
                    case 'preg_match': // Perform a regular expression match
                    case 'preg_quote': // Quote regular expression characters
                    case 'preg_replace': // Perform a regular expression search and replace - 4
                    case 'preg_split': // Split string by a regular expression - 3
                        return new \Twig_SimpleFunction($name, function () use ($name) {
                            $args = func_get_args();
                            $pattern = array_shift($args);
                            if ($name != 'preg_quote') {
                                $this->removeEval($pattern);
                            }
                            if (strpos($name, 'match')) {
                                $name($pattern, array_shift($args), $matches);

                                return $matches;
                            } else {
                                array_unshift($args, $pattern);

                                return call_user_func_array($name, $args);
                            }
                        });
                        break;
                }

                return false;
            });
        }

        return $this->twig;
    }
641901
protected function enterOptimizeFor(Twig_NodeInterface $node, Twig_Environment $env)
    {
        if ($node instanceof Twig_Node_For) {
            // disable the loop variable by default
            $node->setAttribute('with_loop', false);
            array_unshift($this->loops, $node);
        } elseif (!$this->loops) {
            // we are outside a loop
            return;
        }

        // when do we need to add the loop variable back?

        // the loop variable is referenced for the current loop
        elseif ($node instanceof Twig_Node_Expression_Name && 'loop' === $node->getAttribute('name')) {
            $this->addLoopToCurrent();
        }

        // block reference
        elseif ($node instanceof Twig_Node_BlockReference || $node instanceof Twig_Node_Expression_BlockReference) {
            $this->addLoopToCurrent();
        }

        // include without the only attribute
        elseif ($node instanceof Twig_Node_Include && !$node->getAttribute('only')) {
            $this->addLoopToAll();
        }

        // the loop variable is referenced via an attribute
        elseif ($node instanceof Twig_Node_Expression_GetAttr
            && (!$node->getNode('attribute') instanceof Twig_Node_Expression_Constant
                || 'parent' === $node->getNode('attribute')->getAttribute('value')
               )
            && (true === $this->loops[0]->getAttribute('with_loop')
                || ($node->getNode('node') instanceof Twig_Node_Expression_Name
                    && 'loop' === $node->getNode('node')->getAttribute('name')
                   )
               )
        ) {
            $this->addLoopToAll();
        }
    }