diff --git a/application/third_party/Twig/Autoloader.php b/application/third_party/Twig/Autoloader.php index fb502e625af..1082e6985a9 100644 --- a/application/third_party/Twig/Autoloader.php +++ b/application/third_party/Twig/Autoloader.php @@ -49,11 +49,6 @@ public static function autoload($class) if (is_file($file = dirname(__FILE__).'/../'.str_replace(array('_', "\0"), array('/', ''), $class).'.php')) { require $file; - } else { - $file = str_replace('\\', '/', $file); - if (is_file($file)) { - require $file; - } } } } diff --git a/application/third_party/Twig/Cache/CacheInterface.php b/application/third_party/Twig/Cache/CacheInterface.php deleted file mode 100644 index 1c8bb1ec9a9..00000000000 --- a/application/third_party/Twig/Cache/CacheInterface.php +++ /dev/null @@ -1,60 +0,0 @@ - - */ -interface CacheInterface -{ - /** - * Generates a cache key for the given template class name. - * - * @param string $name The template name - * @param string $className The template class name - * - * @return string - */ - public function generateKey($name, $className); - - /** - * Writes the compiled template to cache. - * - * @param string $key The cache key - * @param string $content The template representation as a PHP class - */ - public function write($key, $content); - - /** - * Loads a template from the cache. - * - * @param string $key The cache key - */ - public function load($key); - - /** - * Returns the modification timestamp of a key. - * - * @param string $key The cache key - * - * @return int - */ - public function getTimestamp($key); -} - -class_alias('Twig\Cache\CacheInterface', 'Twig_CacheInterface'); diff --git a/application/third_party/Twig/Cache/FilesystemCache.php b/application/third_party/Twig/Cache/FilesystemCache.php deleted file mode 100644 index b7c1e438e79..00000000000 --- a/application/third_party/Twig/Cache/FilesystemCache.php +++ /dev/null @@ -1,93 +0,0 @@ - - */ -class FilesystemCache implements CacheInterface -{ - const FORCE_BYTECODE_INVALIDATION = 1; - - private $directory; - private $options; - - /** - * @param string $directory The root cache directory - * @param int $options A set of options - */ - public function __construct($directory, $options = 0) - { - $this->directory = rtrim($directory, '\/').'/'; - $this->options = $options; - } - - public function generateKey($name, $className) - { - $hash = hash('sha256', $className); - - return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php'; - } - - public function load($key) - { - if (file_exists($key)) { - @include_once $key; - } - } - - public function write($key, $content) - { - $dir = \dirname($key); - if (!is_dir($dir)) { - if (false === @mkdir($dir, 0777, true)) { - clearstatcache(true, $dir); - if (!is_dir($dir)) { - throw new \RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir)); - } - } - } elseif (!is_writable($dir)) { - throw new \RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir)); - } - - $tmpFile = tempnam($dir, basename($key)); - if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) { - @chmod($key, 0666 & ~umask()); - - if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) { - // Compile cached file into bytecode cache - if (\function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN)) { - @opcache_invalidate($key, true); - } elseif (\function_exists('apc_compile_file')) { - apc_compile_file($key); - } - } - - return; - } - - throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $key)); - } - - public function getTimestamp($key) - { - if (!file_exists($key)) { - return 0; - } - - return (int) @filemtime($key); - } -} - -class_alias('Twig\Cache\FilesystemCache', 'Twig_Cache_Filesystem'); diff --git a/application/third_party/Twig/Cache/NullCache.php b/application/third_party/Twig/Cache/NullCache.php deleted file mode 100644 index c1b37c1243e..00000000000 --- a/application/third_party/Twig/Cache/NullCache.php +++ /dev/null @@ -1,42 +0,0 @@ - - */ -class NullCache implements CacheInterface -{ - public function generateKey($name, $className) - { - return ''; - } - - public function write($key, $content) - { - } - - public function load($key) - { - } - - public function getTimestamp($key) - { - return 0; - } -} - -class_alias('Twig\Cache\NullCache', 'Twig_Cache_Null'); diff --git a/application/third_party/Twig/Compiler.php b/application/third_party/Twig/Compiler.php index e47003ae19e..7ab8feff767 100644 --- a/application/third_party/Twig/Compiler.php +++ b/application/third_party/Twig/Compiler.php @@ -3,35 +3,30 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier - * (c) Armin Ronacher + * (c) 2009 Fabien Potencier + * (c) 2009 Armin Ronacher * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\Node\ModuleNode; - /** * Compiles a node to PHP code. * * @author Fabien Potencier */ -class Compiler implements \Twig_CompilerInterface +class Twig_Compiler implements Twig_CompilerInterface { protected $lastLine; protected $source; protected $indentation; protected $env; - protected $debugInfo = []; + protected $debugInfo = array(); protected $sourceOffset; protected $sourceLine; protected $filename; - private $varNameSalt = 0; - public function __construct(Environment $env) + public function __construct(Twig_Environment $env) { $this->env = $env; } @@ -49,7 +44,7 @@ public function getFilename() /** * Returns the environment instance related to this compiler. * - * @return Environment + * @return Twig_Environment */ public function getEnvironment() { @@ -69,22 +64,22 @@ public function getSource() /** * Compiles a node. * - * @param int $indentation The current indentation + * @param Twig_NodeInterface $node The node to compile + * @param int $indentation The current indentation * * @return $this */ - public function compile(\Twig_NodeInterface $node, $indentation = 0) + public function compile(Twig_NodeInterface $node, $indentation = 0) { $this->lastLine = null; $this->source = ''; - $this->debugInfo = []; + $this->debugInfo = array(); $this->sourceOffset = 0; // source code starts at 1 (as we then increment it when we encounter new lines) $this->sourceLine = 1; $this->indentation = $indentation; - $this->varNameSalt = 0; - if ($node instanceof ModuleNode) { + if ($node instanceof Twig_Node_Module) { // to be removed in 2.0 $this->filename = $node->getTemplateName(); } @@ -94,7 +89,7 @@ public function compile(\Twig_NodeInterface $node, $indentation = 0) return $this; } - public function subcompile(\Twig_NodeInterface $node, $raw = true) + public function subcompile(Twig_NodeInterface $node, $raw = true) { if (false === $raw) { $this->source .= str_repeat(' ', $this->indentation * 4); @@ -126,7 +121,7 @@ public function raw($string) */ public function write() { - $strings = \func_get_args(); + $strings = func_get_args(); foreach ($strings as $string) { $this->source .= str_repeat(' ', $this->indentation * 4).$string; } @@ -173,22 +168,22 @@ public function string($value) */ public function repr($value) { - if (\is_int($value) || \is_float($value)) { - if (false !== $locale = setlocale(LC_NUMERIC, '0')) { + if (is_int($value) || is_float($value)) { + if (false !== $locale = setlocale(LC_NUMERIC, 0)) { setlocale(LC_NUMERIC, 'C'); } - $this->raw(var_export($value, true)); + $this->raw($value); if (false !== $locale) { setlocale(LC_NUMERIC, $locale); } } elseif (null === $value) { $this->raw('null'); - } elseif (\is_bool($value)) { + } elseif (is_bool($value)) { $this->raw($value ? 'true' : 'false'); - } elseif (\is_array($value)) { - $this->raw('['); + } elseif (is_array($value)) { + $this->raw('array('); $first = true; foreach ($value as $key => $v) { if (!$first) { @@ -199,7 +194,7 @@ public function repr($value) $this->raw(' => '); $this->repr($v); } - $this->raw(']'); + $this->raw(')'); } else { $this->string($value); } @@ -212,7 +207,7 @@ public function repr($value) * * @return $this */ - public function addDebugInfo(\Twig_NodeInterface $node) + public function addDebugInfo(Twig_NodeInterface $node) { if ($node->getTemplateLine() != $this->lastLine) { $this->write(sprintf("// line %d\n", $node->getTemplateLine())); @@ -228,7 +223,7 @@ public function addDebugInfo(\Twig_NodeInterface $node) } else { $this->sourceLine += substr_count($this->source, "\n", $this->sourceOffset); } - $this->sourceOffset = \strlen($this->source); + $this->sourceOffset = strlen($this->source); $this->debugInfo[$this->sourceLine] = $node->getTemplateLine(); $this->lastLine = $node->getTemplateLine(); @@ -265,13 +260,13 @@ public function indent($step = 1) * * @return $this * - * @throws \LogicException When trying to outdent too much so the indentation would become negative + * @throws LogicException When trying to outdent too much so the indentation would become negative */ public function outdent($step = 1) { // can't outdent by more steps than the current indentation level if ($this->indentation < $step) { - throw new \LogicException('Unable to call outdent() as the indentation would become negative.'); + throw new LogicException('Unable to call outdent() as the indentation would become negative.'); } $this->indentation -= $step; @@ -281,8 +276,6 @@ public function outdent($step = 1) public function getVarName() { - return sprintf('__internal_%s', hash('sha256', __METHOD__.$this->varNameSalt++)); + return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false)); } } - -class_alias('Twig\Compiler', 'Twig_Compiler'); diff --git a/application/third_party/Twig/Environment.php b/application/third_party/Twig/Environment.php index 1f80f3a8736..6f7f1b60bf1 100644 --- a/application/third_party/Twig/Environment.php +++ b/application/third_party/Twig/Environment.php @@ -3,49 +3,24 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\Cache\CacheInterface; -use Twig\Cache\FilesystemCache; -use Twig\Cache\NullCache; -use Twig\Error\Error; -use Twig\Error\LoaderError; -use Twig\Error\RuntimeError; -use Twig\Error\SyntaxError; -use Twig\Extension\CoreExtension; -use Twig\Extension\EscaperExtension; -use Twig\Extension\ExtensionInterface; -use Twig\Extension\GlobalsInterface; -use Twig\Extension\InitRuntimeInterface; -use Twig\Extension\OptimizerExtension; -use Twig\Extension\StagingExtension; -use Twig\Loader\ArrayLoader; -use Twig\Loader\ChainLoader; -use Twig\Loader\LoaderInterface; -use Twig\Loader\SourceContextLoaderInterface; -use Twig\Node\ModuleNode; -use Twig\NodeVisitor\NodeVisitorInterface; -use Twig\RuntimeLoader\RuntimeLoaderInterface; -use Twig\TokenParser\TokenParserInterface; - /** * Stores the Twig configuration. * * @author Fabien Potencier */ -class Environment +class Twig_Environment { - const VERSION = '1.42.4'; - const VERSION_ID = 14204; + const VERSION = '1.29.0'; + const VERSION_ID = 12900; const MAJOR_VERSION = 1; - const MINOR_VERSION = 42; - const RELEASE_VERSION = 4; + const MINOR_VERSION = 29; + const RELEASE_VERSION = 0; const EXTRA_VERSION = ''; protected $charset; @@ -71,17 +46,17 @@ class Environment protected $unaryOperators; protected $binaryOperators; protected $templateClassPrefix = '__TwigTemplate_'; - protected $functionCallbacks = []; - protected $filterCallbacks = []; + protected $functionCallbacks = array(); + protected $filterCallbacks = array(); protected $staging; private $originalCache; private $bcWriteCacheFile = false; private $bcGetCacheFilename = false; private $lastModifiedExtension = 0; - private $extensionsByClass = []; - private $runtimeLoaders = []; - private $runtimes = []; + private $extensionsByClass = array(); + private $runtimeLoaders = array(); + private $runtimes = array(); private $optionsHash; /** @@ -95,10 +70,10 @@ class Environment * * charset: The charset used by the templates (default to UTF-8). * * * base_template_class: The base template class to use for generated - * templates (default to \Twig\Template). + * templates (default to Twig_Template). * * * cache: An absolute path where to store the compiled templates, - * a \Twig\Cache\CacheInterface implementation, + * a Twig_Cache_Interface implementation, * or false to disable compilation cache (default). * * * auto_reload: Whether to reload the template if the original source changed. @@ -118,25 +93,28 @@ class Environment * * optimizations: A flag that indicates which optimizations to apply * (default to -1 which means that all optimizations are enabled; * set it to 0 to disable). + * + * @param Twig_LoaderInterface $loader + * @param array $options An array of options */ - public function __construct(LoaderInterface $loader = null, $options = []) + public function __construct(Twig_LoaderInterface $loader = null, $options = array()) { if (null !== $loader) { $this->setLoader($loader); } else { - @trigger_error('Not passing a "Twig\Lodaer\LoaderInterface" as the first constructor argument of "Twig\Environment" is deprecated since version 1.21.', E_USER_DEPRECATED); + @trigger_error('Not passing a Twig_LoaderInterface as the first constructor argument of Twig_Environment is deprecated since version 1.21.', E_USER_DEPRECATED); } - $options = array_merge([ + $options = array_merge(array( 'debug' => false, 'charset' => 'UTF-8', - 'base_template_class' => '\Twig\Template', + 'base_template_class' => 'Twig_Template', 'strict_variables' => false, 'autoescape' => 'html', 'cache' => false, 'auto_reload' => null, 'optimizations' => -1, - ], $options); + ), $options); $this->debug = (bool) $options['debug']; $this->charset = strtoupper($options['charset']); @@ -145,23 +123,23 @@ public function __construct(LoaderInterface $loader = null, $options = []) $this->strictVariables = (bool) $options['strict_variables']; $this->setCache($options['cache']); - $this->addExtension(new CoreExtension()); - $this->addExtension(new EscaperExtension($options['autoescape'])); - $this->addExtension(new OptimizerExtension($options['optimizations'])); - $this->staging = new StagingExtension(); + $this->addExtension(new Twig_Extension_Core()); + $this->addExtension(new Twig_Extension_Escaper($options['autoescape'])); + $this->addExtension(new Twig_Extension_Optimizer($options['optimizations'])); + $this->staging = new Twig_Extension_Staging(); // For BC - if (\is_string($this->originalCache)) { - $r = new \ReflectionMethod($this, 'writeCacheFile'); - if (__CLASS__ !== $r->getDeclaringClass()->getName()) { - @trigger_error('The Twig\Environment::writeCacheFile method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED); + if (is_string($this->originalCache)) { + $r = new ReflectionMethod($this, 'writeCacheFile'); + if ($r->getDeclaringClass()->getName() !== __CLASS__) { + @trigger_error('The Twig_Environment::writeCacheFile method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED); $this->bcWriteCacheFile = true; } - $r = new \ReflectionMethod($this, 'getCacheFilename'); - if (__CLASS__ !== $r->getDeclaringClass()->getName()) { - @trigger_error('The Twig\Environment::getCacheFilename method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED); + $r = new ReflectionMethod($this, 'getCacheFilename'); + if ($r->getDeclaringClass()->getName() !== __CLASS__) { + @trigger_error('The Twig_Environment::getCacheFilename method is deprecated since version 1.22 and will be removed in Twig 2.0.', E_USER_DEPRECATED); $this->bcGetCacheFilename = true; } @@ -276,9 +254,9 @@ public function isStrictVariables() * * @param bool $original Whether to return the original cache option or the real cache instance * - * @return CacheInterface|string|false A Twig\Cache\CacheInterface implementation, - * an absolute path to the compiled templates, - * or false to disable cache + * @return Twig_CacheInterface|string|false A Twig_CacheInterface implementation, + * an absolute path to the compiled templates, + * or false to disable cache */ public function getCache($original = true) { @@ -288,26 +266,26 @@ public function getCache($original = true) /** * Sets the current cache implementation. * - * @param CacheInterface|string|false $cache A Twig\Cache\CacheInterface implementation, - * an absolute path to the compiled templates, - * or false to disable cache + * @param Twig_CacheInterface|string|false $cache A Twig_CacheInterface implementation, + * an absolute path to the compiled templates, + * or false to disable cache */ public function setCache($cache) { - if (\is_string($cache)) { + if (is_string($cache)) { $this->originalCache = $cache; - $this->cache = new FilesystemCache($cache); + $this->cache = new Twig_Cache_Filesystem($cache); } elseif (false === $cache) { $this->originalCache = $cache; - $this->cache = new NullCache(); + $this->cache = new Twig_Cache_Null(); } elseif (null === $cache) { @trigger_error('Using "null" as the cache strategy is deprecated since version 1.23 and will be removed in Twig 2.0.', E_USER_DEPRECATED); $this->originalCache = false; - $this->cache = new NullCache(); - } elseif ($cache instanceof CacheInterface) { + $this->cache = new Twig_Cache_Null(); + } elseif ($cache instanceof Twig_CacheInterface) { $this->originalCache = $this->cache = $cache; } else { - throw new \LogicException(sprintf('Cache can only be a string, false, or a \Twig\Cache\CacheInterface implementation.')); + throw new LogicException(sprintf('Cache can only be a string, false, or a Twig_CacheInterface implementation.')); } } @@ -350,7 +328,7 @@ public function getTemplateClass($name, $index = null) { $key = $this->getLoader()->getCacheKey($name).$this->optionsHash; - return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '___'.$index); + return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '_'.$index); } /** @@ -370,57 +348,53 @@ public function getTemplateClassPrefix() /** * Renders a template. * - * @param string|TemplateWrapper $name The template name - * @param array $context An array of parameters to pass to the template + * @param string $name The template name + * @param array $context An array of parameters to pass to the template * * @return string The rendered template * - * @throws LoaderError When the template cannot be found - * @throws SyntaxError When an error occurred during compilation - * @throws RuntimeError When an error occurred during rendering + * @throws Twig_Error_Loader When the template cannot be found + * @throws Twig_Error_Syntax When an error occurred during compilation + * @throws Twig_Error_Runtime When an error occurred during rendering */ - public function render($name, array $context = []) + public function render($name, array $context = array()) { - return $this->load($name)->render($context); + return $this->loadTemplate($name)->render($context); } /** * Displays a template. * - * @param string|TemplateWrapper $name The template name - * @param array $context An array of parameters to pass to the template + * @param string $name The template name + * @param array $context An array of parameters to pass to the template * - * @throws LoaderError When the template cannot be found - * @throws SyntaxError When an error occurred during compilation - * @throws RuntimeError When an error occurred during rendering + * @throws Twig_Error_Loader When the template cannot be found + * @throws Twig_Error_Syntax When an error occurred during compilation + * @throws Twig_Error_Runtime When an error occurred during rendering */ - public function display($name, array $context = []) + public function display($name, array $context = array()) { - $this->load($name)->display($context); + $this->loadTemplate($name)->display($context); } /** * Loads a template. * - * @param string|TemplateWrapper|\Twig\Template $name The template name - * - * @throws LoaderError When the template cannot be found - * @throws RuntimeError When a previously generated cache is corrupted - * @throws SyntaxError When an error occurred during compilation + * @param string|Twig_TemplateWrapper|Twig_Template $name The template name * - * @return TemplateWrapper + * @return Twig_TemplateWrapper */ public function load($name) { - if ($name instanceof TemplateWrapper) { + if ($name instanceof Twig_TemplateWrapper) { return $name; } - if ($name instanceof Template) { - return new TemplateWrapper($this, $name); + if ($name instanceof Twig_Template) { + return new Twig_TemplateWrapper($this, $name); } - return new TemplateWrapper($this, $this->loadTemplate($name)); + return new Twig_TemplateWrapper($this, $this->loadTemplate($name)); } /** @@ -432,28 +406,16 @@ public function load($name) * @param string $name The template name * @param int $index The index if it is an embedded template * - * @return \Twig_TemplateInterface A template instance representing the given template name + * @return Twig_TemplateInterface A template instance representing the given template name * - * @throws LoaderError When the template cannot be found - * @throws RuntimeError When a previously generated cache is corrupted - * @throws SyntaxError When an error occurred during compilation + * @throws Twig_Error_Loader When the template cannot be found + * @throws Twig_Error_Syntax When an error occurred during compilation * * @internal */ public function loadTemplate($name, $index = null) { - return $this->loadClass($this->getTemplateClass($name), $name, $index); - } - - /** - * @internal - */ - public function loadClass($cls, $name, $index = null) - { - $mainCls = $cls; - if (null !== $index) { - $cls .= '___'.$index; - } + $cls = $this->getTemplateClass($name, $index); if (isset($this->loadedTemplates[$cls])) { return $this->loadedTemplates[$cls]; @@ -463,18 +425,17 @@ public function loadClass($cls, $name, $index = null) if ($this->bcGetCacheFilename) { $key = $this->getCacheFilename($name); } else { - $key = $this->cache->generateKey($name, $mainCls); + $key = $this->cache->generateKey($name, $cls); } if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) { $this->cache->load($key); } - $source = null; if (!class_exists($cls, false)) { $loader = $this->getLoader(); - if (!$loader instanceof SourceContextLoaderInterface) { - $source = new Source($loader->getSource($name), $name); + if (!$loader instanceof Twig_SourceContextLoaderInterface) { + $source = new Twig_Source($loader->getSource($name), $name); } else { $source = $loader->getSourceContext($name); } @@ -488,7 +449,7 @@ public function loadClass($cls, $name, $index = null) $this->cache->load($key); } - if (!class_exists($mainCls, false)) { + if (!class_exists($cls, false)) { /* Last line of defense if either $this->bcWriteCacheFile was used, * $this->cache is implemented as a no-op or we have a race condition * where the cache was cleared between the above calls to write to and load from @@ -497,10 +458,6 @@ public function loadClass($cls, $name, $index = null) eval('?>'.$content); } } - - if (!class_exists($cls, false)) { - throw new RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source); - } } if (!$this->runtimeInitialized) { @@ -515,36 +472,30 @@ public function loadClass($cls, $name, $index = null) * * This method should not be used as a generic way to load templates. * - * @param string $template The template source - * @param string $name An optional name of the template to be used in error messages + * @param string $template The template name * - * @return TemplateWrapper A template instance representing the given template name + * @return Twig_Template A template instance representing the given template name * - * @throws LoaderError When the template cannot be found - * @throws SyntaxError When an error occurred during compilation + * @throws Twig_Error_Loader When the template cannot be found + * @throws Twig_Error_Syntax When an error occurred during compilation */ - public function createTemplate($template, $name = null) + public function createTemplate($template) { - $hash = hash('sha256', $template, false); - if (null !== $name) { - $name = sprintf('%s (string template %s)', $name, $hash); - } else { - $name = sprintf('__string_template__%s', $hash); - } + $name = sprintf('__string_template__%s', hash('sha256', uniqid(mt_rand(), true), false)); - $loader = new ChainLoader([ - new ArrayLoader([$name => $template]), + $loader = new Twig_Loader_Chain(array( + new Twig_Loader_Array(array($name => $template)), $current = $this->getLoader(), - ]); + )); $this->setLoader($loader); try { - $template = new TemplateWrapper($this, $this->loadTemplate($name)); - } catch (\Exception $e) { + $template = $this->loadTemplate($name); + } catch (Exception $e) { $this->setLoader($current); throw $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { $this->setLoader($current); throw $e; @@ -570,7 +521,7 @@ public function isTemplateFresh($name, $time) { if (0 === $this->lastModifiedExtension) { foreach ($this->extensions as $extension) { - $r = new \ReflectionObject($extension); + $r = new ReflectionObject($extension); if (file_exists($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModifiedExtension) { $this->lastModifiedExtension = $extensionTime; } @@ -583,40 +534,38 @@ public function isTemplateFresh($name, $time) /** * Tries to load a template consecutively from an array. * - * Similar to load() but it also accepts instances of \Twig\Template and - * \Twig\TemplateWrapper, and an array of templates where each is tried to be loaded. + * Similar to loadTemplate() but it also accepts Twig_TemplateInterface instances and an array + * of templates where each is tried to be loaded. * - * @param string|Template|\Twig\TemplateWrapper|array $names A template or an array of templates to try consecutively + * @param string|Twig_Template|array $names A template or an array of templates to try consecutively * - * @return TemplateWrapper|Template + * @return Twig_Template * - * @throws LoaderError When none of the templates can be found - * @throws SyntaxError When an error occurred during compilation + * @throws Twig_Error_Loader When none of the templates can be found + * @throws Twig_Error_Syntax When an error occurred during compilation */ public function resolveTemplate($names) { - if (!\is_array($names)) { - $names = [$names]; + if (!is_array($names)) { + $names = array($names); } foreach ($names as $name) { - if ($name instanceof Template) { - return $name; - } - if ($name instanceof TemplateWrapper) { + if ($name instanceof Twig_Template) { return $name; } try { return $this->loadTemplate($name); - } catch (LoaderError $e) { - if (1 === \count($names)) { - throw $e; - } + } catch (Twig_Error_Loader $e) { } } - throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names))); + if (1 === count($names)) { + throw $e; + } + + throw new Twig_Error_Loader(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names))); } /** @@ -628,7 +577,7 @@ public function clearTemplateCache() { @trigger_error(sprintf('The %s method is deprecated since version 1.18.3 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); - $this->loadedTemplates = []; + $this->loadedTemplates = array(); } /** @@ -640,8 +589,8 @@ public function clearCacheFiles() { @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); - if (\is_string($this->originalCache)) { - foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->originalCache), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + if (is_string($this->originalCache)) { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->originalCache), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { if ($file->isFile()) { @unlink($file->getPathname()); } @@ -652,7 +601,7 @@ public function clearCacheFiles() /** * Gets the Lexer instance. * - * @return \Twig_LexerInterface + * @return Twig_LexerInterface * * @deprecated since 1.25 (to be removed in 2.0) */ @@ -661,13 +610,13 @@ public function getLexer() @trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED); if (null === $this->lexer) { - $this->lexer = new Lexer($this); + $this->lexer = new Twig_Lexer($this); } return $this->lexer; } - public function setLexer(\Twig_LexerInterface $lexer) + public function setLexer(Twig_LexerInterface $lexer) { $this->lexer = $lexer; } @@ -675,22 +624,22 @@ public function setLexer(\Twig_LexerInterface $lexer) /** * Tokenizes a source code. * - * @param string|Source $source The template source code - * @param string $name The template name (deprecated) + * @param string|Twig_Source $source The template source code + * @param string $name The template name (deprecated) * - * @return TokenStream + * @return Twig_TokenStream * - * @throws SyntaxError When the code is syntactically wrong + * @throws Twig_Error_Syntax When the code is syntactically wrong */ public function tokenize($source, $name = null) { - if (!$source instanceof Source) { - @trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig\Source instance instead.', __METHOD__), E_USER_DEPRECATED); - $source = new Source($source, $name); + if (!$source instanceof Twig_Source) { + @trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED); + $source = new Twig_Source($source, $name); } if (null === $this->lexer) { - $this->lexer = new Lexer($this); + $this->lexer = new Twig_Lexer($this); } return $this->lexer->tokenize($source); @@ -699,7 +648,7 @@ public function tokenize($source, $name = null) /** * Gets the Parser instance. * - * @return \Twig_ParserInterface + * @return Twig_ParserInterface * * @deprecated since 1.25 (to be removed in 2.0) */ @@ -708,13 +657,13 @@ public function getParser() @trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED); if (null === $this->parser) { - $this->parser = new Parser($this); + $this->parser = new Twig_Parser($this); } return $this->parser; } - public function setParser(\Twig_ParserInterface $parser) + public function setParser(Twig_ParserInterface $parser) { $this->parser = $parser; } @@ -722,14 +671,14 @@ public function setParser(\Twig_ParserInterface $parser) /** * Converts a token stream to a node tree. * - * @return ModuleNode + * @return Twig_Node_Module * - * @throws SyntaxError When the token stream is syntactically or semantically wrong + * @throws Twig_Error_Syntax When the token stream is syntactically or semantically wrong */ - public function parse(TokenStream $stream) + public function parse(Twig_TokenStream $stream) { if (null === $this->parser) { - $this->parser = new Parser($this); + $this->parser = new Twig_Parser($this); } return $this->parser->parse($stream); @@ -738,7 +687,7 @@ public function parse(TokenStream $stream) /** * Gets the Compiler instance. * - * @return \Twig_CompilerInterface + * @return Twig_CompilerInterface * * @deprecated since 1.25 (to be removed in 2.0) */ @@ -747,13 +696,13 @@ public function getCompiler() @trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED); if (null === $this->compiler) { - $this->compiler = new Compiler($this); + $this->compiler = new Twig_Compiler($this); } return $this->compiler; } - public function setCompiler(\Twig_CompilerInterface $compiler) + public function setCompiler(Twig_CompilerInterface $compiler) { $this->compiler = $compiler; } @@ -763,10 +712,10 @@ public function setCompiler(\Twig_CompilerInterface $compiler) * * @return string The compiled PHP source code */ - public function compile(\Twig_NodeInterface $node) + public function compile(Twig_NodeInterface $node) { if (null === $this->compiler) { - $this->compiler = new Compiler($this); + $this->compiler = new Twig_Compiler($this); } return $this->compiler->compile($node)->getSource(); @@ -775,34 +724,34 @@ public function compile(\Twig_NodeInterface $node) /** * Compiles a template source code. * - * @param string|Source $source The template source code - * @param string $name The template name (deprecated) + * @param string|Twig_Source $source The template source code + * @param string $name The template name (deprecated) * * @return string The compiled PHP source code * - * @throws SyntaxError When there was an error during tokenizing, parsing or compiling + * @throws Twig_Error_Syntax When there was an error during tokenizing, parsing or compiling */ public function compileSource($source, $name = null) { - if (!$source instanceof Source) { - @trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig\Source instance instead.', __METHOD__), E_USER_DEPRECATED); - $source = new Source($source, $name); + if (!$source instanceof Twig_Source) { + @trigger_error(sprintf('Passing a string as the $source argument of %s() is deprecated since version 1.27. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED); + $source = new Twig_Source($source, $name); } try { return $this->compile($this->parse($this->tokenize($source))); - } catch (Error $e) { + } catch (Twig_Error $e) { $e->setSourceContext($source); throw $e; - } catch (\Exception $e) { - throw new SyntaxError(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e); + } catch (Exception $e) { + throw new Twig_Error_Syntax(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e); } } - public function setLoader(LoaderInterface $loader) + public function setLoader(Twig_LoaderInterface $loader) { - if (!$loader instanceof SourceContextLoaderInterface && 0 !== strpos(\get_class($loader), 'Mock_')) { - @trigger_error(sprintf('Twig loader "%s" should implement Twig\Loader\SourceContextLoaderInterface since version 1.27.', \get_class($loader)), E_USER_DEPRECATED); + if (!$loader instanceof Twig_SourceContextLoaderInterface && 0 !== strpos(get_class($loader), 'Mock_Twig_LoaderInterface')) { + @trigger_error(sprintf('Twig loader "%s" should implement Twig_SourceContextLoaderInterface since version 1.27.', get_class($loader)), E_USER_DEPRECATED); } $this->loader = $loader; @@ -811,12 +760,12 @@ public function setLoader(LoaderInterface $loader) /** * Gets the Loader instance. * - * @return LoaderInterface + * @return Twig_LoaderInterface */ public function getLoader() { if (null === $this->loader) { - throw new \LogicException('You must set a loader first.'); + throw new LogicException('You must set a loader first.'); } return $this->loader; @@ -852,12 +801,11 @@ public function initRuntime() $this->runtimeInitialized = true; foreach ($this->getExtensions() as $name => $extension) { - if (!$extension instanceof InitRuntimeInterface) { - $m = new \ReflectionMethod($extension, 'initRuntime'); + if (!$extension instanceof Twig_Extension_InitRuntimeInterface) { + $m = new ReflectionMethod($extension, 'initRuntime'); - $parentClass = $m->getDeclaringClass()->getName(); - if ('Twig_Extension' !== $parentClass && 'Twig\Extension\AbstractExtension' !== $parentClass) { - @trigger_error(sprintf('Defining the initRuntime() method in the "%s" extension is deprecated since version 1.23. Use the `needs_environment` option to get the \Twig_Environment instance in filters, functions, or tests; or explicitly implement Twig\Extension\InitRuntimeInterface if needed (not recommended).', $name), E_USER_DEPRECATED); + if ('Twig_Extension' !== $m->getDeclaringClass()->getName()) { + @trigger_error(sprintf('Defining the initRuntime() method in the "%s" extension is deprecated since version 1.23. Use the `needs_environment` option to get the Twig_Environment instance in filters, functions, or tests; or explicitly implement Twig_Extension_InitRuntimeInterface if needed (not recommended).', $name), E_USER_DEPRECATED); } } @@ -875,27 +823,21 @@ public function initRuntime() public function hasExtension($class) { $class = ltrim($class, '\\'); - if (!isset($this->extensionsByClass[$class]) && class_exists($class, false)) { - // For BC/FC with namespaced aliases - $class = new \ReflectionClass($class); - $class = $class->name; - } - if (isset($this->extensions[$class])) { - if ($class !== \get_class($this->extensions[$class])) { + if ($class !== get_class($this->extensions[$class])) { @trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED); } return true; } - return isset($this->extensionsByClass[$class]); + return isset($this->extensionsByClass[ltrim($class, '\\')]); } /** * Adds a runtime loader. */ - public function addRuntimeLoader(RuntimeLoaderInterface $loader) + public function addRuntimeLoader(Twig_RuntimeLoaderInterface $loader) { $this->runtimeLoaders[] = $loader; } @@ -905,19 +847,14 @@ public function addRuntimeLoader(RuntimeLoaderInterface $loader) * * @param string $class The extension class name * - * @return ExtensionInterface + * @return Twig_ExtensionInterface */ public function getExtension($class) { $class = ltrim($class, '\\'); - if (!isset($this->extensionsByClass[$class]) && class_exists($class, false)) { - // For BC/FC with namespaced aliases - $class = new \ReflectionClass($class); - $class = $class->name; - } if (isset($this->extensions[$class])) { - if ($class !== \get_class($this->extensions[$class])) { + if ($class !== get_class($this->extensions[$class])) { @trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED); } @@ -925,7 +862,7 @@ public function getExtension($class) } if (!isset($this->extensionsByClass[$class])) { - throw new RuntimeError(sprintf('The "%s" extension is not enabled.', $class)); + throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class)); } return $this->extensionsByClass[$class]; @@ -938,7 +875,7 @@ public function getExtension($class) * * @return object The runtime implementation * - * @throws RuntimeError When the template cannot be found + * @throws Twig_Error_Runtime When the template cannot be found */ public function getRuntime($class) { @@ -952,16 +889,16 @@ public function getRuntime($class) } } - throw new RuntimeError(sprintf('Unable to load the "%s" runtime.', $class)); + throw new Twig_Error_Runtime(sprintf('Unable to load the "%s" runtime.', $class)); } - public function addExtension(ExtensionInterface $extension) + public function addExtension(Twig_ExtensionInterface $extension) { if ($this->extensionInitialized) { - throw new \LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $extension->getName())); + throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $extension->getName())); } - $class = \get_class($extension); + $class = get_class($extension); if ($class !== $extension->getName()) { if (isset($this->extensions[$extension->getName()])) { unset($this->extensions[$extension->getName()], $this->extensionsByClass[$class]); @@ -989,18 +926,12 @@ public function removeExtension($name) @trigger_error(sprintf('The %s method is deprecated since version 1.12 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); if ($this->extensionInitialized) { - throw new \LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name)); + throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name)); } $class = ltrim($name, '\\'); - if (!isset($this->extensionsByClass[$class]) && class_exists($class, false)) { - // For BC/FC with namespaced aliases - $class = new \ReflectionClass($class); - $class = $class->name; - } - if (isset($this->extensions[$class])) { - if ($class !== \get_class($this->extensions[$class])) { + if ($class !== get_class($this->extensions[$class])) { @trigger_error(sprintf('Referencing the "%s" extension by its name (defined by getName()) is deprecated since 1.26 and will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name instead.', $class), E_USER_DEPRECATED); } @@ -1026,17 +957,17 @@ public function setExtensions(array $extensions) /** * Returns all registered extensions. * - * @return ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on) + * @return Twig_ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on) */ public function getExtensions() { return $this->extensions; } - public function addTokenParser(TokenParserInterface $parser) + public function addTokenParser(Twig_TokenParserInterface $parser) { if ($this->extensionInitialized) { - throw new \LogicException('Unable to add a token parser as extensions have already been initialized.'); + throw new LogicException('Unable to add a token parser as extensions have already been initialized.'); } $this->staging->addTokenParser($parser); @@ -1045,7 +976,7 @@ public function addTokenParser(TokenParserInterface $parser) /** * Gets the registered Token Parsers. * - * @return \Twig_TokenParserBrokerInterface + * @return Twig_TokenParserBrokerInterface * * @internal */ @@ -1061,17 +992,17 @@ public function getTokenParsers() /** * Gets registered tags. * - * Be warned that this method cannot return tags defined by \Twig_TokenParserBrokerInterface classes. + * Be warned that this method cannot return tags defined by Twig_TokenParserBrokerInterface classes. * - * @return TokenParserInterface[] + * @return Twig_TokenParserInterface[] * * @internal */ public function getTags() { - $tags = []; + $tags = array(); foreach ($this->getTokenParsers()->getParsers() as $parser) { - if ($parser instanceof TokenParserInterface) { + if ($parser instanceof Twig_TokenParserInterface) { $tags[$parser->getTag()] = $parser; } } @@ -1079,10 +1010,10 @@ public function getTags() return $tags; } - public function addNodeVisitor(NodeVisitorInterface $visitor) + public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { if ($this->extensionInitialized) { - throw new \LogicException('Unable to add a node visitor as extensions have already been initialized.'); + throw new LogicException('Unable to add a node visitor as extensions have already been initialized.'); } $this->staging->addNodeVisitor($visitor); @@ -1091,7 +1022,7 @@ public function addNodeVisitor(NodeVisitorInterface $visitor) /** * Gets the registered Node Visitors. * - * @return NodeVisitorInterface[] + * @return Twig_NodeVisitorInterface[] * * @internal */ @@ -1107,16 +1038,16 @@ public function getNodeVisitors() /** * Registers a Filter. * - * @param string|TwigFilter $name The filter name or a \Twig_SimpleFilter instance - * @param \Twig_FilterInterface|TwigFilter $filter + * @param string|Twig_SimpleFilter $name The filter name or a Twig_SimpleFilter instance + * @param Twig_FilterInterface|Twig_SimpleFilter $filter */ public function addFilter($name, $filter = null) { - if (!$name instanceof TwigFilter && !($filter instanceof TwigFilter || $filter instanceof \Twig_FilterInterface)) { - throw new \LogicException('A filter must be an instance of \Twig_FilterInterface or \Twig_SimpleFilter.'); + if (!$name instanceof Twig_SimpleFilter && !($filter instanceof Twig_SimpleFilter || $filter instanceof Twig_FilterInterface)) { + throw new LogicException('A filter must be an instance of Twig_FilterInterface or Twig_SimpleFilter.'); } - if ($name instanceof TwigFilter) { + if ($name instanceof Twig_SimpleFilter) { $filter = $name; $name = $filter->getName(); } else { @@ -1124,7 +1055,7 @@ public function addFilter($name, $filter = null) } if ($this->extensionInitialized) { - throw new \LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $name)); + throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $name)); } $this->staging->addFilter($name, $filter); @@ -1138,7 +1069,7 @@ public function addFilter($name, $filter = null) * * @param string $name The filter name * - * @return \Twig_Filter|false + * @return Twig_Filter|false A Twig_Filter instance or false if the filter does not exist * * @internal */ @@ -1166,7 +1097,7 @@ public function getFilter($name) } foreach ($this->filterCallbacks as $callback) { - if (false !== $filter = \call_user_func($callback, $name)) { + if (false !== $filter = call_user_func($callback, $name)) { return $filter; } } @@ -1184,7 +1115,7 @@ public function registerUndefinedFilterCallback($callable) * * Be warned that this method cannot return filters defined with registerUndefinedFilterCallback. * - * @return \Twig_FilterInterface[] + * @return Twig_FilterInterface[] * * @see registerUndefinedFilterCallback * @@ -1202,16 +1133,16 @@ public function getFilters() /** * Registers a Test. * - * @param string|TwigTest $name The test name or a \Twig_SimpleTest instance - * @param \Twig_TestInterface|TwigTest $test A \Twig_TestInterface instance or a \Twig_SimpleTest instance + * @param string|Twig_SimpleTest $name The test name or a Twig_SimpleTest instance + * @param Twig_TestInterface|Twig_SimpleTest $test A Twig_TestInterface instance or a Twig_SimpleTest instance */ public function addTest($name, $test = null) { - if (!$name instanceof TwigTest && !($test instanceof TwigTest || $test instanceof \Twig_TestInterface)) { - throw new \LogicException('A test must be an instance of \Twig_TestInterface or \Twig_SimpleTest.'); + if (!$name instanceof Twig_SimpleTest && !($test instanceof Twig_SimpleTest || $test instanceof Twig_TestInterface)) { + throw new LogicException('A test must be an instance of Twig_TestInterface or Twig_SimpleTest.'); } - if ($name instanceof TwigTest) { + if ($name instanceof Twig_SimpleTest) { $test = $name; $name = $test->getName(); } else { @@ -1219,7 +1150,7 @@ public function addTest($name, $test = null) } if ($this->extensionInitialized) { - throw new \LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $name)); + throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $name)); } $this->staging->addTest($name, $test); @@ -1228,7 +1159,7 @@ public function addTest($name, $test = null) /** * Gets the registered Tests. * - * @return \Twig_TestInterface[] + * @return Twig_TestInterface[] * * @internal */ @@ -1246,7 +1177,7 @@ public function getTests() * * @param string $name The test name * - * @return \Twig_Test|false + * @return Twig_Test|false A Twig_Test instance or false if the test does not exist * * @internal */ @@ -1260,35 +1191,22 @@ public function getTest($name) return $this->tests[$name]; } - foreach ($this->tests as $pattern => $test) { - $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); - - if ($count) { - if (preg_match('#^'.$pattern.'$#', $name, $matches)) { - array_shift($matches); - $test->setArguments($matches); - - return $test; - } - } - } - return false; } /** * Registers a Function. * - * @param string|TwigFunction $name The function name or a \Twig_SimpleFunction instance - * @param \Twig_FunctionInterface|TwigFunction $function + * @param string|Twig_SimpleFunction $name The function name or a Twig_SimpleFunction instance + * @param Twig_FunctionInterface|Twig_SimpleFunction $function */ public function addFunction($name, $function = null) { - if (!$name instanceof TwigFunction && !($function instanceof TwigFunction || $function instanceof \Twig_FunctionInterface)) { - throw new \LogicException('A function must be an instance of \Twig_FunctionInterface or \Twig_SimpleFunction.'); + if (!$name instanceof Twig_SimpleFunction && !($function instanceof Twig_SimpleFunction || $function instanceof Twig_FunctionInterface)) { + throw new LogicException('A function must be an instance of Twig_FunctionInterface or Twig_SimpleFunction.'); } - if ($name instanceof TwigFunction) { + if ($name instanceof Twig_SimpleFunction) { $function = $name; $name = $function->getName(); } else { @@ -1296,7 +1214,7 @@ public function addFunction($name, $function = null) } if ($this->extensionInitialized) { - throw new \LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name)); + throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name)); } $this->staging->addFunction($name, $function); @@ -1310,7 +1228,7 @@ public function addFunction($name, $function = null) * * @param string $name function name * - * @return \Twig_Function|false + * @return Twig_Function|false A Twig_Function instance or false if the function does not exist * * @internal */ @@ -1338,7 +1256,7 @@ public function getFunction($name) } foreach ($this->functionCallbacks as $callback) { - if (false !== $function = \call_user_func($callback, $name)) { + if (false !== $function = call_user_func($callback, $name)) { return $function; } } @@ -1356,7 +1274,7 @@ public function registerUndefinedFunctionCallback($callable) * * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback. * - * @return \Twig_FunctionInterface[] + * @return Twig_FunctionInterface[] * * @see registerUndefinedFunctionCallback * @@ -1387,10 +1305,10 @@ public function addGlobal($name, $value) $this->globals = $this->initGlobals(); } - if (!\array_key_exists($name, $this->globals)) { + if (!array_key_exists($name, $this->globals)) { // The deprecation notice must be turned into the following exception in Twig 2.0 @trigger_error(sprintf('Registering global variable "%s" at runtime or when the extensions have already been initialized is deprecated since version 1.21.', $name), E_USER_DEPRECATED); - //throw new \LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name)); + //throw new LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name)); } } @@ -1434,7 +1352,7 @@ public function mergeGlobals(array $context) // we don't use array_merge as the context being generally // bigger than globals, this code is faster. foreach ($this->getGlobals() as $key => $value) { - if (!\array_key_exists($key, $context)) { + if (!array_key_exists($key, $context)) { $context[$key] = $value; } } @@ -1481,7 +1399,7 @@ public function computeAlternatives($name, $items) { @trigger_error(sprintf('The %s method is deprecated since version 1.23 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); - return SyntaxError::computeAlternatives($name, $items); + return Twig_Error_Syntax::computeAlternatives($name, $items); } /** @@ -1489,20 +1407,19 @@ public function computeAlternatives($name, $items) */ protected function initGlobals() { - $globals = []; + $globals = array(); foreach ($this->extensions as $name => $extension) { - if (!$extension instanceof GlobalsInterface) { - $m = new \ReflectionMethod($extension, 'getGlobals'); + if (!$extension instanceof Twig_Extension_GlobalsInterface) { + $m = new ReflectionMethod($extension, 'getGlobals'); - $parentClass = $m->getDeclaringClass()->getName(); - if ('Twig_Extension' !== $parentClass && 'Twig\Extension\AbstractExtension' !== $parentClass) { - @trigger_error(sprintf('Defining the getGlobals() method in the "%s" extension without explicitly implementing Twig\Extension\GlobalsInterface is deprecated since version 1.23.', $name), E_USER_DEPRECATED); + if ('Twig_Extension' !== $m->getDeclaringClass()->getName()) { + @trigger_error(sprintf('Defining the getGlobals() method in the "%s" extension without explicitly implementing Twig_Extension_GlobalsInterface is deprecated since version 1.23.', $name), E_USER_DEPRECATED); } } $extGlob = $extension->getGlobals(); - if (!\is_array($extGlob)) { - throw new \UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', \get_class($extension))); + if (!is_array($extGlob)) { + throw new UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', get_class($extension))); } $globals[] = $extGlob; @@ -1510,7 +1427,7 @@ protected function initGlobals() $globals[] = $this->staging->getGlobals(); - return \call_user_func_array('array_merge', $globals); + return call_user_func_array('array_merge', $globals); } /** @@ -1522,33 +1439,32 @@ protected function initExtensions() return; } - $this->parsers = new \Twig_TokenParserBroker([], [], false); - $this->filters = []; - $this->functions = []; - $this->tests = []; - $this->visitors = []; - $this->unaryOperators = []; - $this->binaryOperators = []; + $this->extensionInitialized = true; + $this->parsers = new Twig_TokenParserBroker(array(), array(), false); + $this->filters = array(); + $this->functions = array(); + $this->tests = array(); + $this->visitors = array(); + $this->unaryOperators = array(); + $this->binaryOperators = array(); foreach ($this->extensions as $extension) { $this->initExtension($extension); } $this->initExtension($this->staging); - // Done at the end only, so that an exception during initialization does not mark the environment as initialized when catching the exception - $this->extensionInitialized = true; } /** * @internal */ - protected function initExtension(ExtensionInterface $extension) + protected function initExtension(Twig_ExtensionInterface $extension) { // filters foreach ($extension->getFilters() as $name => $filter) { - if ($filter instanceof TwigFilter) { + if ($filter instanceof Twig_SimpleFilter) { $name = $filter->getName(); } else { - @trigger_error(sprintf('Using an instance of "%s" for filter "%s" is deprecated since version 1.21. Use \Twig_SimpleFilter instead.', \get_class($filter), $name), E_USER_DEPRECATED); + @trigger_error(sprintf('Using an instance of "%s" for filter "%s" is deprecated since version 1.21. Use Twig_SimpleFilter instead.', get_class($filter), $name), E_USER_DEPRECATED); } $this->filters[$name] = $filter; @@ -1556,10 +1472,10 @@ protected function initExtension(ExtensionInterface $extension) // functions foreach ($extension->getFunctions() as $name => $function) { - if ($function instanceof TwigFunction) { + if ($function instanceof Twig_SimpleFunction) { $name = $function->getName(); } else { - @trigger_error(sprintf('Using an instance of "%s" for function "%s" is deprecated since version 1.21. Use \Twig_SimpleFunction instead.', \get_class($function), $name), E_USER_DEPRECATED); + @trigger_error(sprintf('Using an instance of "%s" for function "%s" is deprecated since version 1.21. Use Twig_SimpleFunction instead.', get_class($function), $name), E_USER_DEPRECATED); } $this->functions[$name] = $function; @@ -1567,10 +1483,10 @@ protected function initExtension(ExtensionInterface $extension) // tests foreach ($extension->getTests() as $name => $test) { - if ($test instanceof TwigTest) { + if ($test instanceof Twig_SimpleTest) { $name = $test->getName(); } else { - @trigger_error(sprintf('Using an instance of "%s" for test "%s" is deprecated since version 1.21. Use \Twig_SimpleTest instead.', \get_class($test), $name), E_USER_DEPRECATED); + @trigger_error(sprintf('Using an instance of "%s" for test "%s" is deprecated since version 1.21. Use Twig_SimpleTest instead.', get_class($test), $name), E_USER_DEPRECATED); } $this->tests[$name] = $test; @@ -1578,14 +1494,14 @@ protected function initExtension(ExtensionInterface $extension) // token parsers foreach ($extension->getTokenParsers() as $parser) { - if ($parser instanceof TokenParserInterface) { + if ($parser instanceof Twig_TokenParserInterface) { $this->parsers->addTokenParser($parser); - } elseif ($parser instanceof \Twig_TokenParserBrokerInterface) { - @trigger_error('Registering a \Twig_TokenParserBrokerInterface instance is deprecated since version 1.21.', E_USER_DEPRECATED); + } elseif ($parser instanceof Twig_TokenParserBrokerInterface) { + @trigger_error('Registering a Twig_TokenParserBrokerInterface instance is deprecated since version 1.21.', E_USER_DEPRECATED); $this->parsers->addTokenParserBroker($parser); } else { - throw new \LogicException('getTokenParsers() must return an array of \Twig_TokenParserInterface or \Twig_TokenParserBrokerInterface instances.'); + throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances.'); } } @@ -1596,12 +1512,12 @@ protected function initExtension(ExtensionInterface $extension) // operators if ($operators = $extension->getOperators()) { - if (!\is_array($operators)) { - throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array with operators, got "%s".', \get_class($extension), \is_object($operators) ? \get_class($operators) : \gettype($operators).(\is_resource($operators) ? '' : '#'.$operators))); + if (!is_array($operators)) { + throw new InvalidArgumentException(sprintf('"%s::getOperators()" must return an array with operators, got "%s".', get_class($extension), is_object($operators) ? get_class($operators) : gettype($operators).(is_resource($operators) ? '' : '#'.$operators))); } - if (2 !== \count($operators)) { - throw new \InvalidArgumentException(sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', \get_class($extension), \count($operators))); + if (2 !== count($operators)) { + throw new InvalidArgumentException(sprintf('"%s::getOperators()" must return an array of 2 elements, got %d.', get_class($extension), count($operators))); } $this->unaryOperators = array_merge($this->unaryOperators, $operators[0]); @@ -1621,18 +1537,16 @@ private function updateOptionsHash() { $hashParts = array_merge( array_keys($this->extensions), - [ - (int) \function_exists('twig_template_get_attributes'), + array( + (int) function_exists('twig_template_get_attributes'), PHP_MAJOR_VERSION, PHP_MINOR_VERSION, self::VERSION, (int) $this->debug, $this->baseTemplateClass, (int) $this->strictVariables, - ] + ) ); $this->optionsHash = implode(':', $hashParts); } } - -class_alias('Twig\Environment', 'Twig_Environment'); diff --git a/application/third_party/Twig/Error/Error.php b/application/third_party/Twig/Error/Error.php deleted file mode 100644 index 2aa70f1538a..00000000000 --- a/application/third_party/Twig/Error/Error.php +++ /dev/null @@ -1,325 +0,0 @@ - - */ -class Error extends \Exception -{ - protected $lineno; - // to be renamed to name in 2.0 - protected $filename; - protected $rawMessage; - - private $sourcePath; - private $sourceCode; - - /** - * Constructor. - * - * Set the line number to -1 to enable its automatic guessing. - * Set the name to null to enable its automatic guessing. - * - * @param string $message The error message - * @param int $lineno The template line where the error occurred - * @param Source|string|null $source The source context where the error occurred - * @param \Exception $previous The previous exception - */ - public function __construct($message, $lineno = -1, $source = null, \Exception $previous = null) - { - if (null === $source) { - $name = null; - } elseif (!$source instanceof Source) { - // for compat with the Twig C ext., passing the template name as string is accepted - $name = $source; - } else { - $name = $source->getName(); - $this->sourceCode = $source->getCode(); - $this->sourcePath = $source->getPath(); - } - parent::__construct('', 0, $previous); - - $this->lineno = $lineno; - $this->filename = $name; - $this->rawMessage = $message; - $this->updateRepr(); - } - - /** - * Gets the raw message. - * - * @return string The raw message - */ - public function getRawMessage() - { - return $this->rawMessage; - } - - /** - * Gets the logical name where the error occurred. - * - * @return string The name - * - * @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead. - */ - public function getTemplateFile() - { - @trigger_error(sprintf('The "%s" method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', __METHOD__), E_USER_DEPRECATED); - - return $this->filename; - } - - /** - * Sets the logical name where the error occurred. - * - * @param string $name The name - * - * @deprecated since 1.27 (to be removed in 2.0). Use setSourceContext() instead. - */ - public function setTemplateFile($name) - { - @trigger_error(sprintf('The "%s" method is deprecated since version 1.27 and will be removed in 2.0. Use setSourceContext() instead.', __METHOD__), E_USER_DEPRECATED); - - $this->filename = $name; - - $this->updateRepr(); - } - - /** - * Gets the logical name where the error occurred. - * - * @return string The name - * - * @deprecated since 1.29 (to be removed in 2.0). Use getSourceContext() instead. - */ - public function getTemplateName() - { - @trigger_error(sprintf('The "%s" method is deprecated since version 1.29 and will be removed in 2.0. Use getSourceContext() instead.', __METHOD__), E_USER_DEPRECATED); - - return $this->filename; - } - - /** - * Sets the logical name where the error occurred. - * - * @param string $name The name - * - * @deprecated since 1.29 (to be removed in 2.0). Use setSourceContext() instead. - */ - public function setTemplateName($name) - { - @trigger_error(sprintf('The "%s" method is deprecated since version 1.29 and will be removed in 2.0. Use setSourceContext() instead.', __METHOD__), E_USER_DEPRECATED); - - $this->filename = $name; - $this->sourceCode = $this->sourcePath = null; - - $this->updateRepr(); - } - - /** - * Gets the template line where the error occurred. - * - * @return int The template line - */ - public function getTemplateLine() - { - return $this->lineno; - } - - /** - * Sets the template line where the error occurred. - * - * @param int $lineno The template line - */ - public function setTemplateLine($lineno) - { - $this->lineno = $lineno; - - $this->updateRepr(); - } - - /** - * Gets the source context of the Twig template where the error occurred. - * - * @return Source|null - */ - public function getSourceContext() - { - return $this->filename ? new Source($this->sourceCode, $this->filename, $this->sourcePath) : null; - } - - /** - * Sets the source context of the Twig template where the error occurred. - */ - public function setSourceContext(Source $source = null) - { - if (null === $source) { - $this->sourceCode = $this->filename = $this->sourcePath = null; - } else { - $this->sourceCode = $source->getCode(); - $this->filename = $source->getName(); - $this->sourcePath = $source->getPath(); - } - - $this->updateRepr(); - } - - public function guess() - { - $this->guessTemplateInfo(); - $this->updateRepr(); - } - - public function appendMessage($rawMessage) - { - $this->rawMessage .= $rawMessage; - $this->updateRepr(); - } - - /** - * @internal - */ - protected function updateRepr() - { - $this->message = $this->rawMessage; - - if ($this->sourcePath && $this->lineno > 0) { - $this->file = $this->sourcePath; - $this->line = $this->lineno; - - return; - } - - $dot = false; - if ('.' === substr($this->message, -1)) { - $this->message = substr($this->message, 0, -1); - $dot = true; - } - - $questionMark = false; - if ('?' === substr($this->message, -1)) { - $this->message = substr($this->message, 0, -1); - $questionMark = true; - } - - if ($this->filename) { - if (\is_string($this->filename) || (\is_object($this->filename) && method_exists($this->filename, '__toString'))) { - $name = sprintf('"%s"', $this->filename); - } else { - $name = json_encode($this->filename); - } - $this->message .= sprintf(' in %s', $name); - } - - if ($this->lineno && $this->lineno >= 0) { - $this->message .= sprintf(' at line %d', $this->lineno); - } - - if ($dot) { - $this->message .= '.'; - } - - if ($questionMark) { - $this->message .= '?'; - } - } - - /** - * @internal - */ - protected function guessTemplateInfo() - { - $template = null; - $templateClass = null; - - $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT); - foreach ($backtrace as $trace) { - if (isset($trace['object']) && $trace['object'] instanceof Template && 'Twig_Template' !== \get_class($trace['object'])) { - $currentClass = \get_class($trace['object']); - $isEmbedContainer = 0 === strpos($templateClass, $currentClass); - if (null === $this->filename || ($this->filename == $trace['object']->getTemplateName() && !$isEmbedContainer)) { - $template = $trace['object']; - $templateClass = \get_class($trace['object']); - } - } - } - - // update template name - if (null !== $template && null === $this->filename) { - $this->filename = $template->getTemplateName(); - } - - // update template path if any - if (null !== $template && null === $this->sourcePath) { - $src = $template->getSourceContext(); - $this->sourceCode = $src->getCode(); - $this->sourcePath = $src->getPath(); - } - - if (null === $template || $this->lineno > -1) { - return; - } - - $r = new \ReflectionObject($template); - $file = $r->getFileName(); - - $exceptions = [$e = $this]; - while ($e instanceof self && $e = $e->getPrevious()) { - $exceptions[] = $e; - } - - while ($e = array_pop($exceptions)) { - $traces = $e->getTrace(); - array_unshift($traces, ['file' => $e->getFile(), 'line' => $e->getLine()]); - - while ($trace = array_shift($traces)) { - if (!isset($trace['file']) || !isset($trace['line']) || $file != $trace['file']) { - continue; - } - - foreach ($template->getDebugInfo() as $codeLine => $templateLine) { - if ($codeLine <= $trace['line']) { - // update template line - $this->lineno = $templateLine; - - return; - } - } - } - } - } -} - -class_alias('Twig\Error\Error', 'Twig_Error'); diff --git a/application/third_party/Twig/Error/LoaderError.php b/application/third_party/Twig/Error/LoaderError.php deleted file mode 100644 index dc5a9f1af73..00000000000 --- a/application/third_party/Twig/Error/LoaderError.php +++ /dev/null @@ -1,23 +0,0 @@ - - */ -class LoaderError extends Error -{ -} - -class_alias('Twig\Error\LoaderError', 'Twig_Error_Loader'); diff --git a/application/third_party/Twig/Error/RuntimeError.php b/application/third_party/Twig/Error/RuntimeError.php deleted file mode 100644 index 9b3f36e050e..00000000000 --- a/application/third_party/Twig/Error/RuntimeError.php +++ /dev/null @@ -1,24 +0,0 @@ - - */ -class RuntimeError extends Error -{ -} - -class_alias('Twig\Error\RuntimeError', 'Twig_Error_Runtime'); diff --git a/application/third_party/Twig/Error/SyntaxError.php b/application/third_party/Twig/Error/SyntaxError.php deleted file mode 100644 index 480e6606210..00000000000 --- a/application/third_party/Twig/Error/SyntaxError.php +++ /dev/null @@ -1,57 +0,0 @@ - - */ -class SyntaxError extends Error -{ - /** - * Tweaks the error message to include suggestions. - * - * @param string $name The original name of the item that does not exist - * @param array $items An array of possible items - */ - public function addSuggestions($name, array $items) - { - if (!$alternatives = self::computeAlternatives($name, $items)) { - return; - } - - $this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', $alternatives))); - } - - /** - * @internal - * - * To be merged with the addSuggestions() method in 2.0. - */ - public static function computeAlternatives($name, $items) - { - $alternatives = []; - foreach ($items as $item) { - $lev = levenshtein($name, $item); - if ($lev <= \strlen($name) / 3 || false !== strpos($item, $name)) { - $alternatives[$item] = $lev; - } - } - asort($alternatives); - - return array_keys($alternatives); - } -} - -class_alias('Twig\Error\SyntaxError', 'Twig_Error_Syntax'); diff --git a/application/third_party/Twig/ExpressionParser.php b/application/third_party/Twig/ExpressionParser.php index 9066ade1695..a683fb35c62 100644 --- a/application/third_party/Twig/ExpressionParser.php +++ b/application/third_party/Twig/ExpressionParser.php @@ -3,45 +3,26 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier - * (c) Armin Ronacher + * (c) 2009 Fabien Potencier + * (c) 2009 Armin Ronacher * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\Error\SyntaxError; -use Twig\Node\Expression\ArrayExpression; -use Twig\Node\Expression\ArrowFunctionExpression; -use Twig\Node\Expression\AssignNameExpression; -use Twig\Node\Expression\Binary\ConcatBinary; -use Twig\Node\Expression\BlockReferenceExpression; -use Twig\Node\Expression\ConditionalExpression; -use Twig\Node\Expression\ConstantExpression; -use Twig\Node\Expression\GetAttrExpression; -use Twig\Node\Expression\MethodCallExpression; -use Twig\Node\Expression\NameExpression; -use Twig\Node\Expression\ParentExpression; -use Twig\Node\Expression\Unary\NegUnary; -use Twig\Node\Expression\Unary\NotUnary; -use Twig\Node\Expression\Unary\PosUnary; -use Twig\Node\Node; - /** * Parses expressions. * * This parser implements a "Precedence climbing" algorithm. * - * @see https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm - * @see https://en.wikipedia.org/wiki/Operator-precedence_parser + * @see http://www.engr.mun.ca/~theo/Misc/exp_parsing.htm + * @see http://en.wikipedia.org/wiki/Operator-precedence_parser * * @author Fabien Potencier * * @internal */ -class ExpressionParser +class Twig_ExpressionParser { const OPERATOR_LEFT = 1; const OPERATOR_RIGHT = 2; @@ -52,11 +33,11 @@ class ExpressionParser private $env; - public function __construct(Parser $parser, $env = null) + public function __construct(Twig_Parser $parser, Twig_Environment $env = null) { $this->parser = $parser; - if ($env instanceof Environment) { + if ($env instanceof Twig_Environment) { $this->env = $env; $this->unaryOperators = $env->getUnaryOperators(); $this->binaryOperators = $env->getBinaryOperators(); @@ -69,12 +50,8 @@ public function __construct(Parser $parser, $env = null) } } - public function parseExpression($precedence = 0, $allowArrow = false) + public function parseExpression($precedence = 0) { - if ($allowArrow && $arrow = $this->parseArrow()) { - return $arrow; - } - $expr = $this->getPrimary(); $token = $this->parser->getCurrentToken(); while ($this->isBinary($token) && $this->binaryOperators[$token->getValue()]['precedence'] >= $precedence) { @@ -86,7 +63,7 @@ public function parseExpression($precedence = 0, $allowArrow = false) } elseif ('is' === $token->getValue()) { $expr = $this->parseTestExpression($expr); } elseif (isset($op['callable'])) { - $expr = \call_user_func($op['callable'], $this->parser, $expr); + $expr = call_user_func($op['callable'], $this->parser, $expr); } else { $expr1 = $this->parseExpression(self::OPERATOR_LEFT === $op['associativity'] ? $op['precedence'] + 1 : $op['precedence']); $class = $op['class']; @@ -103,64 +80,6 @@ public function parseExpression($precedence = 0, $allowArrow = false) return $expr; } - /** - * @return ArrowFunctionExpression|null - */ - private function parseArrow() - { - $stream = $this->parser->getStream(); - - // short array syntax (one argument, no parentheses)? - if ($stream->look(1)->test(Token::ARROW_TYPE)) { - $line = $stream->getCurrent()->getLine(); - $token = $stream->expect(Token::NAME_TYPE); - $names = [new AssignNameExpression($token->getValue(), $token->getLine())]; - $stream->expect(Token::ARROW_TYPE); - - return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line); - } - - // first, determine if we are parsing an arrow function by finding => (long form) - $i = 0; - if (!$stream->look($i)->test(Token::PUNCTUATION_TYPE, '(')) { - return null; - } - ++$i; - while (true) { - // variable name - ++$i; - if (!$stream->look($i)->test(Token::PUNCTUATION_TYPE, ',')) { - break; - } - ++$i; - } - if (!$stream->look($i)->test(Token::PUNCTUATION_TYPE, ')')) { - return null; - } - ++$i; - if (!$stream->look($i)->test(Token::ARROW_TYPE)) { - return null; - } - - // yes, let's parse it properly - $token = $stream->expect(Token::PUNCTUATION_TYPE, '('); - $line = $token->getLine(); - - $names = []; - while (true) { - $token = $stream->expect(Token::NAME_TYPE); - $names[] = new AssignNameExpression($token->getValue(), $token->getLine()); - - if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) { - break; - } - } - $stream->expect(Token::PUNCTUATION_TYPE, ')'); - $stream->expect(Token::ARROW_TYPE); - - return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line); - } - protected function getPrimary() { $token = $this->parser->getCurrentToken(); @@ -172,10 +91,10 @@ protected function getPrimary() $class = $operator['class']; return $this->parsePostfixExpression(new $class($expr, $token->getLine())); - } elseif ($token->test(Token::PUNCTUATION_TYPE, '(')) { + } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '(')) { $this->parser->getStream()->next(); $expr = $this->parseExpression(); - $this->parser->getStream()->expect(Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed'); + $this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed'); return $this->parsePostfixExpression($expr); } @@ -185,95 +104,92 @@ protected function getPrimary() protected function parseConditionalExpression($expr) { - while ($this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE, '?')) { - if (!$this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE, ':')) { + while ($this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, '?')) { + if (!$this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, ':')) { $expr2 = $this->parseExpression(); - if ($this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE, ':')) { + if ($this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, ':')) { $expr3 = $this->parseExpression(); } else { - $expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine()); + $expr3 = new Twig_Node_Expression_Constant('', $this->parser->getCurrentToken()->getLine()); } } else { $expr2 = $expr; $expr3 = $this->parseExpression(); } - $expr = new ConditionalExpression($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine()); + $expr = new Twig_Node_Expression_Conditional($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine()); } return $expr; } - protected function isUnary(Token $token) + protected function isUnary(Twig_Token $token) { - return $token->test(Token::OPERATOR_TYPE) && isset($this->unaryOperators[$token->getValue()]); + return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->unaryOperators[$token->getValue()]); } - protected function isBinary(Token $token) + protected function isBinary(Twig_Token $token) { - return $token->test(Token::OPERATOR_TYPE) && isset($this->binaryOperators[$token->getValue()]); + return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->binaryOperators[$token->getValue()]); } public function parsePrimaryExpression() { $token = $this->parser->getCurrentToken(); switch ($token->getType()) { - case Token::NAME_TYPE: + case Twig_Token::NAME_TYPE: $this->parser->getStream()->next(); switch ($token->getValue()) { case 'true': case 'TRUE': - $node = new ConstantExpression(true, $token->getLine()); + $node = new Twig_Node_Expression_Constant(true, $token->getLine()); break; case 'false': case 'FALSE': - $node = new ConstantExpression(false, $token->getLine()); + $node = new Twig_Node_Expression_Constant(false, $token->getLine()); break; case 'none': case 'NONE': case 'null': case 'NULL': - $node = new ConstantExpression(null, $token->getLine()); + $node = new Twig_Node_Expression_Constant(null, $token->getLine()); break; default: if ('(' === $this->parser->getCurrentToken()->getValue()) { $node = $this->getFunctionNode($token->getValue(), $token->getLine()); } else { - $node = new NameExpression($token->getValue(), $token->getLine()); + $node = new Twig_Node_Expression_Name($token->getValue(), $token->getLine()); } } break; - case Token::NUMBER_TYPE: + case Twig_Token::NUMBER_TYPE: $this->parser->getStream()->next(); - $node = new ConstantExpression($token->getValue(), $token->getLine()); + $node = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine()); break; - case Token::STRING_TYPE: - case Token::INTERPOLATION_START_TYPE: + case Twig_Token::STRING_TYPE: + case Twig_Token::INTERPOLATION_START_TYPE: $node = $this->parseStringExpression(); break; - case Token::OPERATOR_TYPE: - if (preg_match(Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) { + case Twig_Token::OPERATOR_TYPE: + if (preg_match(Twig_Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) { // in this context, string operators are variable names $this->parser->getStream()->next(); - $node = new NameExpression($token->getValue(), $token->getLine()); + $node = new Twig_Node_Expression_Name($token->getValue(), $token->getLine()); break; } elseif (isset($this->unaryOperators[$token->getValue()])) { $class = $this->unaryOperators[$token->getValue()]['class']; - $ref = new \ReflectionClass($class); - $negClass = 'Twig\Node\Expression\Unary\NegUnary'; - $posClass = 'Twig\Node\Expression\Unary\PosUnary'; - if (!(\in_array($ref->getName(), [$negClass, $posClass, 'Twig_Node_Expression_Unary_Neg', 'Twig_Node_Expression_Unary_Pos']) - || $ref->isSubclassOf($negClass) || $ref->isSubclassOf($posClass) - || $ref->isSubclassOf('Twig_Node_Expression_Unary_Neg') || $ref->isSubclassOf('Twig_Node_Expression_Unary_Pos')) - ) { - throw new SyntaxError(sprintf('Unexpected unary operator "%s".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); + $ref = new ReflectionClass($class); + $negClass = 'Twig_Node_Expression_Unary_Neg'; + $posClass = 'Twig_Node_Expression_Unary_Pos'; + if (!(in_array($ref->getName(), array($negClass, $posClass)) || $ref->isSubclassOf($negClass) || $ref->isSubclassOf($posClass))) { + throw new Twig_Error_Syntax(sprintf('Unexpected unary operator "%s".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); } $this->parser->getStream()->next(); @@ -283,16 +199,13 @@ public function parsePrimaryExpression() break; } - // no break default: - if ($token->test(Token::PUNCTUATION_TYPE, '[')) { + if ($token->test(Twig_Token::PUNCTUATION_TYPE, '[')) { $node = $this->parseArrayExpression(); - } elseif ($token->test(Token::PUNCTUATION_TYPE, '{')) { + } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '{')) { $node = $this->parseHashExpression(); - } elseif ($token->test(Token::OPERATOR_TYPE, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) { - throw new SyntaxError(sprintf('Unexpected operator of value "%s". Did you try to use "===" or "!==" for strict comparison? Use "is same as(value)" instead.', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); } else { - throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); + throw new Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s".', Twig_Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); } } @@ -303,16 +216,16 @@ public function parseStringExpression() { $stream = $this->parser->getStream(); - $nodes = []; + $nodes = array(); // a string cannot be followed by another string in a single expression $nextCanBeString = true; while (true) { - if ($nextCanBeString && $token = $stream->nextIf(Token::STRING_TYPE)) { - $nodes[] = new ConstantExpression($token->getValue(), $token->getLine()); + if ($nextCanBeString && $token = $stream->nextIf(Twig_Token::STRING_TYPE)) { + $nodes[] = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine()); $nextCanBeString = false; - } elseif ($stream->nextIf(Token::INTERPOLATION_START_TYPE)) { + } elseif ($stream->nextIf(Twig_Token::INTERPOLATION_START_TYPE)) { $nodes[] = $this->parseExpression(); - $stream->expect(Token::INTERPOLATION_END_TYPE); + $stream->expect(Twig_Token::INTERPOLATION_END_TYPE); $nextCanBeString = true; } else { break; @@ -321,7 +234,7 @@ public function parseStringExpression() $expr = array_shift($nodes); foreach ($nodes as $node) { - $expr = new ConcatBinary($expr, $node, $node->getTemplateLine()); + $expr = new Twig_Node_Expression_Binary_Concat($expr, $node, $node->getTemplateLine()); } return $expr; @@ -330,16 +243,16 @@ public function parseStringExpression() public function parseArrayExpression() { $stream = $this->parser->getStream(); - $stream->expect(Token::PUNCTUATION_TYPE, '[', 'An array element was expected'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected'); - $node = new ArrayExpression([], $stream->getCurrent()->getLine()); + $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine()); $first = true; - while (!$stream->test(Token::PUNCTUATION_TYPE, ']')) { + while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { if (!$first) { - $stream->expect(Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma'); // trailing ,? - if ($stream->test(Token::PUNCTUATION_TYPE, ']')) { + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { break; } } @@ -347,7 +260,7 @@ public function parseArrayExpression() $node->addElement($this->parseExpression()); } - $stream->expect(Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed'); return $node; } @@ -355,16 +268,16 @@ public function parseArrayExpression() public function parseHashExpression() { $stream = $this->parser->getStream(); - $stream->expect(Token::PUNCTUATION_TYPE, '{', 'A hash element was expected'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected'); - $node = new ArrayExpression([], $stream->getCurrent()->getLine()); + $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine()); $first = true; - while (!$stream->test(Token::PUNCTUATION_TYPE, '}')) { + while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) { if (!$first) { - $stream->expect(Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma'); // trailing ,? - if ($stream->test(Token::PUNCTUATION_TYPE, '}')) { + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) { break; } } @@ -376,22 +289,22 @@ public function parseHashExpression() // * a string -- 'a' // * a name, which is equivalent to a string -- a // * an expression, which must be enclosed in parentheses -- (1 + 2) - if (($token = $stream->nextIf(Token::STRING_TYPE)) || ($token = $stream->nextIf(Token::NAME_TYPE)) || $token = $stream->nextIf(Token::NUMBER_TYPE)) { - $key = new ConstantExpression($token->getValue(), $token->getLine()); - } elseif ($stream->test(Token::PUNCTUATION_TYPE, '(')) { + if (($token = $stream->nextIf(Twig_Token::STRING_TYPE)) || ($token = $stream->nextIf(Twig_Token::NAME_TYPE)) || $token = $stream->nextIf(Twig_Token::NUMBER_TYPE)) { + $key = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine()); + } elseif ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) { $key = $this->parseExpression(); } else { $current = $stream->getCurrent(); - throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', Token::typeToEnglish($current->getType()), $current->getValue()), $current->getLine(), $stream->getSourceContext()); + throw new Twig_Error_Syntax(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', Twig_Token::typeToEnglish($current->getType()), $current->getValue()), $current->getLine(), $stream->getSourceContext()); } - $stream->expect(Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)'); $value = $this->parseExpression(); $node->addElement($value, $key); } - $stream->expect(Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed'); return $node; } @@ -400,7 +313,7 @@ public function parsePostfixExpression($node) { while (true) { $token = $this->parser->getCurrentToken(); - if (Token::PUNCTUATION_TYPE == $token->getType()) { + if ($token->getType() == Twig_Token::PUNCTUATION_TYPE) { if ('.' == $token->getValue() || '[' == $token->getValue()) { $node = $this->parseSubscriptExpression($node); } elseif ('|' == $token->getValue()) { @@ -421,37 +334,37 @@ public function getFunctionNode($name, $line) switch ($name) { case 'parent': $this->parseArguments(); - if (!\count($this->parser->getBlockStack())) { - throw new SyntaxError('Calling "parent" outside a block is forbidden.', $line, $this->parser->getStream()->getSourceContext()); + if (!count($this->parser->getBlockStack())) { + throw new Twig_Error_Syntax('Calling "parent" outside a block is forbidden.', $line, $this->parser->getStream()->getSourceContext()); } if (!$this->parser->getParent() && !$this->parser->hasTraits()) { - throw new SyntaxError('Calling "parent" on a template that does not extend nor "use" another template is forbidden.', $line, $this->parser->getStream()->getSourceContext()); + throw new Twig_Error_Syntax('Calling "parent" on a template that does not extend nor "use" another template is forbidden.', $line, $this->parser->getStream()->getSourceContext()); } - return new ParentExpression($this->parser->peekBlockStack(), $line); + return new Twig_Node_Expression_Parent($this->parser->peekBlockStack(), $line); case 'block': $args = $this->parseArguments(); - if (\count($args) < 1) { - throw new SyntaxError('The "block" function takes one argument (the block name).', $line, $this->parser->getStream()->getSourceContext()); + if (count($args) < 1) { + throw new Twig_Error_Syntax('The "block" function takes one argument (the block name).', $line, $this->parser->getStream()->getSourceContext()); } - return new BlockReferenceExpression($args->getNode(0), \count($args) > 1 ? $args->getNode(1) : null, $line); + return new Twig_Node_Expression_BlockReference($args->getNode(0), count($args) > 1 ? $args->getNode(1) : null, $line); case 'attribute': $args = $this->parseArguments(); - if (\count($args) < 2) { - throw new SyntaxError('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext()); + if (count($args) < 2) { + throw new Twig_Error_Syntax('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext()); } - return new GetAttrExpression($args->getNode(0), $args->getNode(1), \count($args) > 2 ? $args->getNode(2) : null, Template::ANY_CALL, $line); + return new Twig_Node_Expression_GetAttr($args->getNode(0), $args->getNode(1), count($args) > 2 ? $args->getNode(2) : null, Twig_Template::ANY_CALL, $line); default: if (null !== $alias = $this->parser->getImportedSymbol('function', $name)) { - $arguments = new ArrayExpression([], $line); + $arguments = new Twig_Node_Expression_Array(array(), $line); foreach ($this->parseArguments() as $n) { $arguments->addElement($n); } - $node = new MethodCallExpression($alias['node'], $alias['name'], $arguments, $line); + $node = new Twig_Node_Expression_MethodCall($alias['node'], $alias['name'], $arguments, $line); $node->setAttribute('safe', true); return $node; @@ -469,81 +382,81 @@ public function parseSubscriptExpression($node) $stream = $this->parser->getStream(); $token = $stream->next(); $lineno = $token->getLine(); - $arguments = new ArrayExpression([], $lineno); - $type = Template::ANY_CALL; - if ('.' == $token->getValue()) { + $arguments = new Twig_Node_Expression_Array(array(), $lineno); + $type = Twig_Template::ANY_CALL; + if ($token->getValue() == '.') { $token = $stream->next(); if ( - Token::NAME_TYPE == $token->getType() + $token->getType() == Twig_Token::NAME_TYPE || - Token::NUMBER_TYPE == $token->getType() + $token->getType() == Twig_Token::NUMBER_TYPE || - (Token::OPERATOR_TYPE == $token->getType() && preg_match(Lexer::REGEX_NAME, $token->getValue())) + ($token->getType() == Twig_Token::OPERATOR_TYPE && preg_match(Twig_Lexer::REGEX_NAME, $token->getValue())) ) { - $arg = new ConstantExpression($token->getValue(), $lineno); + $arg = new Twig_Node_Expression_Constant($token->getValue(), $lineno); - if ($stream->test(Token::PUNCTUATION_TYPE, '(')) { - $type = Template::METHOD_CALL; + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) { + $type = Twig_Template::METHOD_CALL; foreach ($this->parseArguments() as $n) { $arguments->addElement($n); } } } else { - throw new SyntaxError('Expected name or number.', $lineno, $stream->getSourceContext()); + throw new Twig_Error_Syntax('Expected name or number.', $lineno, $stream->getSourceContext()); } - if ($node instanceof NameExpression && null !== $this->parser->getImportedSymbol('template', $node->getAttribute('name'))) { - if (!$arg instanceof ConstantExpression) { - throw new SyntaxError(sprintf('Dynamic macro names are not supported (called on "%s").', $node->getAttribute('name')), $token->getLine(), $stream->getSourceContext()); + if ($node instanceof Twig_Node_Expression_Name && null !== $this->parser->getImportedSymbol('template', $node->getAttribute('name'))) { + if (!$arg instanceof Twig_Node_Expression_Constant) { + throw new Twig_Error_Syntax(sprintf('Dynamic macro names are not supported (called on "%s").', $node->getAttribute('name')), $token->getLine(), $stream->getSourceContext()); } $name = $arg->getAttribute('value'); if ($this->parser->isReservedMacroName($name)) { - throw new SyntaxError(sprintf('"%s" cannot be called as macro as it is a reserved keyword.', $name), $token->getLine(), $stream->getSourceContext()); + throw new Twig_Error_Syntax(sprintf('"%s" cannot be called as macro as it is a reserved keyword.', $name), $token->getLine(), $stream->getSourceContext()); } - $node = new MethodCallExpression($node, 'get'.$name, $arguments, $lineno); + $node = new Twig_Node_Expression_MethodCall($node, 'get'.$name, $arguments, $lineno); $node->setAttribute('safe', true); return $node; } } else { - $type = Template::ARRAY_CALL; + $type = Twig_Template::ARRAY_CALL; // slice? $slice = false; - if ($stream->test(Token::PUNCTUATION_TYPE, ':')) { + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ':')) { $slice = true; - $arg = new ConstantExpression(0, $token->getLine()); + $arg = new Twig_Node_Expression_Constant(0, $token->getLine()); } else { $arg = $this->parseExpression(); } - if ($stream->nextIf(Token::PUNCTUATION_TYPE, ':')) { + if ($stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ':')) { $slice = true; } if ($slice) { - if ($stream->test(Token::PUNCTUATION_TYPE, ']')) { - $length = new ConstantExpression(null, $token->getLine()); + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { + $length = new Twig_Node_Expression_Constant(null, $token->getLine()); } else { $length = $this->parseExpression(); } $class = $this->getFilterNodeClass('slice', $token->getLine()); - $arguments = new Node([$arg, $length]); - $filter = new $class($node, new ConstantExpression('slice', $token->getLine()), $arguments, $token->getLine()); + $arguments = new Twig_Node(array($arg, $length)); + $filter = new $class($node, new Twig_Node_Expression_Constant('slice', $token->getLine()), $arguments, $token->getLine()); - $stream->expect(Token::PUNCTUATION_TYPE, ']'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']'); return $filter; } - $stream->expect(Token::PUNCTUATION_TYPE, ']'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']'); } - return new GetAttrExpression($node, $arg, $arguments, $type, $lineno); + return new Twig_Node_Expression_GetAttr($node, $arg, $arguments, $type, $lineno); } public function parseFilterExpression($node) @@ -556,20 +469,20 @@ public function parseFilterExpression($node) public function parseFilterExpressionRaw($node, $tag = null) { while (true) { - $token = $this->parser->getStream()->expect(Token::NAME_TYPE); + $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE); - $name = new ConstantExpression($token->getValue(), $token->getLine()); - if (!$this->parser->getStream()->test(Token::PUNCTUATION_TYPE, '(')) { - $arguments = new Node(); + $name = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine()); + if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '(')) { + $arguments = new Twig_Node(); } else { - $arguments = $this->parseArguments(true, false, true); + $arguments = $this->parseArguments(true); } $class = $this->getFilterNodeClass($name->getAttribute('value'), $token->getLine()); $node = new $class($node, $name, $arguments, $token->getLine(), $tag); - if (!$this->parser->getStream()->test(Token::PUNCTUATION_TYPE, '|')) { + if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '|')) { break; } @@ -585,32 +498,32 @@ public function parseFilterExpressionRaw($node, $tag = null) * @param bool $namedArguments Whether to allow named arguments or not * @param bool $definition Whether we are parsing arguments for a function definition * - * @return Node + * @return Twig_Node * - * @throws SyntaxError + * @throws Twig_Error_Syntax */ - public function parseArguments($namedArguments = false, $definition = false, $allowArrow = false) + public function parseArguments($namedArguments = false, $definition = false) { - $args = []; + $args = array(); $stream = $this->parser->getStream(); - $stream->expect(Token::PUNCTUATION_TYPE, '(', 'A list of arguments must begin with an opening parenthesis'); - while (!$stream->test(Token::PUNCTUATION_TYPE, ')')) { + $stream->expect(Twig_Token::PUNCTUATION_TYPE, '(', 'A list of arguments must begin with an opening parenthesis'); + while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ')')) { if (!empty($args)) { - $stream->expect(Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma'); } if ($definition) { - $token = $stream->expect(Token::NAME_TYPE, null, 'An argument must be a name'); - $value = new NameExpression($token->getValue(), $this->parser->getCurrentToken()->getLine()); + $token = $stream->expect(Twig_Token::NAME_TYPE, null, 'An argument must be a name'); + $value = new Twig_Node_Expression_Name($token->getValue(), $this->parser->getCurrentToken()->getLine()); } else { - $value = $this->parseExpression(0, $allowArrow); + $value = $this->parseExpression(); } $name = null; - if ($namedArguments && $token = $stream->nextIf(Token::OPERATOR_TYPE, '=')) { - if (!$value instanceof NameExpression) { - throw new SyntaxError(sprintf('A parameter name must be a string, "%s" given.', \get_class($value)), $token->getLine(), $stream->getSourceContext()); + if ($namedArguments && $token = $stream->nextIf(Twig_Token::OPERATOR_TYPE, '=')) { + if (!$value instanceof Twig_Node_Expression_Name) { + throw new Twig_Error_Syntax(sprintf('A parameter name must be a string, "%s" given.', get_class($value)), $token->getLine(), $stream->getSourceContext()); } $name = $value->getAttribute('name'); @@ -618,17 +531,17 @@ public function parseArguments($namedArguments = false, $definition = false, $al $value = $this->parsePrimaryExpression(); if (!$this->checkConstantExpression($value)) { - throw new SyntaxError(sprintf('A default value for an argument must be a constant (a boolean, a string, a number, or an array).'), $token->getLine(), $stream->getSourceContext()); + throw new Twig_Error_Syntax(sprintf('A default value for an argument must be a constant (a boolean, a string, a number, or an array).'), $token->getLine(), $stream->getSourceContext()); } } else { - $value = $this->parseExpression(0, $allowArrow); + $value = $this->parseExpression(); } } if ($definition) { if (null === $name) { $name = $value->getAttribute('name'); - $value = new ConstantExpression(null, $this->parser->getCurrentToken()->getLine()); + $value = new Twig_Node_Expression_Constant(null, $this->parser->getCurrentToken()->getLine()); } $args[$name] = $value; } else { @@ -639,64 +552,58 @@ public function parseArguments($namedArguments = false, $definition = false, $al } } } - $stream->expect(Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis'); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis'); - return new Node($args); + return new Twig_Node($args); } public function parseAssignmentExpression() { $stream = $this->parser->getStream(); - $targets = []; + $targets = array(); while (true) { - $token = $this->parser->getCurrentToken(); - if ($stream->test(Token::OPERATOR_TYPE) && preg_match(Lexer::REGEX_NAME, $token->getValue())) { - // in this context, string operators are variable names - $this->parser->getStream()->next(); - } else { - $stream->expect(Token::NAME_TYPE, null, 'Only variables can be assigned to'); - } + $token = $stream->expect(Twig_Token::NAME_TYPE, null, 'Only variables can be assigned to'); $value = $token->getValue(); - if (\in_array(strtolower($value), ['true', 'false', 'none', 'null'])) { - throw new SyntaxError(sprintf('You cannot assign a value to "%s".', $value), $token->getLine(), $stream->getSourceContext()); + if (in_array(strtolower($value), array('true', 'false', 'none', 'null'))) { + throw new Twig_Error_Syntax(sprintf('You cannot assign a value to "%s".', $value), $token->getLine(), $stream->getSourceContext()); } - $targets[] = new AssignNameExpression($value, $token->getLine()); + $targets[] = new Twig_Node_Expression_AssignName($value, $token->getLine()); - if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) { + if (!$stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) { break; } } - return new Node($targets); + return new Twig_Node($targets); } public function parseMultitargetExpression() { - $targets = []; + $targets = array(); while (true) { $targets[] = $this->parseExpression(); - if (!$this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE, ',')) { + if (!$this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) { break; } } - return new Node($targets); + return new Twig_Node($targets); } - private function parseNotTestExpression(\Twig_NodeInterface $node) + private function parseNotTestExpression(Twig_NodeInterface $node) { - return new NotUnary($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine()); + return new Twig_Node_Expression_Unary_Not($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine()); } - private function parseTestExpression(\Twig_NodeInterface $node) + private function parseTestExpression(Twig_NodeInterface $node) { $stream = $this->parser->getStream(); list($name, $test) = $this->getTest($node->getTemplateLine()); $class = $this->getTestNodeClass($test); $arguments = null; - if ($stream->test(Token::PUNCTUATION_TYPE, '(')) { - $arguments = $this->parseArguments(true); + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) { + $arguments = $this->parser->getExpressionParser()->parseArguments(true); } return new $class($node, $name, $arguments, $this->parser->getCurrentToken()->getLine()); @@ -705,24 +612,24 @@ private function parseTestExpression(\Twig_NodeInterface $node) private function getTest($line) { $stream = $this->parser->getStream(); - $name = $stream->expect(Token::NAME_TYPE)->getValue(); + $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); if ($test = $this->env->getTest($name)) { - return [$name, $test]; + return array($name, $test); } - if ($stream->test(Token::NAME_TYPE)) { + if ($stream->test(Twig_Token::NAME_TYPE)) { // try 2-words tests $name = $name.' '.$this->parser->getCurrentToken()->getValue(); if ($test = $this->env->getTest($name)) { $stream->next(); - return [$name, $test]; + return array($name, $test); } } - $e = new SyntaxError(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext()); + $e = new Twig_Error_Syntax(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext()); $e->addSuggestions($name, array_keys($this->env->getTests())); throw $e; @@ -730,10 +637,10 @@ private function getTest($line) private function getTestNodeClass($test) { - if ($test instanceof TwigTest && $test->isDeprecated()) { + if ($test instanceof Twig_SimpleTest && $test->isDeprecated()) { $stream = $this->parser->getStream(); $message = sprintf('Twig Test "%s" is deprecated', $test->getName()); - if (!\is_bool($test->getDeprecatedVersion())) { + if (!is_bool($test->getDeprecatedVersion())) { $message .= sprintf(' since version %s', $test->getDeprecatedVersion()); } if ($test->getAlternative()) { @@ -745,25 +652,25 @@ private function getTestNodeClass($test) @trigger_error($message, E_USER_DEPRECATED); } - if ($test instanceof TwigTest) { + if ($test instanceof Twig_SimpleTest) { return $test->getNodeClass(); } - return $test instanceof \Twig_Test_Node ? $test->getClass() : 'Twig\Node\Expression\TestExpression'; + return $test instanceof Twig_Test_Node ? $test->getClass() : 'Twig_Node_Expression_Test'; } protected function getFunctionNodeClass($name, $line) { if (false === $function = $this->env->getFunction($name)) { - $e = new SyntaxError(sprintf('Unknown "%s" function.', $name), $line, $this->parser->getStream()->getSourceContext()); + $e = new Twig_Error_Syntax(sprintf('Unknown "%s" function.', $name), $line, $this->parser->getStream()->getSourceContext()); $e->addSuggestions($name, array_keys($this->env->getFunctions())); throw $e; } - if ($function instanceof TwigFunction && $function->isDeprecated()) { + if ($function instanceof Twig_SimpleFunction && $function->isDeprecated()) { $message = sprintf('Twig Function "%s" is deprecated', $function->getName()); - if (!\is_bool($function->getDeprecatedVersion())) { + if (!is_bool($function->getDeprecatedVersion())) { $message .= sprintf(' since version %s', $function->getDeprecatedVersion()); } if ($function->getAlternative()) { @@ -775,25 +682,25 @@ protected function getFunctionNodeClass($name, $line) @trigger_error($message, E_USER_DEPRECATED); } - if ($function instanceof TwigFunction) { + if ($function instanceof Twig_SimpleFunction) { return $function->getNodeClass(); } - return $function instanceof \Twig_Function_Node ? $function->getClass() : 'Twig\Node\Expression\FunctionExpression'; + return $function instanceof Twig_Function_Node ? $function->getClass() : 'Twig_Node_Expression_Function'; } protected function getFilterNodeClass($name, $line) { if (false === $filter = $this->env->getFilter($name)) { - $e = new SyntaxError(sprintf('Unknown "%s" filter.', $name), $line, $this->parser->getStream()->getSourceContext()); + $e = new Twig_Error_Syntax(sprintf('Unknown "%s" filter.', $name), $line, $this->parser->getStream()->getSourceContext()); $e->addSuggestions($name, array_keys($this->env->getFilters())); throw $e; } - if ($filter instanceof TwigFilter && $filter->isDeprecated()) { + if ($filter instanceof Twig_SimpleFilter && $filter->isDeprecated()) { $message = sprintf('Twig Filter "%s" is deprecated', $filter->getName()); - if (!\is_bool($filter->getDeprecatedVersion())) { + if (!is_bool($filter->getDeprecatedVersion())) { $message .= sprintf(' since version %s', $filter->getDeprecatedVersion()); } if ($filter->getAlternative()) { @@ -805,18 +712,18 @@ protected function getFilterNodeClass($name, $line) @trigger_error($message, E_USER_DEPRECATED); } - if ($filter instanceof TwigFilter) { + if ($filter instanceof Twig_SimpleFilter) { return $filter->getNodeClass(); } - return $filter instanceof \Twig_Filter_Node ? $filter->getClass() : 'Twig\Node\Expression\FilterExpression'; + return $filter instanceof Twig_Filter_Node ? $filter->getClass() : 'Twig_Node_Expression_Filter'; } // checks that the node only contains "constant" elements - protected function checkConstantExpression(\Twig_NodeInterface $node) + protected function checkConstantExpression(Twig_NodeInterface $node) { - if (!($node instanceof ConstantExpression || $node instanceof ArrayExpression - || $node instanceof NegUnary || $node instanceof PosUnary + if (!($node instanceof Twig_Node_Expression_Constant || $node instanceof Twig_Node_Expression_Array + || $node instanceof Twig_Node_Expression_Unary_Neg || $node instanceof Twig_Node_Expression_Unary_Pos )) { return false; } @@ -830,5 +737,3 @@ protected function checkConstantExpression(\Twig_NodeInterface $node) return true; } } - -class_alias('Twig\ExpressionParser', 'Twig_ExpressionParser'); diff --git a/application/third_party/Twig/Extension/AbstractExtension.php b/application/third_party/Twig/Extension/AbstractExtension.php deleted file mode 100644 index fa3245b2984..00000000000 --- a/application/third_party/Twig/Extension/AbstractExtension.php +++ /dev/null @@ -1,72 +0,0 @@ -escapers[$strategy] = $callable; - } - - /** - * Gets all defined escapers. - * - * @return array An array of escapers - */ - public function getEscapers() - { - return $this->escapers; - } - - /** - * Sets the default format to be used by the date filter. - * - * @param string $format The default date format string - * @param string $dateIntervalFormat The default date interval format string - */ - public function setDateFormat($format = null, $dateIntervalFormat = null) - { - if (null !== $format) { - $this->dateFormats[0] = $format; - } - - if (null !== $dateIntervalFormat) { - $this->dateFormats[1] = $dateIntervalFormat; - } - } - - /** - * Gets the default format to be used by the date filter. - * - * @return array The default date format string and the default date interval format string - */ - public function getDateFormat() - { - return $this->dateFormats; - } - - /** - * Sets the default timezone to be used by the date filter. - * - * @param \DateTimeZone|string $timezone The default timezone string or a \DateTimeZone object - */ - public function setTimezone($timezone) - { - $this->timezone = $timezone instanceof \DateTimeZone ? $timezone : new \DateTimeZone($timezone); - } - - /** - * Gets the default timezone to be used by the date filter. - * - * @return \DateTimeZone The default timezone currently in use - */ - public function getTimezone() - { - if (null === $this->timezone) { - $this->timezone = new \DateTimeZone(date_default_timezone_get()); - } - - return $this->timezone; - } - - /** - * Sets the default format to be used by the number_format filter. - * - * @param int $decimal the number of decimal places to use - * @param string $decimalPoint the character(s) to use for the decimal point - * @param string $thousandSep the character(s) to use for the thousands separator - */ - public function setNumberFormat($decimal, $decimalPoint, $thousandSep) - { - $this->numberFormat = [$decimal, $decimalPoint, $thousandSep]; - } - - /** - * Get the default format used by the number_format filter. - * - * @return array The arguments for number_format() - */ - public function getNumberFormat() - { - return $this->numberFormat; - } - - public function getTokenParsers() - { - return [ - new ApplyTokenParser(), - new ForTokenParser(), - new IfTokenParser(), - new ExtendsTokenParser(), - new IncludeTokenParser(), - new BlockTokenParser(), - new UseTokenParser(), - new FilterTokenParser(), - new MacroTokenParser(), - new ImportTokenParser(), - new FromTokenParser(), - new SetTokenParser(), - new SpacelessTokenParser(), - new FlushTokenParser(), - new DoTokenParser(), - new EmbedTokenParser(), - new WithTokenParser(), - new DeprecatedTokenParser(), - ]; - } - - public function getFilters() - { - $filters = [ - // formatting filters - new TwigFilter('date', 'twig_date_format_filter', ['needs_environment' => true]), - new TwigFilter('date_modify', 'twig_date_modify_filter', ['needs_environment' => true]), - new TwigFilter('format', 'sprintf'), - new TwigFilter('replace', 'twig_replace_filter'), - new TwigFilter('number_format', 'twig_number_format_filter', ['needs_environment' => true]), - new TwigFilter('abs', 'abs'), - new TwigFilter('round', 'twig_round'), - - // encoding - new TwigFilter('url_encode', 'twig_urlencode_filter'), - new TwigFilter('json_encode', 'twig_jsonencode_filter'), - new TwigFilter('convert_encoding', 'twig_convert_encoding'), - - // string filters - new TwigFilter('title', 'twig_title_string_filter', ['needs_environment' => true]), - new TwigFilter('capitalize', 'twig_capitalize_string_filter', ['needs_environment' => true]), - new TwigFilter('upper', 'strtoupper'), - new TwigFilter('lower', 'strtolower'), - new TwigFilter('striptags', 'strip_tags'), - new TwigFilter('trim', 'twig_trim_filter'), - new TwigFilter('nl2br', 'nl2br', ['pre_escape' => 'html', 'is_safe' => ['html']]), - new TwigFilter('spaceless', 'twig_spaceless', ['is_safe' => ['html']]), - - // array helpers - new TwigFilter('join', 'twig_join_filter'), - new TwigFilter('split', 'twig_split_filter', ['needs_environment' => true]), - new TwigFilter('sort', 'twig_sort_filter'), - new TwigFilter('merge', 'twig_array_merge'), - new TwigFilter('batch', 'twig_array_batch'), - new TwigFilter('filter', 'twig_array_filter'), - new TwigFilter('map', 'twig_array_map'), - new TwigFilter('reduce', 'twig_array_reduce'), - - // string/array filters - new TwigFilter('reverse', 'twig_reverse_filter', ['needs_environment' => true]), - new TwigFilter('length', 'twig_length_filter', ['needs_environment' => true]), - new TwigFilter('slice', 'twig_slice', ['needs_environment' => true]), - new TwigFilter('first', 'twig_first', ['needs_environment' => true]), - new TwigFilter('last', 'twig_last', ['needs_environment' => true]), - - // iteration and runtime - new TwigFilter('default', '_twig_default_filter', ['node_class' => '\Twig\Node\Expression\Filter\DefaultFilter']), - new TwigFilter('keys', 'twig_get_array_keys_filter'), - - // escaping - new TwigFilter('escape', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']), - new TwigFilter('e', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']), - ]; - - if (\function_exists('mb_get_info')) { - $filters[] = new TwigFilter('upper', 'twig_upper_filter', ['needs_environment' => true]); - $filters[] = new TwigFilter('lower', 'twig_lower_filter', ['needs_environment' => true]); - } - - return $filters; - } - - public function getFunctions() - { - return [ - new TwigFunction('max', 'max'), - new TwigFunction('min', 'min'), - new TwigFunction('range', 'range'), - new TwigFunction('constant', 'twig_constant'), - new TwigFunction('cycle', 'twig_cycle'), - new TwigFunction('random', 'twig_random', ['needs_environment' => true]), - new TwigFunction('date', 'twig_date_converter', ['needs_environment' => true]), - new TwigFunction('include', 'twig_include', ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]), - new TwigFunction('source', 'twig_source', ['needs_environment' => true, 'is_safe' => ['all']]), - ]; - } - - public function getTests() - { - return [ - new TwigTest('even', null, ['node_class' => '\Twig\Node\Expression\Test\EvenTest']), - new TwigTest('odd', null, ['node_class' => '\Twig\Node\Expression\Test\OddTest']), - new TwigTest('defined', null, ['node_class' => '\Twig\Node\Expression\Test\DefinedTest']), - new TwigTest('sameas', null, ['node_class' => '\Twig\Node\Expression\Test\SameasTest', 'deprecated' => '1.21', 'alternative' => 'same as']), - new TwigTest('same as', null, ['node_class' => '\Twig\Node\Expression\Test\SameasTest']), - new TwigTest('none', null, ['node_class' => '\Twig\Node\Expression\Test\NullTest']), - new TwigTest('null', null, ['node_class' => '\Twig\Node\Expression\Test\NullTest']), - new TwigTest('divisibleby', null, ['node_class' => '\Twig\Node\Expression\Test\DivisiblebyTest', 'deprecated' => '1.21', 'alternative' => 'divisible by']), - new TwigTest('divisible by', null, ['node_class' => '\Twig\Node\Expression\Test\DivisiblebyTest']), - new TwigTest('constant', null, ['node_class' => '\Twig\Node\Expression\Test\ConstantTest']), - new TwigTest('empty', 'twig_test_empty'), - new TwigTest('iterable', 'twig_test_iterable'), - ]; - } - - public function getOperators() - { - return [ - [ - 'not' => ['precedence' => 50, 'class' => '\Twig\Node\Expression\Unary\NotUnary'], - '-' => ['precedence' => 500, 'class' => '\Twig\Node\Expression\Unary\NegUnary'], - '+' => ['precedence' => 500, 'class' => '\Twig\Node\Expression\Unary\PosUnary'], - ], - [ - 'or' => ['precedence' => 10, 'class' => '\Twig\Node\Expression\Binary\OrBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'and' => ['precedence' => 15, 'class' => '\Twig\Node\Expression\Binary\AndBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'b-or' => ['precedence' => 16, 'class' => '\Twig\Node\Expression\Binary\BitwiseOrBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'b-xor' => ['precedence' => 17, 'class' => '\Twig\Node\Expression\Binary\BitwiseXorBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'b-and' => ['precedence' => 18, 'class' => '\Twig\Node\Expression\Binary\BitwiseAndBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '==' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\EqualBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '!=' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\NotEqualBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '<' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\LessBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '>' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\GreaterBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '>=' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\GreaterEqualBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '<=' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\LessEqualBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'not in' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\NotInBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'in' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\InBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'matches' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\MatchesBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'starts with' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\StartsWithBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'ends with' => ['precedence' => 20, 'class' => '\Twig\Node\Expression\Binary\EndsWithBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '..' => ['precedence' => 25, 'class' => '\Twig\Node\Expression\Binary\RangeBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '+' => ['precedence' => 30, 'class' => '\Twig\Node\Expression\Binary\AddBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '-' => ['precedence' => 30, 'class' => '\Twig\Node\Expression\Binary\SubBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '~' => ['precedence' => 40, 'class' => '\Twig\Node\Expression\Binary\ConcatBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '*' => ['precedence' => 60, 'class' => '\Twig\Node\Expression\Binary\MulBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '/' => ['precedence' => 60, 'class' => '\Twig\Node\Expression\Binary\DivBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '//' => ['precedence' => 60, 'class' => '\Twig\Node\Expression\Binary\FloorDivBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - '%' => ['precedence' => 60, 'class' => '\Twig\Node\Expression\Binary\ModBinary', 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'is' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT], - 'is not' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT], - '**' => ['precedence' => 200, 'class' => '\Twig\Node\Expression\Binary\PowerBinary', 'associativity' => ExpressionParser::OPERATOR_RIGHT], - '??' => ['precedence' => 300, 'class' => '\Twig\Node\Expression\NullCoalesceExpression', 'associativity' => ExpressionParser::OPERATOR_RIGHT], - ], - ]; - } - - public function getName() - { - return 'core'; - } -} - -class_alias('Twig\Extension\CoreExtension', 'Twig_Extension_Core'); -} - -namespace { -use Twig\Environment; -use Twig\Error\LoaderError; -use Twig\Error\RuntimeError; -use Twig\Loader\SourceContextLoaderInterface; -use Twig\Markup; -use Twig\Node\Expression\ConstantExpression; -use Twig\Node\Node; - -/** - * Cycles over a value. - * - * @param \ArrayAccess|array $values - * @param int $position The cycle position - * - * @return string The next value in the cycle - */ -function twig_cycle($values, $position) -{ - if (!\is_array($values) && !$values instanceof \ArrayAccess) { - return $values; - } - - return $values[$position % \count($values)]; -} - -/** - * Returns a random value depending on the supplied parameter type: - * - a random item from a \Traversable or array - * - a random character from a string - * - a random integer between 0 and the integer parameter. - * - * @param \Traversable|array|int|float|string $values The values to pick a random item from - * @param int|null $max Maximum value used when $values is an int - * - * @throws RuntimeError when $values is an empty array (does not apply to an empty string which is returned as is) - * - * @return mixed A random value from the given sequence - */ -function twig_random(Environment $env, $values = null, $max = null) -{ - if (null === $values) { - return null === $max ? mt_rand() : mt_rand(0, $max); - } - - if (\is_int($values) || \is_float($values)) { - if (null === $max) { - if ($values < 0) { - $max = 0; - $min = $values; - } else { - $max = $values; - $min = 0; - } - } else { - $min = $values; - $max = $max; - } - - return mt_rand($min, $max); - } - - if (\is_string($values)) { - if ('' === $values) { - return ''; - } - if (null !== $charset = $env->getCharset()) { - if ('UTF-8' !== $charset) { - $values = twig_convert_encoding($values, 'UTF-8', $charset); - } - - // unicode version of str_split() - // split at all positions, but not after the start and not before the end - $values = preg_split('/(? $value) { - $values[$i] = twig_convert_encoding($value, $charset, 'UTF-8'); - } - } - } else { - return $values[mt_rand(0, \strlen($values) - 1)]; - } - } - - if (!twig_test_iterable($values)) { - return $values; - } - - $values = twig_to_array($values); - - if (0 === \count($values)) { - throw new RuntimeError('The random function cannot pick from an empty array.'); - } - - return $values[array_rand($values, 1)]; -} - -/** - * Converts a date to the given format. - * - * {{ post.published_at|date("m/d/Y") }} - * - * @param \DateTime|\DateTimeInterface|\DateInterval|string $date A date - * @param string|null $format The target format, null to use the default - * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged - * - * @return string The formatted date - */ -function twig_date_format_filter(Environment $env, $date, $format = null, $timezone = null) -{ - if (null === $format) { - $formats = $env->getExtension('\Twig\Extension\CoreExtension')->getDateFormat(); - $format = $date instanceof \DateInterval ? $formats[1] : $formats[0]; - } - - if ($date instanceof \DateInterval) { - return $date->format($format); - } - - return twig_date_converter($env, $date, $timezone)->format($format); -} - -/** - * Returns a new date object modified. - * - * {{ post.published_at|date_modify("-1day")|date("m/d/Y") }} - * - * @param \DateTime|string $date A date - * @param string $modifier A modifier string - * - * @return \DateTime - */ -function twig_date_modify_filter(Environment $env, $date, $modifier) -{ - $date = twig_date_converter($env, $date, false); - $resultDate = $date->modify($modifier); - - // This is a hack to ensure PHP 5.2 support and support for \DateTimeImmutable - // \DateTime::modify does not return the modified \DateTime object < 5.3.0 - // and \DateTimeImmutable does not modify $date. - return null === $resultDate ? $date : $resultDate; -} - -/** - * Converts an input to a \DateTime instance. - * - * {% if date(user.created_at) < date('+2days') %} - * {# do something #} - * {% endif %} - * - * @param \DateTime|\DateTimeInterface|string|null $date A date - * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged - * - * @return \DateTime - */ -function twig_date_converter(Environment $env, $date = null, $timezone = null) -{ - // determine the timezone - if (false !== $timezone) { - if (null === $timezone) { - $timezone = $env->getExtension('\Twig\Extension\CoreExtension')->getTimezone(); - } elseif (!$timezone instanceof \DateTimeZone) { - $timezone = new \DateTimeZone($timezone); - } - } - - // immutable dates - if ($date instanceof \DateTimeImmutable) { - return false !== $timezone ? $date->setTimezone($timezone) : $date; - } - - if ($date instanceof \DateTime || $date instanceof \DateTimeInterface) { - $date = clone $date; - if (false !== $timezone) { - $date->setTimezone($timezone); - } - - return $date; - } - - if (null === $date || 'now' === $date) { - return new \DateTime($date, false !== $timezone ? $timezone : $env->getExtension('\Twig\Extension\CoreExtension')->getTimezone()); - } - - $asString = (string) $date; - if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) { - $date = new \DateTime('@'.$date); - } else { - $date = new \DateTime($date, $env->getExtension('\Twig\Extension\CoreExtension')->getTimezone()); - } - - if (false !== $timezone) { - $date->setTimezone($timezone); - } - - return $date; -} - -/** - * Replaces strings within a string. - * - * @param string $str String to replace in - * @param array|\Traversable $from Replace values - * @param string|null $to Replace to, deprecated (@see https://secure.php.net/manual/en/function.strtr.php) - * - * @return string - */ -function twig_replace_filter($str, $from, $to = null) -{ - if (\is_string($from) && \is_string($to)) { - @trigger_error('Using "replace" with character by character replacement is deprecated since version 1.22 and will be removed in Twig 2.0', E_USER_DEPRECATED); - - return strtr($str, $from, $to); - } - - if (!twig_test_iterable($from)) { - throw new RuntimeError(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".', \is_object($from) ? \get_class($from) : \gettype($from))); - } - - return strtr($str, twig_to_array($from)); -} - -/** - * Rounds a number. - * - * @param int|float $value The value to round - * @param int|float $precision The rounding precision - * @param string $method The method to use for rounding - * - * @return int|float The rounded number - */ -function twig_round($value, $precision = 0, $method = 'common') -{ - if ('common' == $method) { - return round($value, $precision); - } - - if ('ceil' != $method && 'floor' != $method) { - throw new RuntimeError('The round filter only supports the "common", "ceil", and "floor" methods.'); - } - - return $method($value * pow(10, $precision)) / pow(10, $precision); -} - -/** - * Number format filter. - * - * All of the formatting options can be left null, in that case the defaults will - * be used. Supplying any of the parameters will override the defaults set in the - * environment object. - * - * @param mixed $number A float/int/string of the number to format - * @param int $decimal the number of decimal points to display - * @param string $decimalPoint the character(s) to use for the decimal point - * @param string $thousandSep the character(s) to use for the thousands separator - * - * @return string The formatted number - */ -function twig_number_format_filter(Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null) -{ - $defaults = $env->getExtension('\Twig\Extension\CoreExtension')->getNumberFormat(); - if (null === $decimal) { - $decimal = $defaults[0]; - } - - if (null === $decimalPoint) { - $decimalPoint = $defaults[1]; - } - - if (null === $thousandSep) { - $thousandSep = $defaults[2]; - } - - return number_format((float) $number, $decimal, $decimalPoint, $thousandSep); -} - -/** - * URL encodes (RFC 3986) a string as a path segment or an array as a query string. - * - * @param string|array $url A URL or an array of query parameters - * - * @return string The URL encoded value - */ -function twig_urlencode_filter($url) -{ - if (\is_array($url)) { - if (\defined('PHP_QUERY_RFC3986')) { - return http_build_query($url, '', '&', PHP_QUERY_RFC3986); - } - - return http_build_query($url, '', '&'); - } - - return rawurlencode($url); -} - -/** - * JSON encodes a variable. - * - * @param mixed $value the value to encode - * @param int $options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT - * - * @return mixed The JSON encoded value - */ -function twig_jsonencode_filter($value, $options = 0) -{ - if ($value instanceof Markup) { - $value = (string) $value; - } elseif (\is_array($value)) { - array_walk_recursive($value, '_twig_markup2string'); - } - - return json_encode($value, $options); -} - -function _twig_markup2string(&$value) -{ - if ($value instanceof Markup) { - $value = (string) $value; - } -} - -/** - * Merges an array with another one. - * - * {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %} - * - * {% set items = items|merge({ 'peugeot': 'car' }) %} - * - * {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #} - * - * @param array|\Traversable $arr1 An array - * @param array|\Traversable $arr2 An array - * - * @return array The merged array - */ -function twig_array_merge($arr1, $arr2) -{ - if (!twig_test_iterable($arr1)) { - throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($arr1))); - } - - if (!twig_test_iterable($arr2)) { - throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', \gettype($arr2))); - } - - return array_merge(twig_to_array($arr1), twig_to_array($arr2)); -} - -/** - * Slices a variable. - * - * @param mixed $item A variable - * @param int $start Start of the slice - * @param int $length Size of the slice - * @param bool $preserveKeys Whether to preserve key or not (when the input is an array) - * - * @return mixed The sliced variable - */ -function twig_slice(Environment $env, $item, $start, $length = null, $preserveKeys = false) -{ - if ($item instanceof \Traversable) { - while ($item instanceof \IteratorAggregate) { - $item = $item->getIterator(); - } - - if ($start >= 0 && $length >= 0 && $item instanceof \Iterator) { - try { - return iterator_to_array(new \LimitIterator($item, $start, null === $length ? -1 : $length), $preserveKeys); - } catch (\OutOfBoundsException $e) { - return []; - } - } - - $item = iterator_to_array($item, $preserveKeys); - } - - if (\is_array($item)) { - return \array_slice($item, $start, $length, $preserveKeys); - } - - $item = (string) $item; - - if (\function_exists('mb_get_info') && null !== $charset = $env->getCharset()) { - return (string) mb_substr($item, $start, null === $length ? mb_strlen($item, $charset) - $start : $length, $charset); - } - - return (string) (null === $length ? substr($item, $start) : substr($item, $start, $length)); -} - -/** - * Returns the first element of the item. - * - * @param mixed $item A variable - * - * @return mixed The first element of the item - */ -function twig_first(Environment $env, $item) -{ - $elements = twig_slice($env, $item, 0, 1, false); - - return \is_string($elements) ? $elements : current($elements); -} - -/** - * Returns the last element of the item. - * - * @param mixed $item A variable - * - * @return mixed The last element of the item - */ -function twig_last(Environment $env, $item) -{ - $elements = twig_slice($env, $item, -1, 1, false); - - return \is_string($elements) ? $elements : current($elements); -} - -/** - * Joins the values to a string. - * - * The separators between elements are empty strings per default, you can define them with the optional parameters. - * - * {{ [1, 2, 3]|join(', ', ' and ') }} - * {# returns 1, 2 and 3 #} - * - * {{ [1, 2, 3]|join('|') }} - * {# returns 1|2|3 #} - * - * {{ [1, 2, 3]|join }} - * {# returns 123 #} - * - * @param array $value An array - * @param string $glue The separator - * @param string|null $and The separator for the last pair - * - * @return string The concatenated string - */ -function twig_join_filter($value, $glue = '', $and = null) -{ - if (!twig_test_iterable($value)) { - $value = (array) $value; - } - - $value = twig_to_array($value, false); - - if (0 === \count($value)) { - return ''; - } - - if (null === $and || $and === $glue) { - return implode($glue, $value); - } - - if (1 === \count($value)) { - return $value[0]; - } - - return implode($glue, \array_slice($value, 0, -1)).$and.$value[\count($value) - 1]; -} - -/** - * Splits the string into an array. - * - * {{ "one,two,three"|split(',') }} - * {# returns [one, two, three] #} - * - * {{ "one,two,three,four,five"|split(',', 3) }} - * {# returns [one, two, "three,four,five"] #} - * - * {{ "123"|split('') }} - * {# returns [1, 2, 3] #} - * - * {{ "aabbcc"|split('', 2) }} - * {# returns [aa, bb, cc] #} - * - * @param string $value A string - * @param string $delimiter The delimiter - * @param int $limit The limit - * - * @return array The split string as an array - */ -function twig_split_filter(Environment $env, $value, $delimiter, $limit = null) -{ - if (\strlen($delimiter) > 0) { - return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit); - } - - if (!\function_exists('mb_get_info') || null === $charset = $env->getCharset()) { - return str_split($value, null === $limit ? 1 : $limit); - } - - if ($limit <= 1) { - return preg_split('/(?getIterator(); - } - - if ($array instanceof \Iterator) { - $keys = []; - $array->rewind(); - while ($array->valid()) { - $keys[] = $array->key(); - $array->next(); - } - - return $keys; - } - - $keys = []; - foreach ($array as $key => $item) { - $keys[] = $key; - } - - return $keys; - } - - if (!\is_array($array)) { - return []; - } - - return array_keys($array); -} - -/** - * Reverses a variable. - * - * @param array|\Traversable|string $item An array, a \Traversable instance, or a string - * @param bool $preserveKeys Whether to preserve key or not - * - * @return mixed The reversed input - */ -function twig_reverse_filter(Environment $env, $item, $preserveKeys = false) -{ - if ($item instanceof \Traversable) { - return array_reverse(iterator_to_array($item), $preserveKeys); - } - - if (\is_array($item)) { - return array_reverse($item, $preserveKeys); - } - - if (null !== $charset = $env->getCharset()) { - $string = (string) $item; - - if ('UTF-8' !== $charset) { - $item = twig_convert_encoding($string, 'UTF-8', $charset); - } - - preg_match_all('/./us', $item, $matches); - - $string = implode('', array_reverse($matches[0])); - - if ('UTF-8' !== $charset) { - $string = twig_convert_encoding($string, $charset, 'UTF-8'); - } - - return $string; - } - - return strrev((string) $item); -} - -/** - * Sorts an array. - * - * @param array|\Traversable $array - * - * @return array - */ -function twig_sort_filter($array) -{ - if ($array instanceof \Traversable) { - $array = iterator_to_array($array); - } elseif (!\is_array($array)) { - throw new RuntimeError(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', \gettype($array))); - } - - asort($array); - - return $array; -} - -/** - * @internal - */ -function twig_in_filter($value, $compare) -{ - if ($value instanceof Markup) { - $value = (string) $value; - } - if ($compare instanceof Markup) { - $compare = (string) $compare; - } - - if (\is_array($compare)) { - return \in_array($value, $compare, \is_object($value) || \is_resource($value)); - } elseif (\is_string($compare) && (\is_string($value) || \is_int($value) || \is_float($value))) { - return '' === $value || false !== strpos($compare, (string) $value); - } elseif ($compare instanceof \Traversable) { - if (\is_object($value) || \is_resource($value)) { - foreach ($compare as $item) { - if ($item === $value) { - return true; - } - } - } else { - foreach ($compare as $item) { - if ($item == $value) { - return true; - } - } - } - - return false; - } - - return false; -} - -/** - * Returns a trimmed string. - * - * @return string - * - * @throws RuntimeError When an invalid trimming side is used (not a string or not 'left', 'right', or 'both') - */ -function twig_trim_filter($string, $characterMask = null, $side = 'both') -{ - if (null === $characterMask) { - $characterMask = " \t\n\r\0\x0B"; - } - - switch ($side) { - case 'both': - return trim($string, $characterMask); - case 'left': - return ltrim($string, $characterMask); - case 'right': - return rtrim($string, $characterMask); - default: - throw new RuntimeError('Trimming side must be "left", "right" or "both".'); - } -} - -/** - * Removes whitespaces between HTML tags. - * - * @return string - */ -function twig_spaceless($content) -{ - return trim(preg_replace('/>\s+<', $content)); -} - -/** - * Escapes a string. - * - * @param mixed $string The value to be escaped - * @param string $strategy The escaping strategy - * @param string $charset The charset - * @param bool $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false) - * - * @return string - */ -function twig_escape_filter(Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false) -{ - if ($autoescape && $string instanceof Markup) { - return $string; - } - - if (!\is_string($string)) { - if (\is_object($string) && method_exists($string, '__toString')) { - $string = (string) $string; - } elseif (\in_array($strategy, ['html', 'js', 'css', 'html_attr', 'url'])) { - return $string; - } - } - - if ('' === $string) { - return ''; - } - - if (null === $charset) { - $charset = $env->getCharset(); - } - - switch ($strategy) { - case 'html': - // see https://secure.php.net/htmlspecialchars - - // Using a static variable to avoid initializing the array - // each time the function is called. Moving the declaration on the - // top of the function slow downs other escaping strategies. - static $htmlspecialcharsCharsets = [ - 'ISO-8859-1' => true, 'ISO8859-1' => true, - 'ISO-8859-15' => true, 'ISO8859-15' => true, - 'utf-8' => true, 'UTF-8' => true, - 'CP866' => true, 'IBM866' => true, '866' => true, - 'CP1251' => true, 'WINDOWS-1251' => true, 'WIN-1251' => true, - '1251' => true, - 'CP1252' => true, 'WINDOWS-1252' => true, '1252' => true, - 'KOI8-R' => true, 'KOI8-RU' => true, 'KOI8R' => true, - 'BIG5' => true, '950' => true, - 'GB2312' => true, '936' => true, - 'BIG5-HKSCS' => true, - 'SHIFT_JIS' => true, 'SJIS' => true, '932' => true, - 'EUC-JP' => true, 'EUCJP' => true, - 'ISO8859-5' => true, 'ISO-8859-5' => true, 'MACROMAN' => true, - ]; - - if (isset($htmlspecialcharsCharsets[$charset])) { - return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset); - } - - if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) { - // cache the lowercase variant for future iterations - $htmlspecialcharsCharsets[$charset] = true; - - return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset); - } - - $string = twig_convert_encoding($string, 'UTF-8', $charset); - $string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); - - return twig_convert_encoding($string, $charset, 'UTF-8'); - - case 'js': - // escape all non-alphanumeric characters - // into their \x or \uHHHH representations - if ('UTF-8' !== $charset) { - $string = twig_convert_encoding($string, 'UTF-8', $charset); - } - - if (!preg_match('//u', $string)) { - throw new RuntimeError('The string to escape is not a valid UTF-8 string.'); - } - - $string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', '_twig_escape_js_callback', $string); - - if ('UTF-8' !== $charset) { - $string = twig_convert_encoding($string, $charset, 'UTF-8'); - } - - return $string; - - case 'css': - if ('UTF-8' !== $charset) { - $string = twig_convert_encoding($string, 'UTF-8', $charset); - } - - if (!preg_match('//u', $string)) { - throw new RuntimeError('The string to escape is not a valid UTF-8 string.'); - } - - $string = preg_replace_callback('#[^a-zA-Z0-9]#Su', '_twig_escape_css_callback', $string); - - if ('UTF-8' !== $charset) { - $string = twig_convert_encoding($string, $charset, 'UTF-8'); - } - - return $string; - - case 'html_attr': - if ('UTF-8' !== $charset) { - $string = twig_convert_encoding($string, 'UTF-8', $charset); - } - - if (!preg_match('//u', $string)) { - throw new RuntimeError('The string to escape is not a valid UTF-8 string.'); - } - - $string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', '_twig_escape_html_attr_callback', $string); - - if ('UTF-8' !== $charset) { - $string = twig_convert_encoding($string, $charset, 'UTF-8'); - } - - return $string; - - case 'url': - return rawurlencode($string); - - default: - static $escapers; - - if (null === $escapers) { - $escapers = $env->getExtension('\Twig\Extension\CoreExtension')->getEscapers(); - } - - if (isset($escapers[$strategy])) { - return \call_user_func($escapers[$strategy], $env, $string, $charset); - } - - $validStrategies = implode(', ', array_merge(['html', 'js', 'url', 'css', 'html_attr'], array_keys($escapers))); - - throw new RuntimeError(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies)); - } -} - -/** - * @internal - */ -function twig_escape_filter_is_safe(Node $filterArgs) -{ - foreach ($filterArgs as $arg) { - if ($arg instanceof ConstantExpression) { - return [$arg->getAttribute('value')]; - } - - return []; - } - - return ['html']; -} - -if (\function_exists('mb_convert_encoding')) { - function twig_convert_encoding($string, $to, $from) - { - return mb_convert_encoding($string, $to, $from); - } -} elseif (\function_exists('iconv')) { - function twig_convert_encoding($string, $to, $from) - { - return iconv($from, $to, $string); - } -} else { - function twig_convert_encoding($string, $to, $from) - { - throw new RuntimeError('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).'); - } -} - -if (\function_exists('mb_ord')) { - function twig_ord($string) - { - return mb_ord($string, 'UTF-8'); - } -} else { - function twig_ord($string) - { - $code = ($string = unpack('C*', substr($string, 0, 4))) ? $string[1] : 0; - if (0xF0 <= $code) { - return (($code - 0xF0) << 18) + (($string[2] - 0x80) << 12) + (($string[3] - 0x80) << 6) + $string[4] - 0x80; - } - if (0xE0 <= $code) { - return (($code - 0xE0) << 12) + (($string[2] - 0x80) << 6) + $string[3] - 0x80; - } - if (0xC0 <= $code) { - return (($code - 0xC0) << 6) + $string[2] - 0x80; - } - - return $code; - } -} - -function _twig_escape_js_callback($matches) -{ - $char = $matches[0]; - - /* - * A few characters have short escape sequences in JSON and JavaScript. - * Escape sequences supported only by JavaScript, not JSON, are ommitted. - * \" is also supported but omitted, because the resulting string is not HTML safe. - */ - static $shortMap = [ - '\\' => '\\\\', - '/' => '\\/', - "\x08" => '\b', - "\x0C" => '\f', - "\x0A" => '\n', - "\x0D" => '\r', - "\x09" => '\t', - ]; - - if (isset($shortMap[$char])) { - return $shortMap[$char]; - } - - // \uHHHH - $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8'); - $char = strtoupper(bin2hex($char)); - - if (4 >= \strlen($char)) { - return sprintf('\u%04s', $char); - } - - return sprintf('\u%04s\u%04s', substr($char, 0, -4), substr($char, -4)); -} - -function _twig_escape_css_callback($matches) -{ - $char = $matches[0]; - - return sprintf('\\%X ', 1 === \strlen($char) ? \ord($char) : twig_ord($char)); -} - -/** - * This function is adapted from code coming from Zend Framework. - * - * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (https://www.zend.com) - * @license https://framework.zend.com/license/new-bsd New BSD License - */ -function _twig_escape_html_attr_callback($matches) -{ - $chr = $matches[0]; - $ord = \ord($chr); - - /* - * The following replaces characters undefined in HTML with the - * hex entity for the Unicode replacement character. - */ - if (($ord <= 0x1f && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($ord >= 0x7f && $ord <= 0x9f)) { - return '�'; - } - - /* - * Check if the current character to escape has a name entity we should - * replace it with while grabbing the hex value of the character. - */ - if (1 == \strlen($chr)) { - /* - * While HTML supports far more named entities, the lowest common denominator - * has become HTML5's XML Serialisation which is restricted to the those named - * entities that XML supports. Using HTML entities would result in this error: - * XML Parsing Error: undefined entity - */ - static $entityMap = [ - 34 => '"', /* quotation mark */ - 38 => '&', /* ampersand */ - 60 => '<', /* less-than sign */ - 62 => '>', /* greater-than sign */ - ]; - - if (isset($entityMap[$ord])) { - return $entityMap[$ord]; - } - - return sprintf('&#x%02X;', $ord); - } - - /* - * Per OWASP recommendations, we'll use hex entities for any other - * characters where a named entity does not exist. - */ - return sprintf('&#x%04X;', twig_ord($chr)); -} - -// add multibyte extensions if possible -if (\function_exists('mb_get_info')) { - /** - * Returns the length of a variable. - * - * @param mixed $thing A variable - * - * @return int The length of the value - */ - function twig_length_filter(Environment $env, $thing) - { - if (null === $thing) { - return 0; - } - - if (is_scalar($thing)) { - return mb_strlen($thing, $env->getCharset()); - } - - if ($thing instanceof \Countable || \is_array($thing) || $thing instanceof \SimpleXMLElement) { - return \count($thing); - } - - if ($thing instanceof \Traversable) { - return iterator_count($thing); - } - - if (\is_object($thing) && method_exists($thing, '__toString')) { - return mb_strlen((string) $thing, $env->getCharset()); - } - - return 1; - } - - /** - * Converts a string to uppercase. - * - * @param string $string A string - * - * @return string The uppercased string - */ - function twig_upper_filter(Environment $env, $string) - { - if (null !== $charset = $env->getCharset()) { - return mb_strtoupper($string, $charset); - } - - return strtoupper($string); - } - - /** - * Converts a string to lowercase. - * - * @param string $string A string - * - * @return string The lowercased string - */ - function twig_lower_filter(Environment $env, $string) - { - if (null !== $charset = $env->getCharset()) { - return mb_strtolower($string, $charset); - } - - return strtolower($string); - } - - /** - * Returns a titlecased string. - * - * @param string $string A string - * - * @return string The titlecased string - */ - function twig_title_string_filter(Environment $env, $string) - { - if (null !== $charset = $env->getCharset()) { - return mb_convert_case($string, MB_CASE_TITLE, $charset); - } - - return ucwords(strtolower($string)); - } - - /** - * Returns a capitalized string. - * - * @param string $string A string - * - * @return string The capitalized string - */ - function twig_capitalize_string_filter(Environment $env, $string) - { - if (null !== $charset = $env->getCharset()) { - return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset); - } - - return ucfirst(strtolower($string)); - } -} -// and byte fallback -else { - /** - * Returns the length of a variable. - * - * @param mixed $thing A variable - * - * @return int The length of the value - */ - function twig_length_filter(Environment $env, $thing) - { - if (null === $thing) { - return 0; - } - - if (is_scalar($thing)) { - return \strlen($thing); - } - - if ($thing instanceof \SimpleXMLElement) { - return \count($thing); - } - - if (\is_object($thing) && method_exists($thing, '__toString') && !$thing instanceof \Countable) { - return \strlen((string) $thing); - } - - if ($thing instanceof \Countable || \is_array($thing)) { - return \count($thing); - } - - if ($thing instanceof \IteratorAggregate) { - return iterator_count($thing); - } - - return 1; - } - - /** - * Returns a titlecased string. - * - * @param string $string A string - * - * @return string The titlecased string - */ - function twig_title_string_filter(Environment $env, $string) - { - return ucwords(strtolower($string)); - } - - /** - * Returns a capitalized string. - * - * @param string $string A string - * - * @return string The capitalized string - */ - function twig_capitalize_string_filter(Environment $env, $string) - { - return ucfirst(strtolower($string)); - } -} - -/** - * @internal - */ -function twig_ensure_traversable($seq) -{ - if ($seq instanceof \Traversable || \is_array($seq)) { - return $seq; - } - - return []; -} - -/** - * @internal - */ -function twig_to_array($seq, $preserveKeys = true) -{ - if ($seq instanceof \Traversable) { - return iterator_to_array($seq, $preserveKeys); - } - - if (!\is_array($seq)) { - return $seq; - } - - return $preserveKeys ? $seq : array_values($seq); -} - -/** - * Checks if a variable is empty. - * - * {# evaluates to true if the foo variable is null, false, or the empty string #} - * {% if foo is empty %} - * {# ... #} - * {% endif %} - * - * @param mixed $value A variable - * - * @return bool true if the value is empty, false otherwise - */ -function twig_test_empty($value) -{ - if ($value instanceof \Countable) { - return 0 == \count($value); - } - - if ($value instanceof \Traversable) { - return !iterator_count($value); - } - - if (\is_object($value) && method_exists($value, '__toString')) { - return '' === (string) $value; - } - - return '' === $value || false === $value || null === $value || [] === $value; -} - -/** - * Checks if a variable is traversable. - * - * {# evaluates to true if the foo variable is an array or a traversable object #} - * {% if foo is iterable %} - * {# ... #} - * {% endif %} - * - * @param mixed $value A variable - * - * @return bool true if the value is traversable - */ -function twig_test_iterable($value) -{ - return $value instanceof \Traversable || \is_array($value); -} - -/** - * Renders a template. - * - * @param array $context - * @param string|array $template The template to render or an array of templates to try consecutively - * @param array $variables The variables to pass to the template - * @param bool $withContext - * @param bool $ignoreMissing Whether to ignore missing templates or not - * @param bool $sandboxed Whether to sandbox the template or not - * - * @return string The rendered template - */ -function twig_include(Environment $env, $context, $template, $variables = [], $withContext = true, $ignoreMissing = false, $sandboxed = false) -{ - $alreadySandboxed = false; - $sandbox = null; - if ($withContext) { - $variables = array_merge($context, $variables); - } - - if ($isSandboxed = $sandboxed && $env->hasExtension('\Twig\Extension\SandboxExtension')) { - $sandbox = $env->getExtension('\Twig\Extension\SandboxExtension'); - if (!$alreadySandboxed = $sandbox->isSandboxed()) { - $sandbox->enableSandbox(); - } - } - - $loaded = null; - try { - $loaded = $env->resolveTemplate($template); - } catch (LoaderError $e) { - if (!$ignoreMissing) { - if ($isSandboxed && !$alreadySandboxed) { - $sandbox->disableSandbox(); - } - - throw $e; - } - } catch (\Throwable $e) { - if ($isSandboxed && !$alreadySandboxed) { - $sandbox->disableSandbox(); - } - - throw $e; - } catch (\Exception $e) { - if ($isSandboxed && !$alreadySandboxed) { - $sandbox->disableSandbox(); - } - - throw $e; - } - - try { - $ret = $loaded ? $loaded->render($variables) : ''; - } catch (\Exception $e) { - if ($isSandboxed && !$alreadySandboxed) { - $sandbox->disableSandbox(); - } - - throw $e; - } - - if ($isSandboxed && !$alreadySandboxed) { - $sandbox->disableSandbox(); - } - - return $ret; -} - -/** - * Returns a template content without rendering it. - * - * @param string $name The template name - * @param bool $ignoreMissing Whether to ignore missing templates or not - * - * @return string The template source - */ -function twig_source(Environment $env, $name, $ignoreMissing = false) -{ - $loader = $env->getLoader(); - try { - if (!$loader instanceof SourceContextLoaderInterface) { - return $loader->getSource($name); - } else { - return $loader->getSourceContext($name)->getCode(); - } - } catch (LoaderError $e) { - if (!$ignoreMissing) { - throw $e; - } - } -} - -/** - * Provides the ability to get constants from instances as well as class/global constants. - * - * @param string $constant The name of the constant - * @param object|null $object The object to get the constant from - * - * @return string - */ -function twig_constant($constant, $object = null) -{ - if (null !== $object) { - $constant = \get_class($object).'::'.$constant; - } - - return \constant($constant); -} - -/** - * Checks if a constant exists. - * - * @param string $constant The name of the constant - * @param object|null $object The object to get the constant from - * - * @return bool - */ -function twig_constant_is_defined($constant, $object = null) -{ - if (null !== $object) { - $constant = \get_class($object).'::'.$constant; - } - - return \defined($constant); -} - -/** - * Batches item. - * - * @param array $items An array of items - * @param int $size The size of the batch - * @param mixed $fill A value used to fill missing items - * - * @return array - */ -function twig_array_batch($items, $size, $fill = null, $preserveKeys = true) -{ - if (!twig_test_iterable($items)) { - throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', \is_object($items) ? \get_class($items) : \gettype($items))); - } - - $size = ceil($size); - - $result = array_chunk(twig_to_array($items, $preserveKeys), $size, $preserveKeys); - - if (null !== $fill && $result) { - $last = \count($result) - 1; - if ($fillCount = $size - \count($result[$last])) { - for ($i = 0; $i < $fillCount; ++$i) { - $result[$last][] = $fill; - } - } - } - - return $result; -} - -function twig_array_filter($array, $arrow) -{ - if (\is_array($array)) { - if (\PHP_VERSION_ID >= 50600) { - return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH); - } - - return array_filter($array, $arrow); - } - - // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator - return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow); -} - -function twig_array_map($array, $arrow) -{ - $r = []; - foreach ($array as $k => $v) { - $r[$k] = $arrow($v, $k); - } - - return $r; -} - -function twig_array_reduce($array, $arrow, $initial = null) -{ - if (!\is_array($array)) { - $array = iterator_to_array($array); - } - - return array_reduce($array, $arrow, $initial); -} -} diff --git a/application/third_party/Twig/Extension/DebugExtension.php b/application/third_party/Twig/Extension/DebugExtension.php deleted file mode 100644 index 09b0223e2f7..00000000000 --- a/application/third_party/Twig/Extension/DebugExtension.php +++ /dev/null @@ -1,76 +0,0 @@ - $isDumpOutputHtmlSafe ? ['html'] : [], 'needs_context' => true, 'needs_environment' => true, 'is_variadic' => true]), - ]; - } - - public function getName() - { - return 'debug'; - } -} - -class_alias('Twig\Extension\DebugExtension', 'Twig_Extension_Debug'); -} - -namespace { -use Twig\Environment; -use Twig\Template; -use Twig\TemplateWrapper; - -function twig_var_dump(Environment $env, $context, array $vars = []) -{ - if (!$env->isDebug()) { - return; - } - - ob_start(); - - if (!$vars) { - $vars = []; - foreach ($context as $key => $value) { - if (!$value instanceof Template && !$value instanceof TemplateWrapper) { - $vars[$key] = $value; - } - } - - var_dump($vars); - } else { - foreach ($vars as $var) { - var_dump($var); - } - } - - return ob_get_clean(); -} -} diff --git a/application/third_party/Twig/Extension/EscaperExtension.php b/application/third_party/Twig/Extension/EscaperExtension.php deleted file mode 100644 index fc7f6dfeead..00000000000 --- a/application/third_party/Twig/Extension/EscaperExtension.php +++ /dev/null @@ -1,120 +0,0 @@ -setDefaultStrategy($defaultStrategy); - } - - public function getTokenParsers() - { - return [new AutoEscapeTokenParser()]; - } - - public function getNodeVisitors() - { - return [new EscaperNodeVisitor()]; - } - - public function getFilters() - { - return [ - new TwigFilter('raw', 'twig_raw_filter', ['is_safe' => ['all']]), - ]; - } - - /** - * Sets the default strategy to use when not defined by the user. - * - * The strategy can be a valid PHP callback that takes the template - * name as an argument and returns the strategy to use. - * - * @param string|false|callable $defaultStrategy An escaping strategy - */ - public function setDefaultStrategy($defaultStrategy) - { - // for BC - if (true === $defaultStrategy) { - @trigger_error('Using "true" as the default strategy is deprecated since version 1.21. Use "html" instead.', E_USER_DEPRECATED); - - $defaultStrategy = 'html'; - } - - if ('filename' === $defaultStrategy) { - @trigger_error('Using "filename" as the default strategy is deprecated since version 1.27. Use "name" instead.', E_USER_DEPRECATED); - - $defaultStrategy = 'name'; - } - - if ('name' === $defaultStrategy) { - $defaultStrategy = ['\Twig\FileExtensionEscapingStrategy', 'guess']; - } - - $this->defaultStrategy = $defaultStrategy; - } - - /** - * Gets the default strategy to use when not defined by the user. - * - * @param string $name The template name - * - * @return string|false The default strategy to use for the template - */ - public function getDefaultStrategy($name) - { - // disable string callables to avoid calling a function named html or js, - // or any other upcoming escaping strategy - if (!\is_string($this->defaultStrategy) && false !== $this->defaultStrategy) { - return \call_user_func($this->defaultStrategy, $name); - } - - return $this->defaultStrategy; - } - - public function getName() - { - return 'escaper'; - } -} - -class_alias('Twig\Extension\EscaperExtension', 'Twig_Extension_Escaper'); -} - -namespace { -/** - * Marks a variable as being safe. - * - * @param string $string A PHP variable - * - * @return string - */ -function twig_raw_filter($string) -{ - return $string; -} -} diff --git a/application/third_party/Twig/Extension/ExtensionInterface.php b/application/third_party/Twig/Extension/ExtensionInterface.php deleted file mode 100644 index 72b31e9d1af..00000000000 --- a/application/third_party/Twig/Extension/ExtensionInterface.php +++ /dev/null @@ -1,101 +0,0 @@ - - */ -interface ExtensionInterface -{ - /** - * Initializes the runtime environment. - * - * This is where you can load some file that contains filter functions for instance. - * - * @deprecated since 1.23 (to be removed in 2.0), implement \Twig_Extension_InitRuntimeInterface instead - */ - public function initRuntime(Environment $environment); - - /** - * Returns the token parser instances to add to the existing list. - * - * @return TokenParserInterface[] - */ - public function getTokenParsers(); - - /** - * Returns the node visitor instances to add to the existing list. - * - * @return NodeVisitorInterface[] - */ - public function getNodeVisitors(); - - /** - * Returns a list of filters to add to the existing list. - * - * @return TwigFilter[] - */ - public function getFilters(); - - /** - * Returns a list of tests to add to the existing list. - * - * @return TwigTest[] - */ - public function getTests(); - - /** - * Returns a list of functions to add to the existing list. - * - * @return TwigFunction[] - */ - public function getFunctions(); - - /** - * Returns a list of operators to add to the existing list. - * - * @return array First array of unary operators, second array of binary operators - */ - public function getOperators(); - - /** - * Returns a list of global variables to add to the existing list. - * - * @return array An array of global variables - * - * @deprecated since 1.23 (to be removed in 2.0), implement \Twig_Extension_GlobalsInterface instead - */ - public function getGlobals(); - - /** - * Returns the name of the extension. - * - * @return string The extension name - * - * @deprecated since 1.26 (to be removed in 2.0), not used anymore internally - */ - public function getName(); -} - -class_alias('Twig\Extension\ExtensionInterface', 'Twig_ExtensionInterface'); - -// Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. -class_exists('Twig\Environment'); diff --git a/application/third_party/Twig/Extension/GlobalsInterface.php b/application/third_party/Twig/Extension/GlobalsInterface.php index 1f54e257245..5370b8e2aa7 100644 --- a/application/third_party/Twig/Extension/GlobalsInterface.php +++ b/application/third_party/Twig/Extension/GlobalsInterface.php @@ -9,18 +9,14 @@ * file that was distributed with this source code. */ -namespace Twig\Extension; - /** - * Enables usage of the deprecated Twig\Extension\AbstractExtension::getGlobals() method. + * Enables usage of the deprecated Twig_Extension::getGlobals() method. * * Explicitly implement this interface if you really need to implement the * deprecated getGlobals() method in your extensions. * * @author Fabien Potencier */ -interface GlobalsInterface +interface Twig_Extension_GlobalsInterface { } - -class_alias('Twig\Extension\GlobalsInterface', 'Twig_Extension_GlobalsInterface'); diff --git a/application/third_party/Twig/Extension/InitRuntimeInterface.php b/application/third_party/Twig/Extension/InitRuntimeInterface.php index f71d9cb51dc..7a075822f21 100644 --- a/application/third_party/Twig/Extension/InitRuntimeInterface.php +++ b/application/third_party/Twig/Extension/InitRuntimeInterface.php @@ -9,18 +9,14 @@ * file that was distributed with this source code. */ -namespace Twig\Extension; - /** - * Enables usage of the deprecated Twig\Extension\AbstractExtension::initRuntime() method. + * Enables usage of the deprecated Twig_Extension::initRuntime() method. * * Explicitly implement this interface if you really need to implement the * deprecated initRuntime() method in your extensions. * * @author Fabien Potencier */ -interface InitRuntimeInterface +interface Twig_Extension_InitRuntimeInterface { } - -class_alias('Twig\Extension\InitRuntimeInterface', 'Twig_Extension_InitRuntimeInterface'); diff --git a/application/third_party/Twig/Extension/OptimizerExtension.php b/application/third_party/Twig/Extension/OptimizerExtension.php deleted file mode 100644 index 3e137409e27..00000000000 --- a/application/third_party/Twig/Extension/OptimizerExtension.php +++ /dev/null @@ -1,39 +0,0 @@ -optimizers = $optimizers; - } - - public function getNodeVisitors() - { - return [new OptimizerNodeVisitor($this->optimizers)]; - } - - public function getName() - { - return 'optimizer'; - } -} - -class_alias('Twig\Extension\OptimizerExtension', 'Twig_Extension_Optimizer'); diff --git a/application/third_party/Twig/Extension/ProfilerExtension.php b/application/third_party/Twig/Extension/ProfilerExtension.php deleted file mode 100644 index 7b21b9fa555..00000000000 --- a/application/third_party/Twig/Extension/ProfilerExtension.php +++ /dev/null @@ -1,53 +0,0 @@ -actives[] = $profile; - } - - public function enter(Profile $profile) - { - $this->actives[0]->addProfile($profile); - array_unshift($this->actives, $profile); - } - - public function leave(Profile $profile) - { - $profile->leave(); - array_shift($this->actives); - - if (1 === \count($this->actives)) { - $this->actives[0]->leave(); - } - } - - public function getNodeVisitors() - { - return [new ProfilerNodeVisitor(\get_class($this))]; - } - - public function getName() - { - return 'profiler'; - } -} - -class_alias('Twig\Extension\ProfilerExtension', 'Twig_Extension_Profiler'); diff --git a/application/third_party/Twig/Extension/RuntimeExtensionInterface.php b/application/third_party/Twig/Extension/RuntimeExtensionInterface.php deleted file mode 100644 index 63bc3b1ab10..00000000000 --- a/application/third_party/Twig/Extension/RuntimeExtensionInterface.php +++ /dev/null @@ -1,19 +0,0 @@ - - */ -interface RuntimeExtensionInterface -{ -} diff --git a/application/third_party/Twig/Extension/SandboxExtension.php b/application/third_party/Twig/Extension/SandboxExtension.php deleted file mode 100644 index 818c8c94c81..00000000000 --- a/application/third_party/Twig/Extension/SandboxExtension.php +++ /dev/null @@ -1,109 +0,0 @@ -policy = $policy; - $this->sandboxedGlobally = $sandboxed; - } - - public function getTokenParsers() - { - return [new SandboxTokenParser()]; - } - - public function getNodeVisitors() - { - return [new SandboxNodeVisitor()]; - } - - public function enableSandbox() - { - $this->sandboxed = true; - } - - public function disableSandbox() - { - $this->sandboxed = false; - } - - public function isSandboxed() - { - return $this->sandboxedGlobally || $this->sandboxed; - } - - public function isSandboxedGlobally() - { - return $this->sandboxedGlobally; - } - - public function setSecurityPolicy(SecurityPolicyInterface $policy) - { - $this->policy = $policy; - } - - public function getSecurityPolicy() - { - return $this->policy; - } - - public function checkSecurity($tags, $filters, $functions) - { - if ($this->isSandboxed()) { - $this->policy->checkSecurity($tags, $filters, $functions); - } - } - - public function checkMethodAllowed($obj, $method) - { - if ($this->isSandboxed()) { - $this->policy->checkMethodAllowed($obj, $method); - } - } - - public function checkPropertyAllowed($obj, $method) - { - if ($this->isSandboxed()) { - $this->policy->checkPropertyAllowed($obj, $method); - } - } - - public function ensureToStringAllowed($obj) - { - if ($this->isSandboxed() && \is_object($obj) && method_exists($obj, '__toString')) { - $this->policy->checkMethodAllowed($obj, '__toString'); - } - - return $obj; - } - - public function getName() - { - return 'sandbox'; - } -} - -class_alias('Twig\Extension\SandboxExtension', 'Twig_Extension_Sandbox'); diff --git a/application/third_party/Twig/Extension/StagingExtension.php b/application/third_party/Twig/Extension/StagingExtension.php deleted file mode 100644 index 049c5c79775..00000000000 --- a/application/third_party/Twig/Extension/StagingExtension.php +++ /dev/null @@ -1,117 +0,0 @@ - - * - * @internal - */ -class StagingExtension extends AbstractExtension -{ - protected $functions = []; - protected $filters = []; - protected $visitors = []; - protected $tokenParsers = []; - protected $globals = []; - protected $tests = []; - - public function addFunction($name, $function) - { - if (isset($this->functions[$name])) { - @trigger_error(sprintf('Overriding function "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $name), E_USER_DEPRECATED); - } - - $this->functions[$name] = $function; - } - - public function getFunctions() - { - return $this->functions; - } - - public function addFilter($name, $filter) - { - if (isset($this->filters[$name])) { - @trigger_error(sprintf('Overriding filter "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $name), E_USER_DEPRECATED); - } - - $this->filters[$name] = $filter; - } - - public function getFilters() - { - return $this->filters; - } - - public function addNodeVisitor(NodeVisitorInterface $visitor) - { - $this->visitors[] = $visitor; - } - - public function getNodeVisitors() - { - return $this->visitors; - } - - public function addTokenParser(TokenParserInterface $parser) - { - if (isset($this->tokenParsers[$parser->getTag()])) { - @trigger_error(sprintf('Overriding tag "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $parser->getTag()), E_USER_DEPRECATED); - } - - $this->tokenParsers[$parser->getTag()] = $parser; - } - - public function getTokenParsers() - { - return $this->tokenParsers; - } - - public function addGlobal($name, $value) - { - $this->globals[$name] = $value; - } - - public function getGlobals() - { - return $this->globals; - } - - public function addTest($name, $test) - { - if (isset($this->tests[$name])) { - @trigger_error(sprintf('Overriding test "%s" that is already registered is deprecated since version 1.30 and won\'t be possible anymore in 2.0.', $name), E_USER_DEPRECATED); - } - - $this->tests[$name] = $test; - } - - public function getTests() - { - return $this->tests; - } - - public function getName() - { - return 'staging'; - } -} - -class_alias('Twig\Extension\StagingExtension', 'Twig_Extension_Staging'); diff --git a/application/third_party/Twig/Extension/StringLoaderExtension.php b/application/third_party/Twig/Extension/StringLoaderExtension.php deleted file mode 100644 index 93ac834ac24..00000000000 --- a/application/third_party/Twig/Extension/StringLoaderExtension.php +++ /dev/null @@ -1,54 +0,0 @@ - true]), - ]; - } - - public function getName() - { - return 'string_loader'; - } -} - -class_alias('Twig\Extension\StringLoaderExtension', 'Twig_Extension_StringLoader'); -} - -namespace { -use Twig\Environment; -use Twig\TemplateWrapper; - -/** - * Loads a template from a string. - * - * {{ include(template_from_string("Hello {{ name }}")) }} - * - * @param string $template A template as a string or object implementing __toString() - * @param string $name An optional name of the template to be used in error messages - * - * @return TemplateWrapper - */ -function twig_template_from_string(Environment $env, $template, $name = null) -{ - return $env->createTemplate((string) $template, $name); -} -} diff --git a/application/third_party/Twig/FileExtensionEscapingStrategy.php b/application/third_party/Twig/FileExtensionEscapingStrategy.php index bc95f33435c..772139e23cc 100644 --- a/application/third_party/Twig/FileExtensionEscapingStrategy.php +++ b/application/third_party/Twig/FileExtensionEscapingStrategy.php @@ -3,14 +3,12 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2015 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - /** * Default autoescaping strategy based on file names. * @@ -22,7 +20,7 @@ * * @author Fabien Potencier */ -class FileExtensionEscapingStrategy +class Twig_FileExtensionEscapingStrategy { /** * Guesses the best autoescaping strategy based on the file name. @@ -33,7 +31,7 @@ class FileExtensionEscapingStrategy */ public static function guess($name) { - if (\in_array(substr($name, -1), ['/', '\\'])) { + if (in_array(substr($name, -1), array('/', '\\'))) { return 'html'; // return html for directories } @@ -58,5 +56,3 @@ public static function guess($name) } } } - -class_alias('Twig\FileExtensionEscapingStrategy', 'Twig_FileExtensionEscapingStrategy'); diff --git a/application/third_party/Twig/Lexer.php b/application/third_party/Twig/Lexer.php index 697a6cfa1d1..295379aee39 100644 --- a/application/third_party/Twig/Lexer.php +++ b/application/third_party/Twig/Lexer.php @@ -3,23 +3,19 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier - * (c) Armin Ronacher + * (c) 2009 Fabien Potencier + * (c) 2009 Armin Ronacher * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\Error\SyntaxError; - /** * Lexes a template string. * * @author Fabien Potencier */ -class Lexer implements \Twig_LexerInterface +class Twig_Lexer implements Twig_LexerInterface { protected $tokens; protected $code; @@ -47,124 +43,46 @@ class Lexer implements \Twig_LexerInterface const STATE_INTERPOLATION = 4; const REGEX_NAME = '/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A'; - const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?([Ee][\+\-][0-9]+)?/A'; + const REGEX_NUMBER = '/[0-9]+(?:\.[0-9]+)?/A'; const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As'; const REGEX_DQ_STRING_DELIM = '/"/A'; const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As'; const PUNCTUATION = '()[]{}?:.,|'; - public function __construct(Environment $env, array $options = []) + public function __construct(Twig_Environment $env, array $options = array()) { $this->env = $env; - $this->options = array_merge([ - 'tag_comment' => ['{#', '#}'], - 'tag_block' => ['{%', '%}'], - 'tag_variable' => ['{{', '}}'], + $this->options = array_merge(array( + 'tag_comment' => array('{#', '#}'), + 'tag_block' => array('{%', '%}'), + 'tag_variable' => array('{{', '}}'), 'whitespace_trim' => '-', - 'whitespace_line_trim' => '~', - 'whitespace_line_chars' => ' \t\0\x0B', - 'interpolation' => ['#{', '}'], - ], $options); - - // when PHP 7.3 is the min version, we will be able to remove the '#' part in preg_quote as it's part of the default - $this->regexes = [ - // }} - 'lex_var' => '{ - \s* - (?:'. - preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '#').'\s*'. // -}}\s* - '|'. - preg_quote($this->options['whitespace_line_trim'].$this->options['tag_variable'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~}}[ \t\0\x0B]* - '|'. - preg_quote($this->options['tag_variable'][1], '#'). // }} - ') - }Ax', - - // %} - 'lex_block' => '{ - \s* - (?:'. - preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*\n?'. // -%}\s*\n? - '|'. - preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* - '|'. - preg_quote($this->options['tag_block'][1], '#').'\n?'. // %}\n? - ') - }Ax', - - // {% endverbatim %} - 'lex_raw_data' => '{'. - preg_quote($this->options['tag_block'][0], '#'). // {% - '('. - $this->options['whitespace_trim']. // - - '|'. - $this->options['whitespace_line_trim']. // ~ - ')?\s*'. - '(?:end%s)'. // endraw or endverbatim - '\s*'. - '(?:'. - preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%} - '|'. - preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* - '|'. - preg_quote($this->options['tag_block'][1], '#'). // %} - ') - }sx', + 'interpolation' => array('#{', '}'), + ), $options); + $this->regexes = array( + 'lex_var' => '/\s*'.preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_variable'][1], '/').'/A', + 'lex_block' => '/\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')\n?/A', + 'lex_raw_data' => '/('.preg_quote($this->options['tag_block'][0].$this->options['whitespace_trim'], '/').'|'.preg_quote($this->options['tag_block'][0], '/').')\s*(?:end%s)\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')/s', 'operator' => $this->getOperatorRegex(), - - // #} - 'lex_comment' => '{ - (?:'. - preg_quote($this->options['whitespace_trim']).preg_quote($this->options['tag_comment'][1], '#').'\s*\n?'. // -#}\s*\n? - '|'. - preg_quote($this->options['whitespace_line_trim'].$this->options['tag_comment'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~#}[ \t\0\x0B]* - '|'. - preg_quote($this->options['tag_comment'][1], '#').'\n?'. // #}\n? - ') - }sx', - - // verbatim %} - 'lex_block_raw' => '{ - \s* - (raw|verbatim) - \s* - (?:'. - preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%}\s* - '|'. - preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* - '|'. - preg_quote($this->options['tag_block'][1], '#'). // %} - ') - }Asx', - - 'lex_block_line' => '{\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '#').'}As', - - // {{ or {% or {# - 'lex_tokens_start' => '{ - ('. - preg_quote($this->options['tag_variable'][0], '#'). // {{ - '|'. - preg_quote($this->options['tag_block'][0], '#'). // {% - '|'. - preg_quote($this->options['tag_comment'][0], '#'). // {# - ')('. - preg_quote($this->options['whitespace_trim'], '#'). // - - '|'. - preg_quote($this->options['whitespace_line_trim'], '#'). // ~ - ')? - }sx', - 'interpolation_start' => '{'.preg_quote($this->options['interpolation'][0], '#').'\s*}A', - 'interpolation_end' => '{\s*'.preg_quote($this->options['interpolation'][1], '#').'}A', - ]; + 'lex_comment' => '/(?:'.preg_quote($this->options['whitespace_trim'], '/').preg_quote($this->options['tag_comment'][1], '/').'\s*|'.preg_quote($this->options['tag_comment'][1], '/').')\n?/s', + 'lex_block_raw' => '/\s*(raw|verbatim)\s*(?:'.preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '/').'\s*|\s*'.preg_quote($this->options['tag_block'][1], '/').')/As', + 'lex_block_line' => '/\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '/').'/As', + 'lex_tokens_start' => '/('.preg_quote($this->options['tag_variable'][0], '/').'|'.preg_quote($this->options['tag_block'][0], '/').'|'.preg_quote($this->options['tag_comment'][0], '/').')('.preg_quote($this->options['whitespace_trim'], '/').')?/s', + 'interpolation_start' => '/'.preg_quote($this->options['interpolation'][0], '/').'\s*/A', + 'interpolation_end' => '/\s*'.preg_quote($this->options['interpolation'][1], '/').'/A', + ); } + /** + * {@inheritdoc} + */ public function tokenize($code, $name = null) { - if (!$code instanceof Source) { - @trigger_error(sprintf('Passing a string as the $code argument of %s() is deprecated since version 1.27 and will be removed in 2.0. Pass a \Twig\Source instance instead.', __METHOD__), E_USER_DEPRECATED); - $this->source = new Source($code, $name); + if (!$code instanceof Twig_Source) { + @trigger_error(sprintf('Passing a string as the $code argument of %s() is deprecated since version 1.27 and will be removed in 2.0. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED); + $this->source = new Twig_Source($code, $name); } else { $this->source = $code; } @@ -173,22 +91,22 @@ public function tokenize($code, $name = null) @trigger_error('Support for having "mbstring.func_overload" different from 0 is deprecated version 1.29 and will be removed in 2.0.', E_USER_DEPRECATED); } - if (\function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { + if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { $mbEncoding = mb_internal_encoding(); mb_internal_encoding('ASCII'); } else { $mbEncoding = null; } - $this->code = str_replace(["\r\n", "\r"], "\n", $this->source->getCode()); + $this->code = str_replace(array("\r\n", "\r"), "\n", $this->source->getCode()); $this->filename = $this->source->getName(); $this->cursor = 0; $this->lineno = 1; - $this->end = \strlen($this->code); - $this->tokens = []; + $this->end = strlen($this->code); + $this->tokens = array(); $this->state = self::STATE_DATA; - $this->states = []; - $this->brackets = []; + $this->states = array(); + $this->brackets = array(); $this->position = -1; // find all token starts in one go @@ -221,25 +139,25 @@ public function tokenize($code, $name = null) } } - $this->pushToken(Token::EOF_TYPE); + $this->pushToken(Twig_Token::EOF_TYPE); if (!empty($this->brackets)) { list($expect, $lineno) = array_pop($this->brackets); - throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + throw new Twig_Error_Syntax(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); } if ($mbEncoding) { mb_internal_encoding($mbEncoding); } - return new TokenStream($this->tokens, $this->source); + return new Twig_TokenStream($this->tokens, $this->source); } protected function lexData() { // if no matches are left we return the rest of the template as simple text token - if ($this->position == \count($this->positions[0]) - 1) { - $this->pushToken(Token::TEXT_TYPE, substr($this->code, $this->cursor)); + if ($this->position == count($this->positions[0]) - 1) { + $this->pushToken(Twig_Token::TEXT_TYPE, substr($this->code, $this->cursor)); $this->cursor = $this->end; return; @@ -248,7 +166,7 @@ protected function lexData() // Find the first token after the current cursor $position = $this->positions[0][++$this->position]; while ($position[1] < $this->cursor) { - if ($this->position == \count($this->positions[0]) - 1) { + if ($this->position == count($this->positions[0]) - 1) { return; } $position = $this->positions[0][++$this->position]; @@ -256,19 +174,10 @@ protected function lexData() // push the template text first $text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor); - - // trim? if (isset($this->positions[2][$this->position][0])) { - if ($this->options['whitespace_trim'] === $this->positions[2][$this->position][0]) { - // whitespace_trim detected ({%-, {{- or {#-) - $text = rtrim($text); - } elseif ($this->options['whitespace_line_trim'] === $this->positions[2][$this->position][0]) { - // whitespace_line_trim detected ({%~, {{~ or {#~) - // don't trim \r and \n - $text = rtrim($text, " \t\0\x0B"); - } + $text = rtrim($text); } - $this->pushToken(Token::TEXT_TYPE, $text); + $this->pushToken(Twig_Token::TEXT_TYPE, $text); $this->moveCursor($textContent.$position[0]); switch ($this->positions[1][$this->position][0]) { @@ -278,22 +187,22 @@ protected function lexData() case $this->options['tag_block'][0]: // raw data? - if (preg_match($this->regexes['lex_block_raw'], $this->code, $match, 0, $this->cursor)) { + if (preg_match($this->regexes['lex_block_raw'], $this->code, $match, null, $this->cursor)) { $this->moveCursor($match[0]); $this->lexRawData($match[1]); // {% line \d+ %} - } elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, 0, $this->cursor)) { + } elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, null, $this->cursor)) { $this->moveCursor($match[0]); $this->lineno = (int) $match[1]; } else { - $this->pushToken(Token::BLOCK_START_TYPE); + $this->pushToken(Twig_Token::BLOCK_START_TYPE); $this->pushState(self::STATE_BLOCK); $this->currentVarBlockLine = $this->lineno; } break; case $this->options['tag_variable'][0]: - $this->pushToken(Token::VAR_START_TYPE); + $this->pushToken(Twig_Token::VAR_START_TYPE); $this->pushState(self::STATE_VAR); $this->currentVarBlockLine = $this->lineno; break; @@ -302,8 +211,8 @@ protected function lexData() protected function lexBlock() { - if (empty($this->brackets) && preg_match($this->regexes['lex_block'], $this->code, $match, 0, $this->cursor)) { - $this->pushToken(Token::BLOCK_END_TYPE); + if (empty($this->brackets) && preg_match($this->regexes['lex_block'], $this->code, $match, null, $this->cursor)) { + $this->pushToken(Twig_Token::BLOCK_END_TYPE); $this->moveCursor($match[0]); $this->popState(); } else { @@ -313,8 +222,8 @@ protected function lexBlock() protected function lexVar() { - if (empty($this->brackets) && preg_match($this->regexes['lex_var'], $this->code, $match, 0, $this->cursor)) { - $this->pushToken(Token::VAR_END_TYPE); + if (empty($this->brackets) && preg_match($this->regexes['lex_var'], $this->code, $match, null, $this->cursor)) { + $this->pushToken(Twig_Token::VAR_END_TYPE); $this->moveCursor($match[0]); $this->popState(); } else { @@ -325,73 +234,68 @@ protected function lexVar() protected function lexExpression() { // whitespace - if (preg_match('/\s+/A', $this->code, $match, 0, $this->cursor)) { + if (preg_match('/\s+/A', $this->code, $match, null, $this->cursor)) { $this->moveCursor($match[0]); if ($this->cursor >= $this->end) { - throw new SyntaxError(sprintf('Unclosed "%s".', self::STATE_BLOCK === $this->state ? 'block' : 'variable'), $this->currentVarBlockLine, $this->source); + throw new Twig_Error_Syntax(sprintf('Unclosed "%s".', $this->state === self::STATE_BLOCK ? 'block' : 'variable'), $this->currentVarBlockLine, $this->source); } } - // arrow function - if ('=' === $this->code[$this->cursor] && '>' === $this->code[$this->cursor + 1]) { - $this->pushToken(Token::ARROW_TYPE, '=>'); - $this->moveCursor('=>'); - } // operators - elseif (preg_match($this->regexes['operator'], $this->code, $match, 0, $this->cursor)) { - $this->pushToken(Token::OPERATOR_TYPE, preg_replace('/\s+/', ' ', $match[0])); + if (preg_match($this->regexes['operator'], $this->code, $match, null, $this->cursor)) { + $this->pushToken(Twig_Token::OPERATOR_TYPE, preg_replace('/\s+/', ' ', $match[0])); $this->moveCursor($match[0]); } // names - elseif (preg_match(self::REGEX_NAME, $this->code, $match, 0, $this->cursor)) { - $this->pushToken(Token::NAME_TYPE, $match[0]); + elseif (preg_match(self::REGEX_NAME, $this->code, $match, null, $this->cursor)) { + $this->pushToken(Twig_Token::NAME_TYPE, $match[0]); $this->moveCursor($match[0]); } // numbers - elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, 0, $this->cursor)) { + elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, null, $this->cursor)) { $number = (float) $match[0]; // floats if (ctype_digit($match[0]) && $number <= PHP_INT_MAX) { $number = (int) $match[0]; // integers lower than the maximum } - $this->pushToken(Token::NUMBER_TYPE, $number); + $this->pushToken(Twig_Token::NUMBER_TYPE, $number); $this->moveCursor($match[0]); } // punctuation elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) { // opening bracket if (false !== strpos('([{', $this->code[$this->cursor])) { - $this->brackets[] = [$this->code[$this->cursor], $this->lineno]; + $this->brackets[] = array($this->code[$this->cursor], $this->lineno); } // closing bracket elseif (false !== strpos(')]}', $this->code[$this->cursor])) { if (empty($this->brackets)) { - throw new SyntaxError(sprintf('Unexpected "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); + throw new Twig_Error_Syntax(sprintf('Unexpected "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); } list($expect, $lineno) = array_pop($this->brackets); if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) { - throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + throw new Twig_Error_Syntax(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); } } - $this->pushToken(Token::PUNCTUATION_TYPE, $this->code[$this->cursor]); + $this->pushToken(Twig_Token::PUNCTUATION_TYPE, $this->code[$this->cursor]); ++$this->cursor; } // strings - elseif (preg_match(self::REGEX_STRING, $this->code, $match, 0, $this->cursor)) { - $this->pushToken(Token::STRING_TYPE, stripcslashes(substr($match[0], 1, -1))); + elseif (preg_match(self::REGEX_STRING, $this->code, $match, null, $this->cursor)) { + $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes(substr($match[0], 1, -1))); $this->moveCursor($match[0]); } // opening double quoted string - elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) { - $this->brackets[] = ['"', $this->lineno]; + elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) { + $this->brackets[] = array('"', $this->lineno); $this->pushState(self::STATE_STRING); $this->moveCursor($match[0]); } // unlexable else { - throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); + throw new Twig_Error_Syntax(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); } } @@ -402,31 +306,23 @@ protected function lexRawData($tag) } if (!preg_match(str_replace('%s', $tag, $this->regexes['lex_raw_data']), $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { - throw new SyntaxError(sprintf('Unexpected end of file: Unclosed "%s" block.', $tag), $this->lineno, $this->source); + throw new Twig_Error_Syntax(sprintf('Unexpected end of file: Unclosed "%s" block.', $tag), $this->lineno, $this->source); } $text = substr($this->code, $this->cursor, $match[0][1] - $this->cursor); $this->moveCursor($text.$match[0][0]); - // trim? - if (isset($match[1][0])) { - if ($this->options['whitespace_trim'] === $match[1][0]) { - // whitespace_trim detected ({%-, {{- or {#-) - $text = rtrim($text); - } else { - // whitespace_line_trim detected ({%~, {{~ or {#~) - // don't trim \r and \n - $text = rtrim($text, " \t\0\x0B"); - } + if (false !== strpos($match[1][0], $this->options['whitespace_trim'])) { + $text = rtrim($text); } - $this->pushToken(Token::TEXT_TYPE, $text); + $this->pushToken(Twig_Token::TEXT_TYPE, $text); } protected function lexComment() { if (!preg_match($this->regexes['lex_comment'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { - throw new SyntaxError('Unclosed comment.', $this->lineno, $this->source); + throw new Twig_Error_Syntax('Unclosed comment.', $this->lineno, $this->source); } $this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]); @@ -434,34 +330,31 @@ protected function lexComment() protected function lexString() { - if (preg_match($this->regexes['interpolation_start'], $this->code, $match, 0, $this->cursor)) { - $this->brackets[] = [$this->options['interpolation'][0], $this->lineno]; - $this->pushToken(Token::INTERPOLATION_START_TYPE); + if (preg_match($this->regexes['interpolation_start'], $this->code, $match, null, $this->cursor)) { + $this->brackets[] = array($this->options['interpolation'][0], $this->lineno); + $this->pushToken(Twig_Token::INTERPOLATION_START_TYPE); $this->moveCursor($match[0]); $this->pushState(self::STATE_INTERPOLATION); - } elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, 0, $this->cursor) && \strlen($match[0]) > 0) { - $this->pushToken(Token::STRING_TYPE, stripcslashes($match[0])); + } elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, null, $this->cursor) && strlen($match[0]) > 0) { + $this->pushToken(Twig_Token::STRING_TYPE, stripcslashes($match[0])); $this->moveCursor($match[0]); - } elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) { + } elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, null, $this->cursor)) { list($expect, $lineno) = array_pop($this->brackets); - if ('"' != $this->code[$this->cursor]) { - throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + if ($this->code[$this->cursor] != '"') { + throw new Twig_Error_Syntax(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); } $this->popState(); ++$this->cursor; - } else { - // unlexable - throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); } } protected function lexInterpolation() { $bracket = end($this->brackets); - if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, 0, $this->cursor)) { + if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, null, $this->cursor)) { array_pop($this->brackets); - $this->pushToken(Token::INTERPOLATION_END_TYPE); + $this->pushToken(Twig_Token::INTERPOLATION_END_TYPE); $this->moveCursor($match[0]); $this->popState(); } else { @@ -472,23 +365,23 @@ protected function lexInterpolation() protected function pushToken($type, $value = '') { // do not push empty text tokens - if (Token::TEXT_TYPE === $type && '' === $value) { + if (Twig_Token::TEXT_TYPE === $type && '' === $value) { return; } - $this->tokens[] = new Token($type, $value, $this->lineno); + $this->tokens[] = new Twig_Token($type, $value, $this->lineno); } protected function moveCursor($text) { - $this->cursor += \strlen($text); + $this->cursor += strlen($text); $this->lineno += substr_count($text, "\n"); } protected function getOperatorRegex() { $operators = array_merge( - ['='], + array('='), array_keys($this->env->getUnaryOperators()), array_keys($this->env->getBinaryOperators()) ); @@ -496,7 +389,7 @@ protected function getOperatorRegex() $operators = array_combine($operators, array_map('strlen', $operators)); arsort($operators); - $regex = []; + $regex = array(); foreach ($operators as $operator => $length) { // an operator that ends with a character must be followed by // a whitespace or a parenthesis @@ -523,12 +416,10 @@ protected function pushState($state) protected function popState() { - if (0 === \count($this->states)) { - throw new \LogicException('Cannot pop state without a previous state.'); + if (0 === count($this->states)) { + throw new Exception('Cannot pop state without a previous state.'); } $this->state = array_pop($this->states); } } - -class_alias('Twig\Lexer', 'Twig_Lexer'); diff --git a/application/third_party/Twig/Loader/ArrayLoader.php b/application/third_party/Twig/Loader/ArrayLoader.php deleted file mode 100644 index 6bc430f50e4..00000000000 --- a/application/third_party/Twig/Loader/ArrayLoader.php +++ /dev/null @@ -1,102 +0,0 @@ - - */ -class ArrayLoader implements LoaderInterface, ExistsLoaderInterface, SourceContextLoaderInterface -{ - protected $templates = []; - - /** - * @param array $templates An array of templates (keys are the names, and values are the source code) - */ - public function __construct(array $templates = []) - { - $this->templates = $templates; - } - - /** - * Adds or overrides a template. - * - * @param string $name The template name - * @param string $template The template source - */ - public function setTemplate($name, $template) - { - $this->templates[(string) $name] = $template; - } - - public function getSource($name) - { - @trigger_error(sprintf('Calling "getSource" on "%s" is deprecated since 1.27. Use getSourceContext() instead.', \get_class($this)), E_USER_DEPRECATED); - - $name = (string) $name; - if (!isset($this->templates[$name])) { - throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); - } - - return $this->templates[$name]; - } - - public function getSourceContext($name) - { - $name = (string) $name; - if (!isset($this->templates[$name])) { - throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); - } - - return new Source($this->templates[$name], $name); - } - - public function exists($name) - { - return isset($this->templates[(string) $name]); - } - - public function getCacheKey($name) - { - $name = (string) $name; - if (!isset($this->templates[$name])) { - throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); - } - - return $name.':'.$this->templates[$name]; - } - - public function isFresh($name, $time) - { - $name = (string) $name; - if (!isset($this->templates[$name])) { - throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); - } - - return true; - } -} - -class_alias('Twig\Loader\ArrayLoader', 'Twig_Loader_Array'); diff --git a/application/third_party/Twig/Loader/ChainLoader.php b/application/third_party/Twig/Loader/ChainLoader.php deleted file mode 100644 index 25ac55a335b..00000000000 --- a/application/third_party/Twig/Loader/ChainLoader.php +++ /dev/null @@ -1,164 +0,0 @@ - - */ -class ChainLoader implements LoaderInterface, ExistsLoaderInterface, SourceContextLoaderInterface -{ - private $hasSourceCache = []; - protected $loaders = []; - - /** - * @param LoaderInterface[] $loaders - */ - public function __construct(array $loaders = []) - { - foreach ($loaders as $loader) { - $this->addLoader($loader); - } - } - - public function addLoader(LoaderInterface $loader) - { - $this->loaders[] = $loader; - $this->hasSourceCache = []; - } - - /** - * @return LoaderInterface[] - */ - public function getLoaders() - { - return $this->loaders; - } - - public function getSource($name) - { - @trigger_error(sprintf('Calling "getSource" on "%s" is deprecated since 1.27. Use getSourceContext() instead.', \get_class($this)), E_USER_DEPRECATED); - - $exceptions = []; - foreach ($this->loaders as $loader) { - if ($loader instanceof ExistsLoaderInterface && !$loader->exists($name)) { - continue; - } - - try { - return $loader->getSource($name); - } catch (LoaderError $e) { - $exceptions[] = $e->getMessage(); - } - } - - throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); - } - - public function getSourceContext($name) - { - $exceptions = []; - foreach ($this->loaders as $loader) { - if ($loader instanceof ExistsLoaderInterface && !$loader->exists($name)) { - continue; - } - - try { - if ($loader instanceof SourceContextLoaderInterface) { - return $loader->getSourceContext($name); - } - - return new Source($loader->getSource($name), $name); - } catch (LoaderError $e) { - $exceptions[] = $e->getMessage(); - } - } - - throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); - } - - public function exists($name) - { - $name = (string) $name; - - if (isset($this->hasSourceCache[$name])) { - return $this->hasSourceCache[$name]; - } - - foreach ($this->loaders as $loader) { - if ($loader instanceof ExistsLoaderInterface) { - if ($loader->exists($name)) { - return $this->hasSourceCache[$name] = true; - } - - continue; - } - - try { - if ($loader instanceof SourceContextLoaderInterface) { - $loader->getSourceContext($name); - } else { - $loader->getSource($name); - } - - return $this->hasSourceCache[$name] = true; - } catch (LoaderError $e) { - } - } - - return $this->hasSourceCache[$name] = false; - } - - public function getCacheKey($name) - { - $exceptions = []; - foreach ($this->loaders as $loader) { - if ($loader instanceof ExistsLoaderInterface && !$loader->exists($name)) { - continue; - } - - try { - return $loader->getCacheKey($name); - } catch (LoaderError $e) { - $exceptions[] = \get_class($loader).': '.$e->getMessage(); - } - } - - throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); - } - - public function isFresh($name, $time) - { - $exceptions = []; - foreach ($this->loaders as $loader) { - if ($loader instanceof ExistsLoaderInterface && !$loader->exists($name)) { - continue; - } - - try { - return $loader->isFresh($name, $time); - } catch (LoaderError $e) { - $exceptions[] = \get_class($loader).': '.$e->getMessage(); - } - } - - throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); - } -} - -class_alias('Twig\Loader\ChainLoader', 'Twig_Loader_Chain'); diff --git a/application/third_party/Twig/Loader/ExistsLoaderInterface.php b/application/third_party/Twig/Loader/ExistsLoaderInterface.php deleted file mode 100644 index 940d87618c6..00000000000 --- a/application/third_party/Twig/Loader/ExistsLoaderInterface.php +++ /dev/null @@ -1,33 +0,0 @@ - - * - * @deprecated since 1.12 (to be removed in 3.0) - */ -interface ExistsLoaderInterface -{ - /** - * Check if we have the source code of a template, given its name. - * - * @param string $name The name of the template to check if we can load - * - * @return bool If the template source code is handled by this loader or not - */ - public function exists($name); -} - -class_alias('Twig\Loader\ExistsLoaderInterface', 'Twig_ExistsLoaderInterface'); diff --git a/application/third_party/Twig/Loader/FilesystemLoader.php b/application/third_party/Twig/Loader/FilesystemLoader.php deleted file mode 100644 index 19b43a29549..00000000000 --- a/application/third_party/Twig/Loader/FilesystemLoader.php +++ /dev/null @@ -1,323 +0,0 @@ - - */ -class FilesystemLoader implements LoaderInterface, ExistsLoaderInterface, SourceContextLoaderInterface -{ - /** Identifier of the main namespace. */ - const MAIN_NAMESPACE = '__main__'; - - protected $paths = []; - protected $cache = []; - protected $errorCache = []; - - private $rootPath; - - /** - * @param string|array $paths A path or an array of paths where to look for templates - * @param string|null $rootPath The root path common to all relative paths (null for getcwd()) - */ - public function __construct($paths = [], $rootPath = null) - { - $this->rootPath = (null === $rootPath ? getcwd() : $rootPath).\DIRECTORY_SEPARATOR; - if (false !== $realPath = realpath($rootPath)) { - $this->rootPath = $realPath.\DIRECTORY_SEPARATOR; - } - - if ($paths) { - $this->setPaths($paths); - } - } - - /** - * Returns the paths to the templates. - * - * @param string $namespace A path namespace - * - * @return array The array of paths where to look for templates - */ - public function getPaths($namespace = self::MAIN_NAMESPACE) - { - return isset($this->paths[$namespace]) ? $this->paths[$namespace] : []; - } - - /** - * Returns the path namespaces. - * - * The main namespace is always defined. - * - * @return array The array of defined namespaces - */ - public function getNamespaces() - { - return array_keys($this->paths); - } - - /** - * Sets the paths where templates are stored. - * - * @param string|array $paths A path or an array of paths where to look for templates - * @param string $namespace A path namespace - */ - public function setPaths($paths, $namespace = self::MAIN_NAMESPACE) - { - if (!\is_array($paths)) { - $paths = [$paths]; - } - - $this->paths[$namespace] = []; - foreach ($paths as $path) { - $this->addPath($path, $namespace); - } - } - - /** - * Adds a path where templates are stored. - * - * @param string $path A path where to look for templates - * @param string $namespace A path namespace - * - * @throws LoaderError - */ - public function addPath($path, $namespace = self::MAIN_NAMESPACE) - { - // invalidate the cache - $this->cache = $this->errorCache = []; - - $checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path; - if (!is_dir($checkPath)) { - throw new LoaderError(sprintf('The "%s" directory does not exist ("%s").', $path, $checkPath)); - } - - $this->paths[$namespace][] = rtrim($path, '/\\'); - } - - /** - * Prepends a path where templates are stored. - * - * @param string $path A path where to look for templates - * @param string $namespace A path namespace - * - * @throws LoaderError - */ - public function prependPath($path, $namespace = self::MAIN_NAMESPACE) - { - // invalidate the cache - $this->cache = $this->errorCache = []; - - $checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path; - if (!is_dir($checkPath)) { - throw new LoaderError(sprintf('The "%s" directory does not exist ("%s").', $path, $checkPath)); - } - - $path = rtrim($path, '/\\'); - - if (!isset($this->paths[$namespace])) { - $this->paths[$namespace][] = $path; - } else { - array_unshift($this->paths[$namespace], $path); - } - } - - public function getSource($name) - { - @trigger_error(sprintf('Calling "getSource" on "%s" is deprecated since 1.27. Use getSourceContext() instead.', \get_class($this)), E_USER_DEPRECATED); - - if (null === ($path = $this->findTemplate($name)) || false === $path) { - return ''; - } - - return file_get_contents($path); - } - - public function getSourceContext($name) - { - if (null === ($path = $this->findTemplate($name)) || false === $path) { - return new Source('', $name, ''); - } - - return new Source(file_get_contents($path), $name, $path); - } - - public function getCacheKey($name) - { - if (null === ($path = $this->findTemplate($name)) || false === $path) { - return ''; - } - $len = \strlen($this->rootPath); - if (0 === strncmp($this->rootPath, $path, $len)) { - return substr($path, $len); - } - - return $path; - } - - public function exists($name) - { - $name = $this->normalizeName($name); - - if (isset($this->cache[$name])) { - return true; - } - - try { - return null !== ($path = $this->findTemplate($name, false)) && false !== $path; - } catch (LoaderError $e) { - @trigger_error(sprintf('In %s::findTemplate(), you must accept a second argument that when set to "false" returns "false" instead of throwing an exception. Not supporting this argument is deprecated since version 1.27.', \get_class($this)), E_USER_DEPRECATED); - - return false; - } - } - - public function isFresh($name, $time) - { - // false support to be removed in 3.0 - if (null === ($path = $this->findTemplate($name)) || false === $path) { - return false; - } - - return filemtime($path) < $time; - } - - /** - * Checks if the template can be found. - * - * @param string $name The template name - * - * @return string|false|null The template name or false/null - */ - protected function findTemplate($name) - { - $throw = \func_num_args() > 1 ? func_get_arg(1) : true; - $name = $this->normalizeName($name); - - if (isset($this->cache[$name])) { - return $this->cache[$name]; - } - - if (isset($this->errorCache[$name])) { - if (!$throw) { - return false; - } - - throw new LoaderError($this->errorCache[$name]); - } - - try { - $this->validateName($name); - - list($namespace, $shortname) = $this->parseName($name); - } catch (LoaderError $e) { - if (!$throw) { - return false; - } - - throw $e; - } - - if (!isset($this->paths[$namespace])) { - $this->errorCache[$name] = sprintf('There are no registered paths for namespace "%s".', $namespace); - - if (!$throw) { - return false; - } - - throw new LoaderError($this->errorCache[$name]); - } - - foreach ($this->paths[$namespace] as $path) { - if (!$this->isAbsolutePath($path)) { - $path = $this->rootPath.$path; - } - - if (is_file($path.'/'.$shortname)) { - if (false !== $realpath = realpath($path.'/'.$shortname)) { - return $this->cache[$name] = $realpath; - } - - return $this->cache[$name] = $path.'/'.$shortname; - } - } - - $this->errorCache[$name] = sprintf('Unable to find template "%s" (looked into: %s).', $name, implode(', ', $this->paths[$namespace])); - - if (!$throw) { - return false; - } - - throw new LoaderError($this->errorCache[$name]); - } - - protected function parseName($name, $default = self::MAIN_NAMESPACE) - { - if (isset($name[0]) && '@' == $name[0]) { - if (false === $pos = strpos($name, '/')) { - throw new LoaderError(sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name)); - } - - $namespace = substr($name, 1, $pos - 1); - $shortname = substr($name, $pos + 1); - - return [$namespace, $shortname]; - } - - return [$default, $name]; - } - - protected function normalizeName($name) - { - return preg_replace('#/{2,}#', '/', str_replace('\\', '/', (string) $name)); - } - - protected function validateName($name) - { - if (false !== strpos($name, "\0")) { - throw new LoaderError('A template name cannot contain NUL bytes.'); - } - - $name = ltrim($name, '/'); - $parts = explode('/', $name); - $level = 0; - foreach ($parts as $part) { - if ('..' === $part) { - --$level; - } elseif ('.' !== $part) { - ++$level; - } - - if ($level < 0) { - throw new LoaderError(sprintf('Looks like you try to load a template outside configured directories (%s).', $name)); - } - } - } - - private function isAbsolutePath($file) - { - return strspn($file, '/\\', 0, 1) - || (\strlen($file) > 3 && ctype_alpha($file[0]) - && ':' === substr($file, 1, 1) - && strspn($file, '/\\', 2, 1) - ) - || null !== parse_url($file, PHP_URL_SCHEME) - ; - } -} - -class_alias('Twig\Loader\FilesystemLoader', 'Twig_Loader_Filesystem'); diff --git a/application/third_party/Twig/Loader/LoaderInterface.php b/application/third_party/Twig/Loader/LoaderInterface.php deleted file mode 100644 index 15be7a88cd0..00000000000 --- a/application/third_party/Twig/Loader/LoaderInterface.php +++ /dev/null @@ -1,61 +0,0 @@ - - */ -interface LoaderInterface -{ - /** - * Gets the source code of a template, given its name. - * - * @param string $name The name of the template to load - * - * @return string The template source code - * - * @throws LoaderError When $name is not found - * - * @deprecated since 1.27 (to be removed in 2.0), implement Twig\Loader\SourceContextLoaderInterface - */ - public function getSource($name); - - /** - * Gets the cache key to use for the cache for a given template name. - * - * @param string $name The name of the template to load - * - * @return string The cache key - * - * @throws LoaderError When $name is not found - */ - public function getCacheKey($name); - - /** - * Returns true if the template is still fresh. - * - * @param string $name The template name - * @param int $time Timestamp of the last modification time of the - * cached template - * - * @return bool true if the template is fresh, false otherwise - * - * @throws LoaderError When $name is not found - */ - public function isFresh($name, $time); -} - -class_alias('Twig\Loader\LoaderInterface', 'Twig_LoaderInterface'); diff --git a/application/third_party/Twig/Loader/SourceContextLoaderInterface.php b/application/third_party/Twig/Loader/SourceContextLoaderInterface.php deleted file mode 100644 index 78b1fcd40e4..00000000000 --- a/application/third_party/Twig/Loader/SourceContextLoaderInterface.php +++ /dev/null @@ -1,38 +0,0 @@ - - * - * @deprecated since 1.27 (to be removed in 3.0) - */ -interface SourceContextLoaderInterface -{ - /** - * Returns the source context for a given template logical name. - * - * @param string $name The template logical name - * - * @return Source - * - * @throws LoaderError When $name is not found - */ - public function getSourceContext($name); -} - -class_alias('Twig\Loader\SourceContextLoaderInterface', 'Twig_SourceContextLoaderInterface'); diff --git a/application/third_party/Twig/Markup.php b/application/third_party/Twig/Markup.php index 107941cdf71..69871fcbd04 100644 --- a/application/third_party/Twig/Markup.php +++ b/application/third_party/Twig/Markup.php @@ -3,20 +3,18 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2010 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - /** * Marks a content as safe. * * @author Fabien Potencier */ -class Markup implements \Countable +class Twig_Markup implements Countable { protected $content; protected $charset; @@ -34,8 +32,6 @@ public function __toString() public function count() { - return \function_exists('mb_get_info') ? mb_strlen($this->content, $this->charset) : \strlen($this->content); + return function_exists('mb_get_info') ? mb_strlen($this->content, $this->charset) : strlen($this->content); } } - -class_alias('Twig\Markup', 'Twig_Markup'); diff --git a/application/third_party/Twig/Node/AutoEscapeNode.php b/application/third_party/Twig/Node/AutoEscapeNode.php deleted file mode 100644 index a9403066aea..00000000000 --- a/application/third_party/Twig/Node/AutoEscapeNode.php +++ /dev/null @@ -1,40 +0,0 @@ - - */ -class AutoEscapeNode extends Node -{ - public function __construct($value, \Twig_NodeInterface $body, $lineno, $tag = 'autoescape') - { - parent::__construct(['body' => $body], ['value' => $value], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler->subcompile($this->getNode('body')); - } -} - -class_alias('Twig\Node\AutoEscapeNode', 'Twig_Node_AutoEscape'); diff --git a/application/third_party/Twig/Node/BlockNode.php b/application/third_party/Twig/Node/BlockNode.php deleted file mode 100644 index 1ffc8ca78a6..00000000000 --- a/application/third_party/Twig/Node/BlockNode.php +++ /dev/null @@ -1,45 +0,0 @@ - - */ -class BlockNode extends Node -{ - public function __construct($name, \Twig_NodeInterface $body, $lineno, $tag = null) - { - parent::__construct(['body' => $body], ['name' => $name], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write(sprintf("public function block_%s(\$context, array \$blocks = [])\n", $this->getAttribute('name')), "{\n") - ->indent() - ; - - $compiler - ->subcompile($this->getNode('body')) - ->outdent() - ->write("}\n\n") - ; - } -} - -class_alias('Twig\Node\BlockNode', 'Twig_Node_Block'); diff --git a/application/third_party/Twig/Node/BlockReferenceNode.php b/application/third_party/Twig/Node/BlockReferenceNode.php deleted file mode 100644 index de069093f66..00000000000 --- a/application/third_party/Twig/Node/BlockReferenceNode.php +++ /dev/null @@ -1,38 +0,0 @@ - - */ -class BlockReferenceNode extends Node implements NodeOutputInterface -{ - public function __construct($name, $lineno, $tag = null) - { - parent::__construct([], ['name' => $name], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write(sprintf("\$this->displayBlock('%s', \$context, \$blocks);\n", $this->getAttribute('name'))) - ; - } -} - -class_alias('Twig\Node\BlockReferenceNode', 'Twig_Node_BlockReference'); diff --git a/application/third_party/Twig/Node/BodyNode.php b/application/third_party/Twig/Node/BodyNode.php deleted file mode 100644 index 5290be56db6..00000000000 --- a/application/third_party/Twig/Node/BodyNode.php +++ /dev/null @@ -1,23 +0,0 @@ - - */ -class BodyNode extends Node -{ -} - -class_alias('Twig\Node\BodyNode', 'Twig_Node_Body'); diff --git a/application/third_party/Twig/Node/CheckSecurityNode.php b/application/third_party/Twig/Node/CheckSecurityNode.php deleted file mode 100644 index cf0a7a13d8a..00000000000 --- a/application/third_party/Twig/Node/CheckSecurityNode.php +++ /dev/null @@ -1,85 +0,0 @@ - - */ -class CheckSecurityNode extends Node -{ - protected $usedFilters; - protected $usedTags; - protected $usedFunctions; - - public function __construct(array $usedFilters, array $usedTags, array $usedFunctions) - { - $this->usedFilters = $usedFilters; - $this->usedTags = $usedTags; - $this->usedFunctions = $usedFunctions; - - parent::__construct(); - } - - public function compile(Compiler $compiler) - { - $tags = $filters = $functions = []; - foreach (['tags', 'filters', 'functions'] as $type) { - foreach ($this->{'used'.ucfirst($type)} as $name => $node) { - if ($node instanceof Node) { - ${$type}[$name] = $node->getTemplateLine(); - } else { - ${$type}[$node] = null; - } - } - } - - $compiler - ->write("\$this->sandbox = \$this->env->getExtension('\Twig\Extension\SandboxExtension');\n") - ->write('$tags = ')->repr(array_filter($tags))->raw(";\n") - ->write('$filters = ')->repr(array_filter($filters))->raw(";\n") - ->write('$functions = ')->repr(array_filter($functions))->raw(";\n\n") - ->write("try {\n") - ->indent() - ->write("\$this->sandbox->checkSecurity(\n") - ->indent() - ->write(!$tags ? "[],\n" : "['".implode("', '", array_keys($tags))."'],\n") - ->write(!$filters ? "[],\n" : "['".implode("', '", array_keys($filters))."'],\n") - ->write(!$functions ? "[]\n" : "['".implode("', '", array_keys($functions))."']\n") - ->outdent() - ->write(");\n") - ->outdent() - ->write("} catch (SecurityError \$e) {\n") - ->indent() - ->write("\$e->setSourceContext(\$this->getSourceContext());\n\n") - ->write("if (\$e instanceof SecurityNotAllowedTagError && isset(\$tags[\$e->getTagName()])) {\n") - ->indent() - ->write("\$e->setTemplateLine(\$tags[\$e->getTagName()]);\n") - ->outdent() - ->write("} elseif (\$e instanceof SecurityNotAllowedFilterError && isset(\$filters[\$e->getFilterName()])) {\n") - ->indent() - ->write("\$e->setTemplateLine(\$filters[\$e->getFilterName()]);\n") - ->outdent() - ->write("} elseif (\$e instanceof SecurityNotAllowedFunctionError && isset(\$functions[\$e->getFunctionName()])) {\n") - ->indent() - ->write("\$e->setTemplateLine(\$functions[\$e->getFunctionName()]);\n") - ->outdent() - ->write("}\n\n") - ->write("throw \$e;\n") - ->outdent() - ->write("}\n\n") - ; - } -} - -class_alias('Twig\Node\CheckSecurityNode', 'Twig_Node_CheckSecurity'); diff --git a/application/third_party/Twig/Node/CheckToStringNode.php b/application/third_party/Twig/Node/CheckToStringNode.php deleted file mode 100644 index 5d67467916e..00000000000 --- a/application/third_party/Twig/Node/CheckToStringNode.php +++ /dev/null @@ -1,42 +0,0 @@ - - */ -class CheckToStringNode extends AbstractExpression -{ - public function __construct(AbstractExpression $expr) - { - parent::__construct(['expr' => $expr], [], $expr->getTemplateLine(), $expr->getNodeTag()); - } - - public function compile(Compiler $compiler) - { - $compiler - ->raw('$this->sandbox->ensureToStringAllowed(') - ->subcompile($this->getNode('expr')) - ->raw(')') - ; - } -} diff --git a/application/third_party/Twig/Node/DeprecatedNode.php b/application/third_party/Twig/Node/DeprecatedNode.php deleted file mode 100644 index 62c0dd4ba51..00000000000 --- a/application/third_party/Twig/Node/DeprecatedNode.php +++ /dev/null @@ -1,55 +0,0 @@ - - */ -class DeprecatedNode extends Node -{ - public function __construct(AbstractExpression $expr, $lineno, $tag = null) - { - parent::__construct(['expr' => $expr], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler->addDebugInfo($this); - - $expr = $this->getNode('expr'); - - if ($expr instanceof ConstantExpression) { - $compiler->write('@trigger_error(') - ->subcompile($expr); - } else { - $varName = $compiler->getVarName(); - $compiler->write(sprintf('$%s = ', $varName)) - ->subcompile($expr) - ->raw(";\n") - ->write(sprintf('@trigger_error($%s', $varName)); - } - - $compiler - ->raw('.') - ->string(sprintf(' ("%s" at line %d).', $this->getTemplateName(), $this->getTemplateLine())) - ->raw(", E_USER_DEPRECATED);\n") - ; - } -} - -class_alias('Twig\Node\DeprecatedNode', 'Twig_Node_Deprecated'); diff --git a/application/third_party/Twig/Node/DoNode.php b/application/third_party/Twig/Node/DoNode.php deleted file mode 100644 index 80c4cea79ec..00000000000 --- a/application/third_party/Twig/Node/DoNode.php +++ /dev/null @@ -1,40 +0,0 @@ - - */ -class DoNode extends Node -{ - public function __construct(AbstractExpression $expr, $lineno, $tag = null) - { - parent::__construct(['expr' => $expr], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write('') - ->subcompile($this->getNode('expr')) - ->raw(";\n") - ; - } -} - -class_alias('Twig\Node\DoNode', 'Twig_Node_Do'); diff --git a/application/third_party/Twig/Node/EmbedNode.php b/application/third_party/Twig/Node/EmbedNode.php deleted file mode 100644 index 05051ecec8a..00000000000 --- a/application/third_party/Twig/Node/EmbedNode.php +++ /dev/null @@ -1,52 +0,0 @@ - - */ -class EmbedNode extends IncludeNode -{ - // we don't inject the module to avoid node visitors to traverse it twice (as it will be already visited in the main module) - public function __construct($name, $index, AbstractExpression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null) - { - parent::__construct(new ConstantExpression('not_used', $lineno), $variables, $only, $ignoreMissing, $lineno, $tag); - - $this->setAttribute('name', $name); - // to be removed in 2.0, used name instead - $this->setAttribute('filename', $name); - $this->setAttribute('index', $index); - } - - protected function addGetTemplate(Compiler $compiler) - { - $compiler - ->write('$this->loadTemplate(') - ->string($this->getAttribute('name')) - ->raw(', ') - ->repr($this->getTemplateName()) - ->raw(', ') - ->repr($this->getTemplateLine()) - ->raw(', ') - ->string($this->getAttribute('index')) - ->raw(')') - ; - } -} - -class_alias('Twig\Node\EmbedNode', 'Twig_Node_Embed'); diff --git a/application/third_party/Twig/Node/Expression/AbstractExpression.php b/application/third_party/Twig/Node/Expression/AbstractExpression.php deleted file mode 100644 index a3528924ca0..00000000000 --- a/application/third_party/Twig/Node/Expression/AbstractExpression.php +++ /dev/null @@ -1,26 +0,0 @@ - - */ -abstract class AbstractExpression extends Node -{ -} - -class_alias('Twig\Node\Expression\AbstractExpression', 'Twig_Node_Expression'); diff --git a/application/third_party/Twig/Node/Expression/ArrayExpression.php b/application/third_party/Twig/Node/Expression/ArrayExpression.php deleted file mode 100644 index cd63f934e4f..00000000000 --- a/application/third_party/Twig/Node/Expression/ArrayExpression.php +++ /dev/null @@ -1,88 +0,0 @@ -index = -1; - foreach ($this->getKeyValuePairs() as $pair) { - if ($pair['key'] instanceof ConstantExpression && ctype_digit((string) $pair['key']->getAttribute('value')) && $pair['key']->getAttribute('value') > $this->index) { - $this->index = $pair['key']->getAttribute('value'); - } - } - } - - public function getKeyValuePairs() - { - $pairs = []; - - foreach (array_chunk($this->nodes, 2) as $pair) { - $pairs[] = [ - 'key' => $pair[0], - 'value' => $pair[1], - ]; - } - - return $pairs; - } - - public function hasElement(AbstractExpression $key) - { - foreach ($this->getKeyValuePairs() as $pair) { - // we compare the string representation of the keys - // to avoid comparing the line numbers which are not relevant here. - if ((string) $key === (string) $pair['key']) { - return true; - } - } - - return false; - } - - public function addElement(AbstractExpression $value, AbstractExpression $key = null) - { - if (null === $key) { - $key = new ConstantExpression(++$this->index, $value->getTemplateLine()); - } - - array_push($this->nodes, $key, $value); - } - - public function compile(Compiler $compiler) - { - $compiler->raw('['); - $first = true; - foreach ($this->getKeyValuePairs() as $pair) { - if (!$first) { - $compiler->raw(', '); - } - $first = false; - - $compiler - ->subcompile($pair['key']) - ->raw(' => ') - ->subcompile($pair['value']) - ; - } - $compiler->raw(']'); - } -} - -class_alias('Twig\Node\Expression\ArrayExpression', 'Twig_Node_Expression_Array'); diff --git a/application/third_party/Twig/Node/Expression/ArrowFunctionExpression.php b/application/third_party/Twig/Node/Expression/ArrowFunctionExpression.php deleted file mode 100644 index 36b77da86f5..00000000000 --- a/application/third_party/Twig/Node/Expression/ArrowFunctionExpression.php +++ /dev/null @@ -1,64 +0,0 @@ - - */ -class ArrowFunctionExpression extends AbstractExpression -{ - public function __construct(AbstractExpression $expr, Node $names, $lineno, $tag = null) - { - parent::__construct(['expr' => $expr, 'names' => $names], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->raw('function (') - ; - foreach ($this->getNode('names') as $i => $name) { - if ($i) { - $compiler->raw(', '); - } - - $compiler - ->raw('$__') - ->raw($name->getAttribute('name')) - ->raw('__') - ; - } - $compiler - ->raw(') use ($context) { ') - ; - foreach ($this->getNode('names') as $name) { - $compiler - ->raw('$context["') - ->raw($name->getAttribute('name')) - ->raw('"] = $__') - ->raw($name->getAttribute('name')) - ->raw('__; ') - ; - } - $compiler - ->raw('return ') - ->subcompile($this->getNode('expr')) - ->raw('; }') - ; - } -} diff --git a/application/third_party/Twig/Node/Expression/AssignNameExpression.php b/application/third_party/Twig/Node/Expression/AssignNameExpression.php deleted file mode 100644 index 62c4ac0b48f..00000000000 --- a/application/third_party/Twig/Node/Expression/AssignNameExpression.php +++ /dev/null @@ -1,29 +0,0 @@ -raw('$context[') - ->string($this->getAttribute('name')) - ->raw(']') - ; - } -} - -class_alias('Twig\Node\Expression\AssignNameExpression', 'Twig_Node_Expression_AssignName'); diff --git a/application/third_party/Twig/Node/Expression/Binary/AbstractBinary.php b/application/third_party/Twig/Node/Expression/Binary/AbstractBinary.php deleted file mode 100644 index 0600aeedbb7..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/AbstractBinary.php +++ /dev/null @@ -1,43 +0,0 @@ - $left, 'right' => $right], [], $lineno); - } - - public function compile(Compiler $compiler) - { - $compiler - ->raw('(') - ->subcompile($this->getNode('left')) - ->raw(' ') - ; - $this->operator($compiler); - $compiler - ->raw(' ') - ->subcompile($this->getNode('right')) - ->raw(')') - ; - } - - abstract public function operator(Compiler $compiler); -} - -class_alias('Twig\Node\Expression\Binary\AbstractBinary', 'Twig_Node_Expression_Binary'); diff --git a/application/third_party/Twig/Node/Expression/Binary/AddBinary.php b/application/third_party/Twig/Node/Expression/Binary/AddBinary.php deleted file mode 100644 index f7719a19ea2..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/AddBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('+'); - } -} - -class_alias('Twig\Node\Expression\Binary\AddBinary', 'Twig_Node_Expression_Binary_Add'); diff --git a/application/third_party/Twig/Node/Expression/Binary/AndBinary.php b/application/third_party/Twig/Node/Expression/Binary/AndBinary.php deleted file mode 100644 index 484597da77d..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/AndBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('&&'); - } -} - -class_alias('Twig\Node\Expression\Binary\AndBinary', 'Twig_Node_Expression_Binary_And'); diff --git a/application/third_party/Twig/Node/Expression/Binary/BitwiseAndBinary.php b/application/third_party/Twig/Node/Expression/Binary/BitwiseAndBinary.php deleted file mode 100644 index cf286912b28..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/BitwiseAndBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('&'); - } -} - -class_alias('Twig\Node\Expression\Binary\BitwiseAndBinary', 'Twig_Node_Expression_Binary_BitwiseAnd'); diff --git a/application/third_party/Twig/Node/Expression/Binary/BitwiseOrBinary.php b/application/third_party/Twig/Node/Expression/Binary/BitwiseOrBinary.php deleted file mode 100644 index 7d5d2600799..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/BitwiseOrBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('|'); - } -} - -class_alias('Twig\Node\Expression\Binary\BitwiseOrBinary', 'Twig_Node_Expression_Binary_BitwiseOr'); diff --git a/application/third_party/Twig/Node/Expression/Binary/BitwiseXorBinary.php b/application/third_party/Twig/Node/Expression/Binary/BitwiseXorBinary.php deleted file mode 100644 index 72919871952..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/BitwiseXorBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('^'); - } -} - -class_alias('Twig\Node\Expression\Binary\BitwiseXorBinary', 'Twig_Node_Expression_Binary_BitwiseXor'); diff --git a/application/third_party/Twig/Node/Expression/Binary/ConcatBinary.php b/application/third_party/Twig/Node/Expression/Binary/ConcatBinary.php deleted file mode 100644 index f6e5938fdd1..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/ConcatBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('.'); - } -} - -class_alias('Twig\Node\Expression\Binary\ConcatBinary', 'Twig_Node_Expression_Binary_Concat'); diff --git a/application/third_party/Twig/Node/Expression/Binary/DivBinary.php b/application/third_party/Twig/Node/Expression/Binary/DivBinary.php deleted file mode 100644 index ebfcc758b65..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/DivBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('/'); - } -} - -class_alias('Twig\Node\Expression\Binary\DivBinary', 'Twig_Node_Expression_Binary_Div'); diff --git a/application/third_party/Twig/Node/Expression/Binary/EndsWithBinary.php b/application/third_party/Twig/Node/Expression/Binary/EndsWithBinary.php deleted file mode 100644 index 41a0065bbc6..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/EndsWithBinary.php +++ /dev/null @@ -1,37 +0,0 @@ -getVarName(); - $right = $compiler->getVarName(); - $compiler - ->raw(sprintf('(is_string($%s = ', $left)) - ->subcompile($this->getNode('left')) - ->raw(sprintf(') && is_string($%s = ', $right)) - ->subcompile($this->getNode('right')) - ->raw(sprintf(') && (\'\' === $%2$s || $%2$s === substr($%1$s, -strlen($%2$s))))', $left, $right)) - ; - } - - public function operator(Compiler $compiler) - { - return $compiler->raw(''); - } -} - -class_alias('Twig\Node\Expression\Binary\EndsWithBinary', 'Twig_Node_Expression_Binary_EndsWith'); diff --git a/application/third_party/Twig/Node/Expression/Binary/EqualBinary.php b/application/third_party/Twig/Node/Expression/Binary/EqualBinary.php deleted file mode 100644 index 84904c364ae..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/EqualBinary.php +++ /dev/null @@ -1,24 +0,0 @@ -raw('=='); - } -} - -class_alias('Twig\Node\Expression\Binary\EqualBinary', 'Twig_Node_Expression_Binary_Equal'); diff --git a/application/third_party/Twig/Node/Expression/Binary/FloorDivBinary.php b/application/third_party/Twig/Node/Expression/Binary/FloorDivBinary.php deleted file mode 100644 index 4dd5e3d32b7..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/FloorDivBinary.php +++ /dev/null @@ -1,31 +0,0 @@ -raw('(int) floor('); - parent::compile($compiler); - $compiler->raw(')'); - } - - public function operator(Compiler $compiler) - { - return $compiler->raw('/'); - } -} - -class_alias('Twig\Node\Expression\Binary\FloorDivBinary', 'Twig_Node_Expression_Binary_FloorDiv'); diff --git a/application/third_party/Twig/Node/Expression/Binary/GreaterBinary.php b/application/third_party/Twig/Node/Expression/Binary/GreaterBinary.php deleted file mode 100644 index be73001e5b9..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/GreaterBinary.php +++ /dev/null @@ -1,24 +0,0 @@ -raw('>'); - } -} - -class_alias('Twig\Node\Expression\Binary\GreaterBinary', 'Twig_Node_Expression_Binary_Greater'); diff --git a/application/third_party/Twig/Node/Expression/Binary/GreaterEqualBinary.php b/application/third_party/Twig/Node/Expression/Binary/GreaterEqualBinary.php deleted file mode 100644 index 5c2ae72ee23..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/GreaterEqualBinary.php +++ /dev/null @@ -1,24 +0,0 @@ -raw('>='); - } -} - -class_alias('Twig\Node\Expression\Binary\GreaterEqualBinary', 'Twig_Node_Expression_Binary_GreaterEqual'); diff --git a/application/third_party/Twig/Node/Expression/Binary/InBinary.php b/application/third_party/Twig/Node/Expression/Binary/InBinary.php deleted file mode 100644 index f00b23060f8..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/InBinary.php +++ /dev/null @@ -1,35 +0,0 @@ -raw('twig_in_filter(') - ->subcompile($this->getNode('left')) - ->raw(', ') - ->subcompile($this->getNode('right')) - ->raw(')') - ; - } - - public function operator(Compiler $compiler) - { - return $compiler->raw('in'); - } -} - -class_alias('Twig\Node\Expression\Binary\InBinary', 'Twig_Node_Expression_Binary_In'); diff --git a/application/third_party/Twig/Node/Expression/Binary/LessBinary.php b/application/third_party/Twig/Node/Expression/Binary/LessBinary.php deleted file mode 100644 index 2b202daa728..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/LessBinary.php +++ /dev/null @@ -1,24 +0,0 @@ -raw('<'); - } -} - -class_alias('Twig\Node\Expression\Binary\LessBinary', 'Twig_Node_Expression_Binary_Less'); diff --git a/application/third_party/Twig/Node/Expression/Binary/LessEqualBinary.php b/application/third_party/Twig/Node/Expression/Binary/LessEqualBinary.php deleted file mode 100644 index 4fffafea6dc..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/LessEqualBinary.php +++ /dev/null @@ -1,24 +0,0 @@ -raw('<='); - } -} - -class_alias('Twig\Node\Expression\Binary\LessEqualBinary', 'Twig_Node_Expression_Binary_LessEqual'); diff --git a/application/third_party/Twig/Node/Expression/Binary/MatchesBinary.php b/application/third_party/Twig/Node/Expression/Binary/MatchesBinary.php deleted file mode 100644 index ae810b2664a..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/MatchesBinary.php +++ /dev/null @@ -1,35 +0,0 @@ -raw('preg_match(') - ->subcompile($this->getNode('right')) - ->raw(', ') - ->subcompile($this->getNode('left')) - ->raw(')') - ; - } - - public function operator(Compiler $compiler) - { - return $compiler->raw(''); - } -} - -class_alias('Twig\Node\Expression\Binary\MatchesBinary', 'Twig_Node_Expression_Binary_Matches'); diff --git a/application/third_party/Twig/Node/Expression/Binary/ModBinary.php b/application/third_party/Twig/Node/Expression/Binary/ModBinary.php deleted file mode 100644 index e6a2b360346..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/ModBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('%'); - } -} - -class_alias('Twig\Node\Expression\Binary\ModBinary', 'Twig_Node_Expression_Binary_Mod'); diff --git a/application/third_party/Twig/Node/Expression/Binary/MulBinary.php b/application/third_party/Twig/Node/Expression/Binary/MulBinary.php deleted file mode 100644 index cd65f5dff2d..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/MulBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('*'); - } -} - -class_alias('Twig\Node\Expression\Binary\MulBinary', 'Twig_Node_Expression_Binary_Mul'); diff --git a/application/third_party/Twig/Node/Expression/Binary/NotEqualBinary.php b/application/third_party/Twig/Node/Expression/Binary/NotEqualBinary.php deleted file mode 100644 index df5c6a23884..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/NotEqualBinary.php +++ /dev/null @@ -1,24 +0,0 @@ -raw('!='); - } -} - -class_alias('Twig\Node\Expression\Binary\NotEqualBinary', 'Twig_Node_Expression_Binary_NotEqual'); diff --git a/application/third_party/Twig/Node/Expression/Binary/NotInBinary.php b/application/third_party/Twig/Node/Expression/Binary/NotInBinary.php deleted file mode 100644 index ed2034e35ad..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/NotInBinary.php +++ /dev/null @@ -1,35 +0,0 @@ -raw('!twig_in_filter(') - ->subcompile($this->getNode('left')) - ->raw(', ') - ->subcompile($this->getNode('right')) - ->raw(')') - ; - } - - public function operator(Compiler $compiler) - { - return $compiler->raw('not in'); - } -} - -class_alias('Twig\Node\Expression\Binary\NotInBinary', 'Twig_Node_Expression_Binary_NotIn'); diff --git a/application/third_party/Twig/Node/Expression/Binary/OrBinary.php b/application/third_party/Twig/Node/Expression/Binary/OrBinary.php deleted file mode 100644 index 8f9da43105c..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/OrBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('||'); - } -} - -class_alias('Twig\Node\Expression\Binary\OrBinary', 'Twig_Node_Expression_Binary_Or'); diff --git a/application/third_party/Twig/Node/Expression/Binary/PowerBinary.php b/application/third_party/Twig/Node/Expression/Binary/PowerBinary.php deleted file mode 100644 index 10a8d94cfe8..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/PowerBinary.php +++ /dev/null @@ -1,39 +0,0 @@ -= 50600) { - return parent::compile($compiler); - } - - $compiler - ->raw('pow(') - ->subcompile($this->getNode('left')) - ->raw(', ') - ->subcompile($this->getNode('right')) - ->raw(')') - ; - } - - public function operator(Compiler $compiler) - { - return $compiler->raw('**'); - } -} - -class_alias('Twig\Node\Expression\Binary\PowerBinary', 'Twig_Node_Expression_Binary_Power'); diff --git a/application/third_party/Twig/Node/Expression/Binary/RangeBinary.php b/application/third_party/Twig/Node/Expression/Binary/RangeBinary.php deleted file mode 100644 index e9c0cdf5e41..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/RangeBinary.php +++ /dev/null @@ -1,35 +0,0 @@ -raw('range(') - ->subcompile($this->getNode('left')) - ->raw(', ') - ->subcompile($this->getNode('right')) - ->raw(')') - ; - } - - public function operator(Compiler $compiler) - { - return $compiler->raw('..'); - } -} - -class_alias('Twig\Node\Expression\Binary\RangeBinary', 'Twig_Node_Expression_Binary_Range'); diff --git a/application/third_party/Twig/Node/Expression/Binary/StartsWithBinary.php b/application/third_party/Twig/Node/Expression/Binary/StartsWithBinary.php deleted file mode 100644 index 1fe59fb4173..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/StartsWithBinary.php +++ /dev/null @@ -1,37 +0,0 @@ -getVarName(); - $right = $compiler->getVarName(); - $compiler - ->raw(sprintf('(is_string($%s = ', $left)) - ->subcompile($this->getNode('left')) - ->raw(sprintf(') && is_string($%s = ', $right)) - ->subcompile($this->getNode('right')) - ->raw(sprintf(') && (\'\' === $%2$s || 0 === strpos($%1$s, $%2$s)))', $left, $right)) - ; - } - - public function operator(Compiler $compiler) - { - return $compiler->raw(''); - } -} - -class_alias('Twig\Node\Expression\Binary\StartsWithBinary', 'Twig_Node_Expression_Binary_StartsWith'); diff --git a/application/third_party/Twig/Node/Expression/Binary/SubBinary.php b/application/third_party/Twig/Node/Expression/Binary/SubBinary.php deleted file mode 100644 index 25469750aa0..00000000000 --- a/application/third_party/Twig/Node/Expression/Binary/SubBinary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('-'); - } -} - -class_alias('Twig\Node\Expression\Binary\SubBinary', 'Twig_Node_Expression_Binary_Sub'); diff --git a/application/third_party/Twig/Node/Expression/BlockReferenceExpression.php b/application/third_party/Twig/Node/Expression/BlockReferenceExpression.php deleted file mode 100644 index 0a56849c7aa..00000000000 --- a/application/third_party/Twig/Node/Expression/BlockReferenceExpression.php +++ /dev/null @@ -1,98 +0,0 @@ - - */ -class BlockReferenceExpression extends AbstractExpression -{ - /** - * @param Node|null $template - */ - public function __construct(\Twig_NodeInterface $name, $template = null, $lineno, $tag = null) - { - if (\is_bool($template)) { - @trigger_error(sprintf('The %s method "$asString" argument is deprecated since version 1.28 and will be removed in 2.0.', __METHOD__), E_USER_DEPRECATED); - - $template = null; - } - - $nodes = ['name' => $name]; - if (null !== $template) { - $nodes['template'] = $template; - } - - parent::__construct($nodes, ['is_defined_test' => false, 'output' => false], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - if ($this->getAttribute('is_defined_test')) { - $this->compileTemplateCall($compiler, 'hasBlock'); - } else { - if ($this->getAttribute('output')) { - $compiler->addDebugInfo($this); - - $this - ->compileTemplateCall($compiler, 'displayBlock') - ->raw(";\n"); - } else { - $this->compileTemplateCall($compiler, 'renderBlock'); - } - } - } - - private function compileTemplateCall(Compiler $compiler, $method) - { - if (!$this->hasNode('template')) { - $compiler->write('$this'); - } else { - $compiler - ->write('$this->loadTemplate(') - ->subcompile($this->getNode('template')) - ->raw(', ') - ->repr($this->getTemplateName()) - ->raw(', ') - ->repr($this->getTemplateLine()) - ->raw(')') - ; - } - - $compiler->raw(sprintf('->%s', $method)); - $this->compileBlockArguments($compiler); - - return $compiler; - } - - private function compileBlockArguments(Compiler $compiler) - { - $compiler - ->raw('(') - ->subcompile($this->getNode('name')) - ->raw(', $context'); - - if (!$this->hasNode('template')) { - $compiler->raw(', $blocks'); - } - - return $compiler->raw(')'); - } -} - -class_alias('Twig\Node\Expression\BlockReferenceExpression', 'Twig_Node_Expression_BlockReference'); diff --git a/application/third_party/Twig/Node/Expression/CallExpression.php b/application/third_party/Twig/Node/Expression/CallExpression.php deleted file mode 100644 index d202a739532..00000000000 --- a/application/third_party/Twig/Node/Expression/CallExpression.php +++ /dev/null @@ -1,305 +0,0 @@ -hasAttribute('callable') && $callable = $this->getAttribute('callable')) { - if (\is_string($callable) && false === strpos($callable, '::')) { - $compiler->raw($callable); - } else { - list($r, $callable) = $this->reflectCallable($callable); - if ($r instanceof \ReflectionMethod && \is_string($callable[0])) { - if ($r->isStatic()) { - $compiler->raw(sprintf('%s::%s', $callable[0], $callable[1])); - } else { - $compiler->raw(sprintf('$this->env->getRuntime(\'%s\')->%s', $callable[0], $callable[1])); - } - } elseif ($r instanceof \ReflectionMethod && $callable[0] instanceof ExtensionInterface) { - $compiler->raw(sprintf('$this->env->getExtension(\'%s\')->%s', \get_class($callable[0]), $callable[1])); - } else { - $type = ucfirst($this->getAttribute('type')); - $compiler->raw(sprintf('call_user_func_array($this->env->get%s(\'%s\')->getCallable(), ', $type, $this->getAttribute('name'))); - $closingParenthesis = true; - $isArray = true; - } - } - } else { - $compiler->raw($this->getAttribute('thing')->compile()); - } - - $this->compileArguments($compiler, $isArray); - - if ($closingParenthesis) { - $compiler->raw(')'); - } - } - - protected function compileArguments(Compiler $compiler, $isArray = false) - { - $compiler->raw($isArray ? '[' : '('); - - $first = true; - - if ($this->hasAttribute('needs_environment') && $this->getAttribute('needs_environment')) { - $compiler->raw('$this->env'); - $first = false; - } - - if ($this->hasAttribute('needs_context') && $this->getAttribute('needs_context')) { - if (!$first) { - $compiler->raw(', '); - } - $compiler->raw('$context'); - $first = false; - } - - if ($this->hasAttribute('arguments')) { - foreach ($this->getAttribute('arguments') as $argument) { - if (!$first) { - $compiler->raw(', '); - } - $compiler->string($argument); - $first = false; - } - } - - if ($this->hasNode('node')) { - if (!$first) { - $compiler->raw(', '); - } - $compiler->subcompile($this->getNode('node')); - $first = false; - } - - if ($this->hasNode('arguments')) { - $callable = $this->hasAttribute('callable') ? $this->getAttribute('callable') : null; - - $arguments = $this->getArguments($callable, $this->getNode('arguments')); - - foreach ($arguments as $node) { - if (!$first) { - $compiler->raw(', '); - } - $compiler->subcompile($node); - $first = false; - } - } - - $compiler->raw($isArray ? ']' : ')'); - } - - protected function getArguments($callable, $arguments) - { - $callType = $this->getAttribute('type'); - $callName = $this->getAttribute('name'); - - $parameters = []; - $named = false; - foreach ($arguments as $name => $node) { - if (!\is_int($name)) { - $named = true; - $name = $this->normalizeName($name); - } elseif ($named) { - throw new SyntaxError(sprintf('Positional arguments cannot be used after named arguments for %s "%s".', $callType, $callName), $this->getTemplateLine(), $this->getSourceContext()); - } - - $parameters[$name] = $node; - } - - $isVariadic = $this->hasAttribute('is_variadic') && $this->getAttribute('is_variadic'); - if (!$named && !$isVariadic) { - return $parameters; - } - - if (!$callable) { - if ($named) { - $message = sprintf('Named arguments are not supported for %s "%s".', $callType, $callName); - } else { - $message = sprintf('Arbitrary positional arguments are not supported for %s "%s".', $callType, $callName); - } - - throw new \LogicException($message); - } - - $callableParameters = $this->getCallableParameters($callable, $isVariadic); - $arguments = []; - $names = []; - $missingArguments = []; - $optionalArguments = []; - $pos = 0; - foreach ($callableParameters as $callableParameter) { - $names[] = $name = $this->normalizeName($callableParameter->name); - - if (\array_key_exists($name, $parameters)) { - if (\array_key_exists($pos, $parameters)) { - throw new SyntaxError(sprintf('Argument "%s" is defined twice for %s "%s".', $name, $callType, $callName), $this->getTemplateLine(), $this->getSourceContext()); - } - - if (\count($missingArguments)) { - throw new SyntaxError(sprintf( - 'Argument "%s" could not be assigned for %s "%s(%s)" because it is mapped to an internal PHP function which cannot determine default value for optional argument%s "%s".', - $name, $callType, $callName, implode(', ', $names), \count($missingArguments) > 1 ? 's' : '', implode('", "', $missingArguments) - ), $this->getTemplateLine(), $this->getSourceContext()); - } - - $arguments = array_merge($arguments, $optionalArguments); - $arguments[] = $parameters[$name]; - unset($parameters[$name]); - $optionalArguments = []; - } elseif (\array_key_exists($pos, $parameters)) { - $arguments = array_merge($arguments, $optionalArguments); - $arguments[] = $parameters[$pos]; - unset($parameters[$pos]); - $optionalArguments = []; - ++$pos; - } elseif ($callableParameter->isDefaultValueAvailable()) { - $optionalArguments[] = new ConstantExpression($callableParameter->getDefaultValue(), -1); - } elseif ($callableParameter->isOptional()) { - if (empty($parameters)) { - break; - } else { - $missingArguments[] = $name; - } - } else { - throw new SyntaxError(sprintf('Value for argument "%s" is required for %s "%s".', $name, $callType, $callName), $this->getTemplateLine(), $this->getSourceContext()); - } - } - - if ($isVariadic) { - $arbitraryArguments = new ArrayExpression([], -1); - foreach ($parameters as $key => $value) { - if (\is_int($key)) { - $arbitraryArguments->addElement($value); - } else { - $arbitraryArguments->addElement($value, new ConstantExpression($key, -1)); - } - unset($parameters[$key]); - } - - if ($arbitraryArguments->count()) { - $arguments = array_merge($arguments, $optionalArguments); - $arguments[] = $arbitraryArguments; - } - } - - if (!empty($parameters)) { - $unknownParameter = null; - foreach ($parameters as $parameter) { - if ($parameter instanceof Node) { - $unknownParameter = $parameter; - break; - } - } - - throw new SyntaxError( - sprintf( - 'Unknown argument%s "%s" for %s "%s(%s)".', - \count($parameters) > 1 ? 's' : '', implode('", "', array_keys($parameters)), $callType, $callName, implode(', ', $names) - ), - $unknownParameter ? $unknownParameter->getTemplateLine() : $this->getTemplateLine(), - $unknownParameter ? $unknownParameter->getSourceContext() : $this->getSourceContext() - ); - } - - return $arguments; - } - - protected function normalizeName($name) - { - return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], $name)); - } - - private function getCallableParameters($callable, $isVariadic) - { - list($r) = $this->reflectCallable($callable); - if (null === $r) { - return []; - } - - $parameters = $r->getParameters(); - if ($this->hasNode('node')) { - array_shift($parameters); - } - if ($this->hasAttribute('needs_environment') && $this->getAttribute('needs_environment')) { - array_shift($parameters); - } - if ($this->hasAttribute('needs_context') && $this->getAttribute('needs_context')) { - array_shift($parameters); - } - if ($this->hasAttribute('arguments') && null !== $this->getAttribute('arguments')) { - foreach ($this->getAttribute('arguments') as $argument) { - array_shift($parameters); - } - } - if ($isVariadic) { - $argument = end($parameters); - if ($argument && $argument->isArray() && $argument->isDefaultValueAvailable() && [] === $argument->getDefaultValue()) { - array_pop($parameters); - } else { - $callableName = $r->name; - if ($r instanceof \ReflectionMethod) { - $callableName = $r->getDeclaringClass()->name.'::'.$callableName; - } - - throw new \LogicException(sprintf('The last parameter of "%s" for %s "%s" must be an array with default value, eg. "array $arg = []".', $callableName, $this->getAttribute('type'), $this->getAttribute('name'))); - } - } - - return $parameters; - } - - private function reflectCallable($callable) - { - if (null !== $this->reflector) { - return $this->reflector; - } - - if (\is_array($callable)) { - if (!method_exists($callable[0], $callable[1])) { - // __call() - return [null, []]; - } - $r = new \ReflectionMethod($callable[0], $callable[1]); - } elseif (\is_object($callable) && !$callable instanceof \Closure) { - $r = new \ReflectionObject($callable); - $r = $r->getMethod('__invoke'); - $callable = [$callable, '__invoke']; - } elseif (\is_string($callable) && false !== $pos = strpos($callable, '::')) { - $class = substr($callable, 0, $pos); - $method = substr($callable, $pos + 2); - if (!method_exists($class, $method)) { - // __staticCall() - return [null, []]; - } - $r = new \ReflectionMethod($callable); - $callable = [$class, $method]; - } else { - $r = new \ReflectionFunction($callable); - } - - return $this->reflector = [$r, $callable]; - } -} - -class_alias('Twig\Node\Expression\CallExpression', 'Twig_Node_Expression_Call'); diff --git a/application/third_party/Twig/Node/Expression/ConditionalExpression.php b/application/third_party/Twig/Node/Expression/ConditionalExpression.php deleted file mode 100644 index b611218d31b..00000000000 --- a/application/third_party/Twig/Node/Expression/ConditionalExpression.php +++ /dev/null @@ -1,38 +0,0 @@ - $expr1, 'expr2' => $expr2, 'expr3' => $expr3], [], $lineno); - } - - public function compile(Compiler $compiler) - { - $compiler - ->raw('((') - ->subcompile($this->getNode('expr1')) - ->raw(') ? (') - ->subcompile($this->getNode('expr2')) - ->raw(') : (') - ->subcompile($this->getNode('expr3')) - ->raw('))') - ; - } -} - -class_alias('Twig\Node\Expression\ConditionalExpression', 'Twig_Node_Expression_Conditional'); diff --git a/application/third_party/Twig/Node/Expression/ConstantExpression.php b/application/third_party/Twig/Node/Expression/ConstantExpression.php deleted file mode 100644 index fd58264dca1..00000000000 --- a/application/third_party/Twig/Node/Expression/ConstantExpression.php +++ /dev/null @@ -1,30 +0,0 @@ - $value], $lineno); - } - - public function compile(Compiler $compiler) - { - $compiler->repr($this->getAttribute('value')); - } -} - -class_alias('Twig\Node\Expression\ConstantExpression', 'Twig_Node_Expression_Constant'); diff --git a/application/third_party/Twig/Node/Expression/Filter/DefaultFilter.php b/application/third_party/Twig/Node/Expression/Filter/DefaultFilter.php deleted file mode 100644 index 7c5e2d20aa4..00000000000 --- a/application/third_party/Twig/Node/Expression/Filter/DefaultFilter.php +++ /dev/null @@ -1,54 +0,0 @@ - - */ -class DefaultFilter extends FilterExpression -{ - public function __construct(\Twig_NodeInterface $node, ConstantExpression $filterName, \Twig_NodeInterface $arguments, $lineno, $tag = null) - { - $default = new FilterExpression($node, new ConstantExpression('default', $node->getTemplateLine()), $arguments, $node->getTemplateLine()); - - if ('default' === $filterName->getAttribute('value') && ($node instanceof NameExpression || $node instanceof GetAttrExpression)) { - $test = new DefinedTest(clone $node, 'defined', new Node(), $node->getTemplateLine()); - $false = \count($arguments) ? $arguments->getNode(0) : new ConstantExpression('', $node->getTemplateLine()); - - $node = new ConditionalExpression($test, $default, $false, $node->getTemplateLine()); - } else { - $node = $default; - } - - parent::__construct($node, $filterName, $arguments, $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler->subcompile($this->getNode('node')); - } -} - -class_alias('Twig\Node\Expression\Filter\DefaultFilter', 'Twig_Node_Expression_Filter_Default'); diff --git a/application/third_party/Twig/Node/Expression/FilterExpression.php b/application/third_party/Twig/Node/Expression/FilterExpression.php deleted file mode 100644 index 6131c2fd403..00000000000 --- a/application/third_party/Twig/Node/Expression/FilterExpression.php +++ /dev/null @@ -1,47 +0,0 @@ - $node, 'filter' => $filterName, 'arguments' => $arguments], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $name = $this->getNode('filter')->getAttribute('value'); - $filter = $compiler->getEnvironment()->getFilter($name); - - $this->setAttribute('name', $name); - $this->setAttribute('type', 'filter'); - $this->setAttribute('thing', $filter); - $this->setAttribute('needs_environment', $filter->needsEnvironment()); - $this->setAttribute('needs_context', $filter->needsContext()); - $this->setAttribute('arguments', $filter->getArguments()); - if ($filter instanceof \Twig_FilterCallableInterface || $filter instanceof TwigFilter) { - $this->setAttribute('callable', $filter->getCallable()); - } - if ($filter instanceof TwigFilter) { - $this->setAttribute('is_variadic', $filter->isVariadic()); - } - - $this->compileCallable($compiler); - } -} - -class_alias('Twig\Node\Expression\FilterExpression', 'Twig_Node_Expression_Filter'); diff --git a/application/third_party/Twig/Node/Expression/FunctionExpression.php b/application/third_party/Twig/Node/Expression/FunctionExpression.php deleted file mode 100644 index cf2c72b635f..00000000000 --- a/application/third_party/Twig/Node/Expression/FunctionExpression.php +++ /dev/null @@ -1,51 +0,0 @@ - $arguments], ['name' => $name, 'is_defined_test' => false], $lineno); - } - - public function compile(Compiler $compiler) - { - $name = $this->getAttribute('name'); - $function = $compiler->getEnvironment()->getFunction($name); - - $this->setAttribute('name', $name); - $this->setAttribute('type', 'function'); - $this->setAttribute('thing', $function); - $this->setAttribute('needs_environment', $function->needsEnvironment()); - $this->setAttribute('needs_context', $function->needsContext()); - $this->setAttribute('arguments', $function->getArguments()); - if ($function instanceof \Twig_FunctionCallableInterface || $function instanceof TwigFunction) { - $callable = $function->getCallable(); - if ('constant' === $name && $this->getAttribute('is_defined_test')) { - $callable = 'twig_constant_is_defined'; - } - - $this->setAttribute('callable', $callable); - } - if ($function instanceof TwigFunction) { - $this->setAttribute('is_variadic', $function->isVariadic()); - } - - $this->compileCallable($compiler); - } -} - -class_alias('Twig\Node\Expression\FunctionExpression', 'Twig_Node_Expression_Function'); diff --git a/application/third_party/Twig/Node/Expression/GetAttrExpression.php b/application/third_party/Twig/Node/Expression/GetAttrExpression.php deleted file mode 100644 index b790bf7af7a..00000000000 --- a/application/third_party/Twig/Node/Expression/GetAttrExpression.php +++ /dev/null @@ -1,80 +0,0 @@ - $node, 'attribute' => $attribute]; - if (null !== $arguments) { - $nodes['arguments'] = $arguments; - } - - parent::__construct($nodes, ['type' => $type, 'is_defined_test' => false, 'ignore_strict_check' => false, 'disable_c_ext' => false], $lineno); - } - - public function compile(Compiler $compiler) - { - if ($this->getAttribute('disable_c_ext')) { - @trigger_error(sprintf('Using the "disable_c_ext" attribute on %s is deprecated since version 1.30 and will be removed in 2.0.', __CLASS__), E_USER_DEPRECATED); - } - - if (\function_exists('twig_template_get_attributes') && !$this->getAttribute('disable_c_ext')) { - $compiler->raw('twig_template_get_attributes($this, '); - } else { - $compiler->raw('$this->getAttribute('); - } - - if ($this->getAttribute('ignore_strict_check')) { - $this->getNode('node')->setAttribute('ignore_strict_check', true); - } - - $compiler->subcompile($this->getNode('node')); - - $compiler->raw(', ')->subcompile($this->getNode('attribute')); - - // only generate optional arguments when needed (to make generated code more readable) - $needFourth = $this->getAttribute('ignore_strict_check'); - $needThird = $needFourth || $this->getAttribute('is_defined_test'); - $needSecond = $needThird || Template::ANY_CALL !== $this->getAttribute('type'); - $needFirst = $needSecond || $this->hasNode('arguments'); - - if ($needFirst) { - if ($this->hasNode('arguments')) { - $compiler->raw(', ')->subcompile($this->getNode('arguments')); - } else { - $compiler->raw(', []'); - } - } - - if ($needSecond) { - $compiler->raw(', ')->repr($this->getAttribute('type')); - } - - if ($needThird) { - $compiler->raw(', ')->repr($this->getAttribute('is_defined_test')); - } - - if ($needFourth) { - $compiler->raw(', ')->repr($this->getAttribute('ignore_strict_check')); - } - - $compiler->raw(')'); - } -} - -class_alias('Twig\Node\Expression\GetAttrExpression', 'Twig_Node_Expression_GetAttr'); diff --git a/application/third_party/Twig/Node/Expression/InlinePrint.php b/application/third_party/Twig/Node/Expression/InlinePrint.php deleted file mode 100644 index 469e73675a4..00000000000 --- a/application/third_party/Twig/Node/Expression/InlinePrint.php +++ /dev/null @@ -1,35 +0,0 @@ - $node], [], $lineno); - } - - public function compile(Compiler $compiler) - { - $compiler - ->raw('print (') - ->subcompile($this->getNode('node')) - ->raw(')') - ; - } -} diff --git a/application/third_party/Twig/Node/Expression/MethodCallExpression.php b/application/third_party/Twig/Node/Expression/MethodCallExpression.php deleted file mode 100644 index f6311249dee..00000000000 --- a/application/third_party/Twig/Node/Expression/MethodCallExpression.php +++ /dev/null @@ -1,48 +0,0 @@ - $node, 'arguments' => $arguments], ['method' => $method, 'safe' => false], $lineno); - - if ($node instanceof NameExpression) { - $node->setAttribute('always_defined', true); - } - } - - public function compile(Compiler $compiler) - { - $compiler - ->subcompile($this->getNode('node')) - ->raw('->') - ->raw($this->getAttribute('method')) - ->raw('(') - ; - $first = true; - foreach ($this->getNode('arguments')->getKeyValuePairs() as $pair) { - if (!$first) { - $compiler->raw(', '); - } - $first = false; - - $compiler->subcompile($pair['value']); - } - $compiler->raw(')'); - } -} - -class_alias('Twig\Node\Expression\MethodCallExpression', 'Twig_Node_Expression_MethodCall'); diff --git a/application/third_party/Twig/Node/Expression/NameExpression.php b/application/third_party/Twig/Node/Expression/NameExpression.php deleted file mode 100644 index d3f7d107fb0..00000000000 --- a/application/third_party/Twig/Node/Expression/NameExpression.php +++ /dev/null @@ -1,119 +0,0 @@ - '$this', - '_context' => '$context', - '_charset' => '$this->env->getCharset()', - ]; - - public function __construct($name, $lineno) - { - parent::__construct([], ['name' => $name, 'is_defined_test' => false, 'ignore_strict_check' => false, 'always_defined' => false], $lineno); - } - - public function compile(Compiler $compiler) - { - $name = $this->getAttribute('name'); - - $compiler->addDebugInfo($this); - - if ($this->getAttribute('is_defined_test')) { - if ($this->isSpecial()) { - $compiler->repr(true); - } elseif (\PHP_VERSION_ID >= 700400) { - $compiler - ->raw('array_key_exists(') - ->string($name) - ->raw(', $context)') - ; - } else { - $compiler - ->raw('(isset($context[') - ->string($name) - ->raw(']) || array_key_exists(') - ->string($name) - ->raw(', $context))') - ; - } - } elseif ($this->isSpecial()) { - $compiler->raw($this->specialVars[$name]); - } elseif ($this->getAttribute('always_defined')) { - $compiler - ->raw('$context[') - ->string($name) - ->raw(']') - ; - } else { - if (\PHP_VERSION_ID >= 70000) { - // use PHP 7 null coalescing operator - $compiler - ->raw('($context[') - ->string($name) - ->raw('] ?? ') - ; - - if ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables()) { - $compiler->raw('null)'); - } else { - $compiler->raw('$this->getContext($context, ')->string($name)->raw('))'); - } - } elseif (\PHP_VERSION_ID >= 50400) { - // PHP 5.4 ternary operator performance was optimized - $compiler - ->raw('(isset($context[') - ->string($name) - ->raw(']) ? $context[') - ->string($name) - ->raw('] : ') - ; - - if ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables()) { - $compiler->raw('null)'); - } else { - $compiler->raw('$this->getContext($context, ')->string($name)->raw('))'); - } - } else { - $compiler - ->raw('$this->getContext($context, ') - ->string($name) - ; - - if ($this->getAttribute('ignore_strict_check')) { - $compiler->raw(', true'); - } - - $compiler - ->raw(')') - ; - } - } - } - - public function isSpecial() - { - return isset($this->specialVars[$this->getAttribute('name')]); - } - - public function isSimple() - { - return !$this->isSpecial() && !$this->getAttribute('is_defined_test'); - } -} - -class_alias('Twig\Node\Expression\NameExpression', 'Twig_Node_Expression_Name'); diff --git a/application/third_party/Twig/Node/Expression/NullCoalesceExpression.php b/application/third_party/Twig/Node/Expression/NullCoalesceExpression.php deleted file mode 100644 index 917d31a3b27..00000000000 --- a/application/third_party/Twig/Node/Expression/NullCoalesceExpression.php +++ /dev/null @@ -1,62 +0,0 @@ -getTemplateLine()); - // for "block()", we don't need the null test as the return value is always a string - if (!$left instanceof BlockReferenceExpression) { - $test = new AndBinary( - $test, - new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), - $left->getTemplateLine() - ); - } - - parent::__construct($test, $left, $right, $lineno); - } - - public function compile(Compiler $compiler) - { - /* - * This optimizes only one case. PHP 7 also supports more complex expressions - * that can return null. So, for instance, if log is defined, log("foo") ?? "..." works, - * but log($a["foo"]) ?? "..." does not if $a["foo"] is not defined. More advanced - * cases might be implemented as an optimizer node visitor, but has not been done - * as benefits are probably not worth the added complexity. - */ - if (\PHP_VERSION_ID >= 70000 && $this->getNode('expr2') instanceof NameExpression) { - $this->getNode('expr2')->setAttribute('always_defined', true); - $compiler - ->raw('((') - ->subcompile($this->getNode('expr2')) - ->raw(') ?? (') - ->subcompile($this->getNode('expr3')) - ->raw('))') - ; - } else { - parent::compile($compiler); - } - } -} - -class_alias('Twig\Node\Expression\NullCoalesceExpression', 'Twig_Node_Expression_NullCoalesce'); diff --git a/application/third_party/Twig/Node/Expression/ParentExpression.php b/application/third_party/Twig/Node/Expression/ParentExpression.php deleted file mode 100644 index 12472830362..00000000000 --- a/application/third_party/Twig/Node/Expression/ParentExpression.php +++ /dev/null @@ -1,48 +0,0 @@ - - */ -class ParentExpression extends AbstractExpression -{ - public function __construct($name, $lineno, $tag = null) - { - parent::__construct([], ['output' => false, 'name' => $name], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - if ($this->getAttribute('output')) { - $compiler - ->addDebugInfo($this) - ->write('$this->displayParentBlock(') - ->string($this->getAttribute('name')) - ->raw(", \$context, \$blocks);\n") - ; - } else { - $compiler - ->raw('$this->renderParentBlock(') - ->string($this->getAttribute('name')) - ->raw(', $context, $blocks)') - ; - } - } -} - -class_alias('Twig\Node\Expression\ParentExpression', 'Twig_Node_Expression_Parent'); diff --git a/application/third_party/Twig/Node/Expression/TempNameExpression.php b/application/third_party/Twig/Node/Expression/TempNameExpression.php deleted file mode 100644 index ce0a158981e..00000000000 --- a/application/third_party/Twig/Node/Expression/TempNameExpression.php +++ /dev/null @@ -1,33 +0,0 @@ - $name], $lineno); - } - - public function compile(Compiler $compiler) - { - $compiler - ->raw('$_') - ->raw($this->getAttribute('name')) - ->raw('_') - ; - } -} - -class_alias('Twig\Node\Expression\TempNameExpression', 'Twig_Node_Expression_TempName'); diff --git a/application/third_party/Twig/Node/Expression/Test/ConstantTest.php b/application/third_party/Twig/Node/Expression/Test/ConstantTest.php deleted file mode 100644 index 78353a8b256..00000000000 --- a/application/third_party/Twig/Node/Expression/Test/ConstantTest.php +++ /dev/null @@ -1,51 +0,0 @@ - - */ -class ConstantTest extends TestExpression -{ - public function compile(Compiler $compiler) - { - $compiler - ->raw('(') - ->subcompile($this->getNode('node')) - ->raw(' === constant(') - ; - - if ($this->getNode('arguments')->hasNode(1)) { - $compiler - ->raw('get_class(') - ->subcompile($this->getNode('arguments')->getNode(1)) - ->raw(')."::".') - ; - } - - $compiler - ->subcompile($this->getNode('arguments')->getNode(0)) - ->raw('))') - ; - } -} - -class_alias('Twig\Node\Expression\Test\ConstantTest', 'Twig_Node_Expression_Test_Constant'); diff --git a/application/third_party/Twig/Node/Expression/Test/DefinedTest.php b/application/third_party/Twig/Node/Expression/Test/DefinedTest.php deleted file mode 100644 index 2222e11cfda..00000000000 --- a/application/third_party/Twig/Node/Expression/Test/DefinedTest.php +++ /dev/null @@ -1,71 +0,0 @@ - - */ -class DefinedTest extends TestExpression -{ - public function __construct(\Twig_NodeInterface $node, $name, \Twig_NodeInterface $arguments = null, $lineno) - { - if ($node instanceof NameExpression) { - $node->setAttribute('is_defined_test', true); - } elseif ($node instanceof GetAttrExpression) { - $node->setAttribute('is_defined_test', true); - $this->changeIgnoreStrictCheck($node); - } elseif ($node instanceof BlockReferenceExpression) { - $node->setAttribute('is_defined_test', true); - } elseif ($node instanceof FunctionExpression && 'constant' === $node->getAttribute('name')) { - $node->setAttribute('is_defined_test', true); - } elseif ($node instanceof ConstantExpression || $node instanceof ArrayExpression) { - $node = new ConstantExpression(true, $node->getTemplateLine()); - } else { - throw new SyntaxError('The "defined" test only works with simple variables.', $lineno); - } - - parent::__construct($node, $name, $arguments, $lineno); - } - - protected function changeIgnoreStrictCheck(GetAttrExpression $node) - { - $node->setAttribute('ignore_strict_check', true); - - if ($node->getNode('node') instanceof GetAttrExpression) { - $this->changeIgnoreStrictCheck($node->getNode('node')); - } - } - - public function compile(Compiler $compiler) - { - $compiler->subcompile($this->getNode('node')); - } -} - -class_alias('Twig\Node\Expression\Test\DefinedTest', 'Twig_Node_Expression_Test_Defined'); diff --git a/application/third_party/Twig/Node/Expression/Test/DivisiblebyTest.php b/application/third_party/Twig/Node/Expression/Test/DivisiblebyTest.php deleted file mode 100644 index 05c8ad8f7c3..00000000000 --- a/application/third_party/Twig/Node/Expression/Test/DivisiblebyTest.php +++ /dev/null @@ -1,38 +0,0 @@ - - */ -class DivisiblebyTest extends TestExpression -{ - public function compile(Compiler $compiler) - { - $compiler - ->raw('(0 == ') - ->subcompile($this->getNode('node')) - ->raw(' % ') - ->subcompile($this->getNode('arguments')->getNode(0)) - ->raw(')') - ; - } -} - -class_alias('Twig\Node\Expression\Test\DivisiblebyTest', 'Twig_Node_Expression_Test_Divisibleby'); diff --git a/application/third_party/Twig/Node/Expression/Test/EvenTest.php b/application/third_party/Twig/Node/Expression/Test/EvenTest.php deleted file mode 100644 index 3b955d26a2f..00000000000 --- a/application/third_party/Twig/Node/Expression/Test/EvenTest.php +++ /dev/null @@ -1,37 +0,0 @@ - - */ -class EvenTest extends TestExpression -{ - public function compile(Compiler $compiler) - { - $compiler - ->raw('(') - ->subcompile($this->getNode('node')) - ->raw(' % 2 == 0') - ->raw(')') - ; - } -} - -class_alias('Twig\Node\Expression\Test\EvenTest', 'Twig_Node_Expression_Test_Even'); diff --git a/application/third_party/Twig/Node/Expression/Test/NullTest.php b/application/third_party/Twig/Node/Expression/Test/NullTest.php deleted file mode 100644 index 24d399781ec..00000000000 --- a/application/third_party/Twig/Node/Expression/Test/NullTest.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class NullTest extends TestExpression -{ - public function compile(Compiler $compiler) - { - $compiler - ->raw('(null === ') - ->subcompile($this->getNode('node')) - ->raw(')') - ; - } -} - -class_alias('Twig\Node\Expression\Test\NullTest', 'Twig_Node_Expression_Test_Null'); diff --git a/application/third_party/Twig/Node/Expression/Test/OddTest.php b/application/third_party/Twig/Node/Expression/Test/OddTest.php deleted file mode 100644 index 2dc693a9ae6..00000000000 --- a/application/third_party/Twig/Node/Expression/Test/OddTest.php +++ /dev/null @@ -1,37 +0,0 @@ - - */ -class OddTest extends TestExpression -{ - public function compile(Compiler $compiler) - { - $compiler - ->raw('(') - ->subcompile($this->getNode('node')) - ->raw(' % 2 == 1') - ->raw(')') - ; - } -} - -class_alias('Twig\Node\Expression\Test\OddTest', 'Twig_Node_Expression_Test_Odd'); diff --git a/application/third_party/Twig/Node/Expression/Test/SameasTest.php b/application/third_party/Twig/Node/Expression/Test/SameasTest.php deleted file mode 100644 index 75f2b82a5bb..00000000000 --- a/application/third_party/Twig/Node/Expression/Test/SameasTest.php +++ /dev/null @@ -1,36 +0,0 @@ - - */ -class SameasTest extends TestExpression -{ - public function compile(Compiler $compiler) - { - $compiler - ->raw('(') - ->subcompile($this->getNode('node')) - ->raw(' === ') - ->subcompile($this->getNode('arguments')->getNode(0)) - ->raw(')') - ; - } -} - -class_alias('Twig\Node\Expression\Test\SameasTest', 'Twig_Node_Expression_Test_Sameas'); diff --git a/application/third_party/Twig/Node/Expression/TestExpression.php b/application/third_party/Twig/Node/Expression/TestExpression.php deleted file mode 100644 index 8fc31d3aadc..00000000000 --- a/application/third_party/Twig/Node/Expression/TestExpression.php +++ /dev/null @@ -1,51 +0,0 @@ - $node]; - if (null !== $arguments) { - $nodes['arguments'] = $arguments; - } - - parent::__construct($nodes, ['name' => $name], $lineno); - } - - public function compile(Compiler $compiler) - { - $name = $this->getAttribute('name'); - $test = $compiler->getEnvironment()->getTest($name); - - $this->setAttribute('name', $name); - $this->setAttribute('type', 'test'); - $this->setAttribute('thing', $test); - if ($test instanceof TwigTest) { - $this->setAttribute('arguments', $test->getArguments()); - } - if ($test instanceof \Twig_TestCallableInterface || $test instanceof TwigTest) { - $this->setAttribute('callable', $test->getCallable()); - } - if ($test instanceof TwigTest) { - $this->setAttribute('is_variadic', $test->isVariadic()); - } - - $this->compileCallable($compiler); - } -} - -class_alias('Twig\Node\Expression\TestExpression', 'Twig_Node_Expression_Test'); diff --git a/application/third_party/Twig/Node/Expression/Unary/AbstractUnary.php b/application/third_party/Twig/Node/Expression/Unary/AbstractUnary.php deleted file mode 100644 index 415c3d407e9..00000000000 --- a/application/third_party/Twig/Node/Expression/Unary/AbstractUnary.php +++ /dev/null @@ -1,35 +0,0 @@ - $node], [], $lineno); - } - - public function compile(Compiler $compiler) - { - $compiler->raw(' '); - $this->operator($compiler); - $compiler->subcompile($this->getNode('node')); - } - - abstract public function operator(Compiler $compiler); -} - -class_alias('Twig\Node\Expression\Unary\AbstractUnary', 'Twig_Node_Expression_Unary'); diff --git a/application/third_party/Twig/Node/Expression/Unary/NegUnary.php b/application/third_party/Twig/Node/Expression/Unary/NegUnary.php deleted file mode 100644 index dfb6f542954..00000000000 --- a/application/third_party/Twig/Node/Expression/Unary/NegUnary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('-'); - } -} - -class_alias('Twig\Node\Expression\Unary\NegUnary', 'Twig_Node_Expression_Unary_Neg'); diff --git a/application/third_party/Twig/Node/Expression/Unary/NotUnary.php b/application/third_party/Twig/Node/Expression/Unary/NotUnary.php deleted file mode 100644 index 7bdde96fffc..00000000000 --- a/application/third_party/Twig/Node/Expression/Unary/NotUnary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('!'); - } -} - -class_alias('Twig\Node\Expression\Unary\NotUnary', 'Twig_Node_Expression_Unary_Not'); diff --git a/application/third_party/Twig/Node/Expression/Unary/PosUnary.php b/application/third_party/Twig/Node/Expression/Unary/PosUnary.php deleted file mode 100644 index 52d5d0c89a7..00000000000 --- a/application/third_party/Twig/Node/Expression/Unary/PosUnary.php +++ /dev/null @@ -1,25 +0,0 @@ -raw('+'); - } -} - -class_alias('Twig\Node\Expression\Unary\PosUnary', 'Twig_Node_Expression_Unary_Pos'); diff --git a/application/third_party/Twig/Node/FlushNode.php b/application/third_party/Twig/Node/FlushNode.php deleted file mode 100644 index 6cbc489a62d..00000000000 --- a/application/third_party/Twig/Node/FlushNode.php +++ /dev/null @@ -1,37 +0,0 @@ - - */ -class FlushNode extends Node -{ - public function __construct($lineno, $tag) - { - parent::__construct([], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write("flush();\n") - ; - } -} - -class_alias('Twig\Node\FlushNode', 'Twig_Node_Flush'); diff --git a/application/third_party/Twig/Node/ForLoopNode.php b/application/third_party/Twig/Node/ForLoopNode.php deleted file mode 100644 index 3902093556b..00000000000 --- a/application/third_party/Twig/Node/ForLoopNode.php +++ /dev/null @@ -1,56 +0,0 @@ - - */ -class ForLoopNode extends Node -{ - public function __construct($lineno, $tag = null) - { - parent::__construct([], ['with_loop' => false, 'ifexpr' => false, 'else' => false], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - if ($this->getAttribute('else')) { - $compiler->write("\$context['_iterated'] = true;\n"); - } - - if ($this->getAttribute('with_loop')) { - $compiler - ->write("++\$context['loop']['index0'];\n") - ->write("++\$context['loop']['index'];\n") - ->write("\$context['loop']['first'] = false;\n") - ; - - if (!$this->getAttribute('ifexpr')) { - $compiler - ->write("if (isset(\$context['loop']['length'])) {\n") - ->indent() - ->write("--\$context['loop']['revindex0'];\n") - ->write("--\$context['loop']['revindex'];\n") - ->write("\$context['loop']['last'] = 0 === \$context['loop']['revindex0'];\n") - ->outdent() - ->write("}\n") - ; - } - } - } -} - -class_alias('Twig\Node\ForLoopNode', 'Twig_Node_ForLoop'); diff --git a/application/third_party/Twig/Node/ForNode.php b/application/third_party/Twig/Node/ForNode.php deleted file mode 100644 index 49409a39b18..00000000000 --- a/application/third_party/Twig/Node/ForNode.php +++ /dev/null @@ -1,119 +0,0 @@ - - */ -class ForNode extends Node -{ - protected $loop; - - public function __construct(AssignNameExpression $keyTarget, AssignNameExpression $valueTarget, AbstractExpression $seq, AbstractExpression $ifexpr = null, \Twig_NodeInterface $body, \Twig_NodeInterface $else = null, $lineno, $tag = null) - { - $body = new Node([$body, $this->loop = new ForLoopNode($lineno, $tag)]); - - if (null !== $ifexpr) { - $body = new IfNode(new Node([$ifexpr, $body]), null, $lineno, $tag); - } - - $nodes = ['key_target' => $keyTarget, 'value_target' => $valueTarget, 'seq' => $seq, 'body' => $body]; - if (null !== $else) { - $nodes['else'] = $else; - } - - parent::__construct($nodes, ['with_loop' => true, 'ifexpr' => null !== $ifexpr], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write("\$context['_parent'] = \$context;\n") - ->write("\$context['_seq'] = twig_ensure_traversable(") - ->subcompile($this->getNode('seq')) - ->raw(");\n") - ; - - if ($this->hasNode('else')) { - $compiler->write("\$context['_iterated'] = false;\n"); - } - - if ($this->getAttribute('with_loop')) { - $compiler - ->write("\$context['loop'] = [\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', $this->hasNode('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 ($this->hasNode('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"); - } -} - -class_alias('Twig\Node\ForNode', 'Twig_Node_For'); diff --git a/application/third_party/Twig/Node/IfNode.php b/application/third_party/Twig/Node/IfNode.php deleted file mode 100644 index 4836d91f088..00000000000 --- a/application/third_party/Twig/Node/IfNode.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class IfNode extends Node -{ - public function __construct(\Twig_NodeInterface $tests, \Twig_NodeInterface $else = null, $lineno, $tag = null) - { - $nodes = ['tests' => $tests]; - if (null !== $else) { - $nodes['else'] = $else; - } - - parent::__construct($nodes, [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler->addDebugInfo($this); - for ($i = 0, $count = \count($this->getNode('tests')); $i < $count; $i += 2) { - if ($i > 0) { - $compiler - ->outdent() - ->write('} elseif (') - ; - } else { - $compiler - ->write('if (') - ; - } - - $compiler - ->subcompile($this->getNode('tests')->getNode($i)) - ->raw(") {\n") - ->indent() - ->subcompile($this->getNode('tests')->getNode($i + 1)) - ; - } - - if ($this->hasNode('else')) { - $compiler - ->outdent() - ->write("} else {\n") - ->indent() - ->subcompile($this->getNode('else')) - ; - } - - $compiler - ->outdent() - ->write("}\n"); - } -} - -class_alias('Twig\Node\IfNode', 'Twig_Node_If'); diff --git a/application/third_party/Twig/Node/ImportNode.php b/application/third_party/Twig/Node/ImportNode.php deleted file mode 100644 index 236db8900ea..00000000000 --- a/application/third_party/Twig/Node/ImportNode.php +++ /dev/null @@ -1,57 +0,0 @@ - - */ -class ImportNode extends Node -{ - public function __construct(AbstractExpression $expr, AbstractExpression $var, $lineno, $tag = null) - { - parent::__construct(['expr' => $expr, 'var' => $var], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write('') - ->subcompile($this->getNode('var')) - ->raw(' = ') - ; - - if ($this->getNode('expr') instanceof NameExpression && '_self' === $this->getNode('expr')->getAttribute('name')) { - $compiler->raw('$this'); - } else { - $compiler - ->raw('$this->loadTemplate(') - ->subcompile($this->getNode('expr')) - ->raw(', ') - ->repr($this->getTemplateName()) - ->raw(', ') - ->repr($this->getTemplateLine()) - ->raw(')->unwrap()') - ; - } - - $compiler->raw(";\n"); - } -} - -class_alias('Twig\Node\ImportNode', 'Twig_Node_Import'); diff --git a/application/third_party/Twig/Node/IncludeNode.php b/application/third_party/Twig/Node/IncludeNode.php deleted file mode 100644 index 544db81eaf3..00000000000 --- a/application/third_party/Twig/Node/IncludeNode.php +++ /dev/null @@ -1,108 +0,0 @@ - - */ -class IncludeNode extends Node implements NodeOutputInterface -{ - public function __construct(AbstractExpression $expr, AbstractExpression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null) - { - $nodes = ['expr' => $expr]; - if (null !== $variables) { - $nodes['variables'] = $variables; - } - - parent::__construct($nodes, ['only' => (bool) $only, 'ignore_missing' => (bool) $ignoreMissing], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler->addDebugInfo($this); - - if ($this->getAttribute('ignore_missing')) { - $template = $compiler->getVarName(); - - $compiler - ->write(sprintf("$%s = null;\n", $template)) - ->write("try {\n") - ->indent() - ->write(sprintf('$%s = ', $template)) - ; - - $this->addGetTemplate($compiler); - - $compiler - ->raw(";\n") - ->outdent() - ->write("} catch (LoaderError \$e) {\n") - ->indent() - ->write("// ignore missing template\n") - ->outdent() - ->write("}\n") - ->write(sprintf("if ($%s) {\n", $template)) - ->indent() - ->write(sprintf('$%s->display(', $template)) - ; - $this->addTemplateArguments($compiler); - $compiler - ->raw(");\n") - ->outdent() - ->write("}\n") - ; - } else { - $this->addGetTemplate($compiler); - $compiler->raw('->display('); - $this->addTemplateArguments($compiler); - $compiler->raw(");\n"); - } - } - - protected function addGetTemplate(Compiler $compiler) - { - $compiler - ->write('$this->loadTemplate(') - ->subcompile($this->getNode('expr')) - ->raw(', ') - ->repr($this->getTemplateName()) - ->raw(', ') - ->repr($this->getTemplateLine()) - ->raw(')') - ; - } - - protected function addTemplateArguments(Compiler $compiler) - { - if (!$this->hasNode('variables')) { - $compiler->raw(false === $this->getAttribute('only') ? '$context' : '[]'); - } elseif (false === $this->getAttribute('only')) { - $compiler - ->raw('twig_array_merge($context, ') - ->subcompile($this->getNode('variables')) - ->raw(')') - ; - } else { - $compiler->raw('twig_to_array('); - $compiler->subcompile($this->getNode('variables')); - $compiler->raw(')'); - } - } -} - -class_alias('Twig\Node\IncludeNode', 'Twig_Node_Include'); diff --git a/application/third_party/Twig/Node/MacroNode.php b/application/third_party/Twig/Node/MacroNode.php deleted file mode 100644 index 6eb67955f4b..00000000000 --- a/application/third_party/Twig/Node/MacroNode.php +++ /dev/null @@ -1,136 +0,0 @@ - - */ -class MacroNode extends Node -{ - const VARARGS_NAME = 'varargs'; - - public function __construct($name, \Twig_NodeInterface $body, \Twig_NodeInterface $arguments, $lineno, $tag = null) - { - foreach ($arguments as $argumentName => $argument) { - if (self::VARARGS_NAME === $argumentName) { - throw new SyntaxError(sprintf('The argument "%s" in macro "%s" cannot be defined because the variable "%s" is reserved for arbitrary arguments.', self::VARARGS_NAME, $name, self::VARARGS_NAME), $argument->getTemplateLine(), $argument->getSourceContext()); - } - } - - parent::__construct(['body' => $body, 'arguments' => $arguments], ['name' => $name], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write(sprintf('public function get%s(', $this->getAttribute('name'))) - ; - - $count = \count($this->getNode('arguments')); - $pos = 0; - foreach ($this->getNode('arguments') as $name => $default) { - $compiler - ->raw('$__'.$name.'__ = ') - ->subcompile($default) - ; - - if (++$pos < $count) { - $compiler->raw(', '); - } - } - - if (\PHP_VERSION_ID >= 50600) { - if ($count) { - $compiler->raw(', '); - } - - $compiler->raw('...$__varargs__'); - } - - $compiler - ->raw(")\n") - ->write("{\n") - ->indent() - ; - - $compiler - ->write("\$context = \$this->env->mergeGlobals([\n") - ->indent() - ; - - foreach ($this->getNode('arguments') as $name => $default) { - $compiler - ->write('') - ->string($name) - ->raw(' => $__'.$name.'__') - ->raw(",\n") - ; - } - - $compiler - ->write('') - ->string(self::VARARGS_NAME) - ->raw(' => ') - ; - - if (\PHP_VERSION_ID >= 50600) { - $compiler->raw("\$__varargs__,\n"); - } else { - $compiler - ->raw('func_num_args() > ') - ->repr($count) - ->raw(' ? array_slice(func_get_args(), ') - ->repr($count) - ->raw(") : [],\n") - ; - } - - $compiler - ->outdent() - ->write("]);\n\n") - ->write("\$blocks = [];\n\n") - ; - if ($compiler->getEnvironment()->isDebug()) { - $compiler->write("ob_start();\n"); - } else { - $compiler->write("ob_start(function () { return ''; });\n"); - } - $compiler - ->write("try {\n") - ->indent() - ->subcompile($this->getNode('body')) - ->outdent() - ->write("} catch (\Exception \$e) {\n") - ->indent() - ->write("ob_end_clean();\n\n") - ->write("throw \$e;\n") - ->outdent() - ->write("} catch (\Throwable \$e) {\n") - ->indent() - ->write("ob_end_clean();\n\n") - ->write("throw \$e;\n") - ->outdent() - ->write("}\n\n") - ->write("return ('' === \$tmp = ob_get_clean()) ? '' : new Markup(\$tmp, \$this->env->getCharset());\n") - ->outdent() - ->write("}\n\n") - ; - } -} - -class_alias('Twig\Node\MacroNode', 'Twig_Node_Macro'); diff --git a/application/third_party/Twig/Node/ModuleNode.php b/application/third_party/Twig/Node/ModuleNode.php deleted file mode 100644 index aab2aa33f2d..00000000000 --- a/application/third_party/Twig/Node/ModuleNode.php +++ /dev/null @@ -1,492 +0,0 @@ - - */ -class ModuleNode extends Node -{ - public function __construct(\Twig_NodeInterface $body, AbstractExpression $parent = null, \Twig_NodeInterface $blocks, \Twig_NodeInterface $macros, \Twig_NodeInterface $traits, $embeddedTemplates, $name, $source = '') - { - if (!$name instanceof Source) { - @trigger_error(sprintf('Passing a string as the $name argument of %s() is deprecated since version 1.27. Pass a \Twig\Source instance instead.', __METHOD__), E_USER_DEPRECATED); - $source = new Source($source, $name); - } else { - $source = $name; - } - - $nodes = [ - 'body' => $body, - 'blocks' => $blocks, - 'macros' => $macros, - 'traits' => $traits, - 'display_start' => new Node(), - 'display_end' => new Node(), - 'constructor_start' => new Node(), - 'constructor_end' => new Node(), - 'class_end' => new Node(), - ]; - if (null !== $parent) { - $nodes['parent'] = $parent; - } - - // embedded templates are set as attributes so that they are only visited once by the visitors - parent::__construct($nodes, [ - // source to be remove in 2.0 - 'source' => $source->getCode(), - // filename to be remove in 2.0 (use getTemplateName() instead) - 'filename' => $source->getName(), - 'index' => null, - 'embedded_templates' => $embeddedTemplates, - ], 1); - - // populate the template name of all node children - $this->setTemplateName($source->getName()); - $this->setSourceContext($source); - } - - public function setIndex($index) - { - $this->setAttribute('index', $index); - } - - public function compile(Compiler $compiler) - { - $this->compileTemplate($compiler); - - foreach ($this->getAttribute('embedded_templates') as $template) { - $compiler->subcompile($template); - } - } - - protected function compileTemplate(Compiler $compiler) - { - if (!$this->getAttribute('index')) { - $compiler->write('compileClassHeader($compiler); - - if ( - \count($this->getNode('blocks')) - || \count($this->getNode('traits')) - || !$this->hasNode('parent') - || $this->getNode('parent') instanceof ConstantExpression - || \count($this->getNode('constructor_start')) - || \count($this->getNode('constructor_end')) - ) { - $this->compileConstructor($compiler); - } - - $this->compileGetParent($compiler); - - $this->compileDisplay($compiler); - - $compiler->subcompile($this->getNode('blocks')); - - $this->compileMacros($compiler); - - $this->compileGetTemplateName($compiler); - - $this->compileIsTraitable($compiler); - - $this->compileDebugInfo($compiler); - - $this->compileGetSource($compiler); - - $this->compileGetSourceContext($compiler); - - $this->compileClassFooter($compiler); - } - - protected function compileGetParent(Compiler $compiler) - { - if (!$this->hasNode('parent')) { - return; - } - $parent = $this->getNode('parent'); - - $compiler - ->write("protected function doGetParent(array \$context)\n", "{\n") - ->indent() - ->addDebugInfo($parent) - ->write('return ') - ; - - if ($parent instanceof ConstantExpression) { - $compiler->subcompile($parent); - } else { - $compiler - ->raw('$this->loadTemplate(') - ->subcompile($parent) - ->raw(', ') - ->repr($this->getSourceContext()->getName()) - ->raw(', ') - ->repr($parent->getTemplateLine()) - ->raw(')') - ; - } - - $compiler - ->raw(";\n") - ->outdent() - ->write("}\n\n") - ; - } - - protected function compileClassHeader(Compiler $compiler) - { - $compiler - ->write("\n\n") - ; - if (!$this->getAttribute('index')) { - $compiler - ->write("use Twig\Environment;\n") - ->write("use Twig\Error\LoaderError;\n") - ->write("use Twig\Error\RuntimeError;\n") - ->write("use Twig\Markup;\n") - ->write("use Twig\Sandbox\SecurityError;\n") - ->write("use Twig\Sandbox\SecurityNotAllowedTagError;\n") - ->write("use Twig\Sandbox\SecurityNotAllowedFilterError;\n") - ->write("use Twig\Sandbox\SecurityNotAllowedFunctionError;\n") - ->write("use Twig\Source;\n") - ->write("use Twig\Template;\n\n") - ; - } - $compiler - // if the template name contains */, add a blank to avoid a PHP parse error - ->write('/* '.str_replace('*/', '* /', $this->getSourceContext()->getName())." */\n") - ->write('class '.$compiler->getEnvironment()->getTemplateClass($this->getSourceContext()->getName(), $this->getAttribute('index'))) - ->raw(sprintf(" extends %s\n", $compiler->getEnvironment()->getBaseTemplateClass())) - ->write("{\n") - ->indent() - ; - } - - protected function compileConstructor(Compiler $compiler) - { - $compiler - ->write("public function __construct(Environment \$env)\n", "{\n") - ->indent() - ->subcompile($this->getNode('constructor_start')) - ->write("parent::__construct(\$env);\n\n") - ; - - // parent - if (!$this->hasNode('parent')) { - $compiler->write("\$this->parent = false;\n\n"); - } - - $countTraits = \count($this->getNode('traits')); - if ($countTraits) { - // traits - foreach ($this->getNode('traits') as $i => $trait) { - $this->compileLoadTemplate($compiler, $trait->getNode('template'), sprintf('$_trait_%s', $i)); - - $node = $trait->getNode('template'); - $compiler - ->addDebugInfo($node) - ->write(sprintf("if (!\$_trait_%s->isTraitable()) {\n", $i)) - ->indent() - ->write("throw new RuntimeError('Template \"'.") - ->subcompile($trait->getNode('template')) - ->raw(".'\" cannot be used as a trait.', ") - ->repr($node->getTemplateLine()) - ->raw(", \$this->getSourceContext());\n") - ->outdent() - ->write("}\n") - ->write(sprintf("\$_trait_%s_blocks = \$_trait_%s->getBlocks();\n\n", $i, $i)) - ; - - foreach ($trait->getNode('targets') as $key => $value) { - $compiler - ->write(sprintf('if (!isset($_trait_%s_blocks[', $i)) - ->string($key) - ->raw("])) {\n") - ->indent() - ->write("throw new RuntimeError(sprintf('Block ") - ->string($key) - ->raw(' is not defined in trait ') - ->subcompile($trait->getNode('template')) - ->raw(".'), ") - ->repr($node->getTemplateLine()) - ->raw(", \$this->getSourceContext());\n") - ->outdent() - ->write("}\n\n") - - ->write(sprintf('$_trait_%s_blocks[', $i)) - ->subcompile($value) - ->raw(sprintf('] = $_trait_%s_blocks[', $i)) - ->string($key) - ->raw(sprintf(']; unset($_trait_%s_blocks[', $i)) - ->string($key) - ->raw("]);\n\n") - ; - } - } - - if ($countTraits > 1) { - $compiler - ->write("\$this->traits = array_merge(\n") - ->indent() - ; - - for ($i = 0; $i < $countTraits; ++$i) { - $compiler - ->write(sprintf('$_trait_%s_blocks'.($i == $countTraits - 1 ? '' : ',')."\n", $i)) - ; - } - - $compiler - ->outdent() - ->write(");\n\n") - ; - } else { - $compiler - ->write("\$this->traits = \$_trait_0_blocks;\n\n") - ; - } - - $compiler - ->write("\$this->blocks = array_merge(\n") - ->indent() - ->write("\$this->traits,\n") - ->write("[\n") - ; - } else { - $compiler - ->write("\$this->blocks = [\n") - ; - } - - // blocks - $compiler - ->indent() - ; - - foreach ($this->getNode('blocks') as $name => $node) { - $compiler - ->write(sprintf("'%s' => [\$this, 'block_%s'],\n", $name, $name)) - ; - } - - if ($countTraits) { - $compiler - ->outdent() - ->write("]\n") - ->outdent() - ->write(");\n") - ; - } else { - $compiler - ->outdent() - ->write("];\n") - ; - } - - $compiler - ->subcompile($this->getNode('constructor_end')) - ->outdent() - ->write("}\n\n") - ; - } - - protected function compileDisplay(Compiler $compiler) - { - $compiler - ->write("protected function doDisplay(array \$context, array \$blocks = [])\n", "{\n") - ->indent() - ->subcompile($this->getNode('display_start')) - ->subcompile($this->getNode('body')) - ; - - if ($this->hasNode('parent')) { - $parent = $this->getNode('parent'); - - $compiler->addDebugInfo($parent); - if ($parent instanceof ConstantExpression) { - $compiler - ->write('$this->parent = $this->loadTemplate(') - ->subcompile($parent) - ->raw(', ') - ->repr($this->getSourceContext()->getName()) - ->raw(', ') - ->repr($parent->getTemplateLine()) - ->raw(");\n") - ; - $compiler->write('$this->parent'); - } else { - $compiler->write('$this->getParent($context)'); - } - $compiler->raw("->display(\$context, array_merge(\$this->blocks, \$blocks));\n"); - } - - $compiler - ->subcompile($this->getNode('display_end')) - ->outdent() - ->write("}\n\n") - ; - } - - protected function compileClassFooter(Compiler $compiler) - { - $compiler - ->subcompile($this->getNode('class_end')) - ->outdent() - ->write("}\n") - ; - } - - protected function compileMacros(Compiler $compiler) - { - $compiler->subcompile($this->getNode('macros')); - } - - protected function compileGetTemplateName(Compiler $compiler) - { - $compiler - ->write("public function getTemplateName()\n", "{\n") - ->indent() - ->write('return ') - ->repr($this->getSourceContext()->getName()) - ->raw(";\n") - ->outdent() - ->write("}\n\n") - ; - } - - protected function compileIsTraitable(Compiler $compiler) - { - // A template can be used as a trait if: - // * it has no parent - // * it has no macros - // * it has no body - // - // Put another way, a template can be used as a trait if it - // only contains blocks and use statements. - $traitable = !$this->hasNode('parent') && 0 === \count($this->getNode('macros')); - if ($traitable) { - if ($this->getNode('body') instanceof BodyNode) { - $nodes = $this->getNode('body')->getNode(0); - } else { - $nodes = $this->getNode('body'); - } - - if (!\count($nodes)) { - $nodes = new Node([$nodes]); - } - - foreach ($nodes as $node) { - if (!\count($node)) { - continue; - } - - if ($node instanceof TextNode && ctype_space($node->getAttribute('data'))) { - continue; - } - - if ($node instanceof BlockReferenceNode) { - continue; - } - - $traitable = false; - break; - } - } - - if ($traitable) { - return; - } - - $compiler - ->write("public function isTraitable()\n", "{\n") - ->indent() - ->write(sprintf("return %s;\n", $traitable ? 'true' : 'false')) - ->outdent() - ->write("}\n\n") - ; - } - - protected function compileDebugInfo(Compiler $compiler) - { - $compiler - ->write("public function getDebugInfo()\n", "{\n") - ->indent() - ->write(sprintf("return %s;\n", str_replace("\n", '', var_export(array_reverse($compiler->getDebugInfo(), true), true)))) - ->outdent() - ->write("}\n\n") - ; - } - - protected function compileGetSource(Compiler $compiler) - { - $compiler - ->write("/** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */\n") - ->write("public function getSource()\n", "{\n") - ->indent() - ->write("@trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED);\n\n") - ->write('return $this->getSourceContext()->getCode();') - ->raw("\n") - ->outdent() - ->write("}\n\n") - ; - } - - protected function compileGetSourceContext(Compiler $compiler) - { - $compiler - ->write("public function getSourceContext()\n", "{\n") - ->indent() - ->write('return new Source(') - ->string($compiler->getEnvironment()->isDebug() ? $this->getSourceContext()->getCode() : '') - ->raw(', ') - ->string($this->getSourceContext()->getName()) - ->raw(', ') - ->string($this->getSourceContext()->getPath()) - ->raw(");\n") - ->outdent() - ->write("}\n") - ; - } - - protected function compileLoadTemplate(Compiler $compiler, $node, $var) - { - if ($node instanceof ConstantExpression) { - $compiler - ->write(sprintf('%s = $this->loadTemplate(', $var)) - ->subcompile($node) - ->raw(', ') - ->repr($node->getTemplateName()) - ->raw(', ') - ->repr($node->getTemplateLine()) - ->raw(");\n") - ; - } else { - throw new \LogicException('Trait templates can only be constant nodes.'); - } - } -} - -class_alias('Twig\Node\ModuleNode', 'Twig_Node_Module'); diff --git a/application/third_party/Twig/Node/Node.php b/application/third_party/Twig/Node/Node.php deleted file mode 100644 index c890feb72da..00000000000 --- a/application/third_party/Twig/Node/Node.php +++ /dev/null @@ -1,274 +0,0 @@ - - */ -class Node implements \Twig_NodeInterface -{ - protected $nodes; - protected $attributes; - protected $lineno; - protected $tag; - - private $name; - private $sourceContext; - - /** - * @param array $nodes An array of named nodes - * @param array $attributes An array of attributes (should not be nodes) - * @param int $lineno The line number - * @param string $tag The tag name associated with the Node - */ - public function __construct(array $nodes = [], array $attributes = [], $lineno = 0, $tag = null) - { - foreach ($nodes as $name => $node) { - if (!$node instanceof \Twig_NodeInterface) { - @trigger_error(sprintf('Using "%s" for the value of node "%s" of "%s" is deprecated since version 1.25 and will be removed in 2.0.', \is_object($node) ? \get_class($node) : (null === $node ? 'null' : \gettype($node)), $name, \get_class($this)), E_USER_DEPRECATED); - } - } - $this->nodes = $nodes; - $this->attributes = $attributes; - $this->lineno = $lineno; - $this->tag = $tag; - } - - public function __toString() - { - $attributes = []; - foreach ($this->attributes as $name => $value) { - $attributes[] = sprintf('%s: %s', $name, str_replace("\n", '', var_export($value, true))); - } - - $repr = [\get_class($this).'('.implode(', ', $attributes)]; - - if (\count($this->nodes)) { - foreach ($this->nodes as $name => $node) { - $len = \strlen($name) + 4; - $noderepr = []; - foreach (explode("\n", (string) $node) as $line) { - $noderepr[] = str_repeat(' ', $len).$line; - } - - $repr[] = sprintf(' %s: %s', $name, ltrim(implode("\n", $noderepr))); - } - - $repr[] = ')'; - } else { - $repr[0] .= ')'; - } - - return implode("\n", $repr); - } - - /** - * @deprecated since 1.16.1 (to be removed in 2.0) - */ - public function toXml($asDom = false) - { - @trigger_error(sprintf('%s is deprecated since version 1.16.1 and will be removed in 2.0.', __METHOD__), E_USER_DEPRECATED); - - $dom = new \DOMDocument('1.0', 'UTF-8'); - $dom->formatOutput = true; - $dom->appendChild($xml = $dom->createElement('twig')); - - $xml->appendChild($node = $dom->createElement('node')); - $node->setAttribute('class', \get_class($this)); - - foreach ($this->attributes as $name => $value) { - $node->appendChild($attribute = $dom->createElement('attribute')); - $attribute->setAttribute('name', $name); - $attribute->appendChild($dom->createTextNode($value)); - } - - foreach ($this->nodes as $name => $n) { - if (null === $n) { - continue; - } - - $child = $n->toXml(true)->getElementsByTagName('node')->item(0); - $child = $dom->importNode($child, true); - $child->setAttribute('name', $name); - - $node->appendChild($child); - } - - return $asDom ? $dom : $dom->saveXML(); - } - - public function compile(Compiler $compiler) - { - foreach ($this->nodes as $node) { - $node->compile($compiler); - } - } - - public function getTemplateLine() - { - return $this->lineno; - } - - /** - * @deprecated since 1.27 (to be removed in 2.0) - */ - public function getLine() - { - @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getTemplateLine() instead.', E_USER_DEPRECATED); - - return $this->lineno; - } - - public function getNodeTag() - { - return $this->tag; - } - - /** - * @return bool - */ - public function hasAttribute($name) - { - return \array_key_exists($name, $this->attributes); - } - - /** - * @return mixed - */ - public function getAttribute($name) - { - if (!\array_key_exists($name, $this->attributes)) { - throw new \LogicException(sprintf('Attribute "%s" does not exist for Node "%s".', $name, \get_class($this))); - } - - return $this->attributes[$name]; - } - - /** - * @param string $name - * @param mixed $value - */ - public function setAttribute($name, $value) - { - $this->attributes[$name] = $value; - } - - public function removeAttribute($name) - { - unset($this->attributes[$name]); - } - - /** - * @return bool - */ - public function hasNode($name) - { - return \array_key_exists($name, $this->nodes); - } - - /** - * @return Node - */ - public function getNode($name) - { - if (!\array_key_exists($name, $this->nodes)) { - throw new \LogicException(sprintf('Node "%s" does not exist for Node "%s".', $name, \get_class($this))); - } - - return $this->nodes[$name]; - } - - public function setNode($name, $node = null) - { - if (!$node instanceof \Twig_NodeInterface) { - @trigger_error(sprintf('Using "%s" for the value of node "%s" of "%s" is deprecated since version 1.25 and will be removed in 2.0.', \is_object($node) ? \get_class($node) : (null === $node ? 'null' : \gettype($node)), $name, \get_class($this)), E_USER_DEPRECATED); - } - - $this->nodes[$name] = $node; - } - - public function removeNode($name) - { - unset($this->nodes[$name]); - } - - public function count() - { - return \count($this->nodes); - } - - public function getIterator() - { - return new \ArrayIterator($this->nodes); - } - - public function setTemplateName($name) - { - $this->name = $name; - foreach ($this->nodes as $node) { - if (null !== $node) { - $node->setTemplateName($name); - } - } - } - - public function getTemplateName() - { - return $this->name; - } - - public function setSourceContext(Source $source) - { - $this->sourceContext = $source; - foreach ($this->nodes as $node) { - if ($node instanceof Node) { - $node->setSourceContext($source); - } - } - } - - public function getSourceContext() - { - return $this->sourceContext; - } - - /** - * @deprecated since 1.27 (to be removed in 2.0) - */ - public function setFilename($name) - { - @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use setTemplateName() instead.', E_USER_DEPRECATED); - - $this->setTemplateName($name); - } - - /** - * @deprecated since 1.27 (to be removed in 2.0) - */ - public function getFilename() - { - @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getTemplateName() instead.', E_USER_DEPRECATED); - - return $this->name; - } -} - -class_alias('Twig\Node\Node', 'Twig_Node'); - -// Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. -class_exists('Twig\Compiler'); diff --git a/application/third_party/Twig/Node/NodeCaptureInterface.php b/application/third_party/Twig/Node/NodeCaptureInterface.php deleted file mode 100644 index 474003f34bd..00000000000 --- a/application/third_party/Twig/Node/NodeCaptureInterface.php +++ /dev/null @@ -1,23 +0,0 @@ - - */ -interface NodeCaptureInterface -{ -} - -class_alias('Twig\Node\NodeCaptureInterface', 'Twig_NodeCaptureInterface'); diff --git a/application/third_party/Twig/Node/NodeOutputInterface.php b/application/third_party/Twig/Node/NodeOutputInterface.php deleted file mode 100644 index 8b046ee7661..00000000000 --- a/application/third_party/Twig/Node/NodeOutputInterface.php +++ /dev/null @@ -1,23 +0,0 @@ - - */ -interface NodeOutputInterface -{ -} - -class_alias('Twig\Node\NodeOutputInterface', 'Twig_NodeOutputInterface'); diff --git a/application/third_party/Twig/Node/PrintNode.php b/application/third_party/Twig/Node/PrintNode.php deleted file mode 100644 index 27f1ca42272..00000000000 --- a/application/third_party/Twig/Node/PrintNode.php +++ /dev/null @@ -1,41 +0,0 @@ - - */ -class PrintNode extends Node implements NodeOutputInterface -{ - public function __construct(AbstractExpression $expr, $lineno, $tag = null) - { - parent::__construct(['expr' => $expr], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write('echo ') - ->subcompile($this->getNode('expr')) - ->raw(";\n") - ; - } -} - -class_alias('Twig\Node\PrintNode', 'Twig_Node_Print'); diff --git a/application/third_party/Twig/Node/SandboxNode.php b/application/third_party/Twig/Node/SandboxNode.php deleted file mode 100644 index 2d644c3a137..00000000000 --- a/application/third_party/Twig/Node/SandboxNode.php +++ /dev/null @@ -1,47 +0,0 @@ - - */ -class SandboxNode extends Node -{ - public function __construct(\Twig_NodeInterface $body, $lineno, $tag = null) - { - parent::__construct(['body' => $body], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write("if (!\$alreadySandboxed = \$this->sandbox->isSandboxed()) {\n") - ->indent() - ->write("\$this->sandbox->enableSandbox();\n") - ->outdent() - ->write("}\n") - ->subcompile($this->getNode('body')) - ->write("if (!\$alreadySandboxed) {\n") - ->indent() - ->write("\$this->sandbox->disableSandbox();\n") - ->outdent() - ->write("}\n") - ; - } -} - -class_alias('Twig\Node\SandboxNode', 'Twig_Node_Sandbox'); diff --git a/application/third_party/Twig/Node/SandboxedPrintNode.php b/application/third_party/Twig/Node/SandboxedPrintNode.php deleted file mode 100644 index 2359af91104..00000000000 --- a/application/third_party/Twig/Node/SandboxedPrintNode.php +++ /dev/null @@ -1,69 +0,0 @@ - - */ -class SandboxedPrintNode extends PrintNode -{ - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write('echo ') - ; - $expr = $this->getNode('expr'); - if ($expr instanceof ConstantExpression) { - $compiler - ->subcompile($expr) - ->raw(";\n") - ; - } else { - $compiler - ->write('$this->env->getExtension(\'\Twig\Extension\SandboxExtension\')->ensureToStringAllowed(') - ->subcompile($expr) - ->raw(");\n") - ; - } - } - - /** - * Removes node filters. - * - * This is mostly needed when another visitor adds filters (like the escaper one). - * - * @return Node - */ - protected function removeNodeFilter(Node $node) - { - if ($node instanceof FilterExpression) { - return $this->removeNodeFilter($node->getNode('node')); - } - - return $node; - } -} - -class_alias('Twig\Node\SandboxedPrintNode', 'Twig_Node_SandboxedPrint'); diff --git a/application/third_party/Twig/Node/SetNode.php b/application/third_party/Twig/Node/SetNode.php deleted file mode 100644 index 656103b9fd2..00000000000 --- a/application/third_party/Twig/Node/SetNode.php +++ /dev/null @@ -1,107 +0,0 @@ - - */ -class SetNode extends Node implements NodeCaptureInterface -{ - public function __construct($capture, \Twig_NodeInterface $names, \Twig_NodeInterface $values, $lineno, $tag = null) - { - parent::__construct(['names' => $names, 'values' => $values], ['capture' => $capture, 'safe' => false], $lineno, $tag); - - /* - * Optimizes the node when capture is used for a large block of text. - * - * {% set foo %}foo{% endset %} is compiled to $context['foo'] = new Twig\Markup("foo"); - */ - if ($this->getAttribute('capture')) { - $this->setAttribute('safe', true); - - $values = $this->getNode('values'); - if ($values instanceof TextNode) { - $this->setNode('values', new ConstantExpression($values->getAttribute('data'), $values->getTemplateLine())); - $this->setAttribute('capture', false); - } - } - } - - public function compile(Compiler $compiler) - { - $compiler->addDebugInfo($this); - - if (\count($this->getNode('names')) > 1) { - $compiler->write('list('); - foreach ($this->getNode('names') as $idx => $node) { - if ($idx) { - $compiler->raw(', '); - } - - $compiler->subcompile($node); - } - $compiler->raw(')'); - } else { - if ($this->getAttribute('capture')) { - if ($compiler->getEnvironment()->isDebug()) { - $compiler->write("ob_start();\n"); - } else { - $compiler->write("ob_start(function () { return ''; });\n"); - } - $compiler - ->subcompile($this->getNode('values')) - ; - } - - $compiler->subcompile($this->getNode('names'), false); - - if ($this->getAttribute('capture')) { - $compiler->raw(" = ('' === \$tmp = ob_get_clean()) ? '' : new Markup(\$tmp, \$this->env->getCharset())"); - } - } - - if (!$this->getAttribute('capture')) { - $compiler->raw(' = '); - - if (\count($this->getNode('names')) > 1) { - $compiler->write('['); - foreach ($this->getNode('values') as $idx => $value) { - if ($idx) { - $compiler->raw(', '); - } - - $compiler->subcompile($value); - } - $compiler->raw(']'); - } else { - if ($this->getAttribute('safe')) { - $compiler - ->raw("('' === \$tmp = ") - ->subcompile($this->getNode('values')) - ->raw(") ? '' : new Markup(\$tmp, \$this->env->getCharset())") - ; - } else { - $compiler->subcompile($this->getNode('values')); - } - } - } - - $compiler->raw(";\n"); - } -} - -class_alias('Twig\Node\SetNode', 'Twig_Node_Set'); diff --git a/application/third_party/Twig/Node/SetTempNode.php b/application/third_party/Twig/Node/SetTempNode.php deleted file mode 100644 index 918fb991de0..00000000000 --- a/application/third_party/Twig/Node/SetTempNode.php +++ /dev/null @@ -1,44 +0,0 @@ - $name], $lineno); - } - - public function compile(Compiler $compiler) - { - $name = $this->getAttribute('name'); - $compiler - ->addDebugInfo($this) - ->write('if (isset($context[') - ->string($name) - ->raw('])) { $_') - ->raw($name) - ->raw('_ = $context[') - ->repr($name) - ->raw(']; } else { $_') - ->raw($name) - ->raw("_ = null; }\n") - ; - } -} - -class_alias('Twig\Node\SetTempNode', 'Twig_Node_SetTemp'); diff --git a/application/third_party/Twig/Node/SpacelessNode.php b/application/third_party/Twig/Node/SpacelessNode.php deleted file mode 100644 index c8d32daf6bd..00000000000 --- a/application/third_party/Twig/Node/SpacelessNode.php +++ /dev/null @@ -1,47 +0,0 @@ - - */ -class SpacelessNode extends Node -{ - public function __construct(\Twig_NodeInterface $body, $lineno, $tag = 'spaceless') - { - parent::__construct(['body' => $body], [], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ; - if ($compiler->getEnvironment()->isDebug()) { - $compiler->write("ob_start();\n"); - } else { - $compiler->write("ob_start(function () { return ''; });\n"); - } - $compiler - ->subcompile($this->getNode('body')) - ->write("echo trim(preg_replace('/>\s+<', ob_get_clean()));\n") - ; - } -} - -class_alias('Twig\Node\SpacelessNode', 'Twig_Node_Spaceless'); diff --git a/application/third_party/Twig/Node/TextNode.php b/application/third_party/Twig/Node/TextNode.php deleted file mode 100644 index 9ac435e904f..00000000000 --- a/application/third_party/Twig/Node/TextNode.php +++ /dev/null @@ -1,40 +0,0 @@ - - */ -class TextNode extends Node implements NodeOutputInterface -{ - public function __construct($data, $lineno) - { - parent::__construct([], ['data' => $data], $lineno); - } - - public function compile(Compiler $compiler) - { - $compiler - ->addDebugInfo($this) - ->write('echo ') - ->string($this->getAttribute('data')) - ->raw(";\n") - ; - } -} - -class_alias('Twig\Node\TextNode', 'Twig_Node_Text'); diff --git a/application/third_party/Twig/Node/WithNode.php b/application/third_party/Twig/Node/WithNode.php deleted file mode 100644 index f5ae9246ddc..00000000000 --- a/application/third_party/Twig/Node/WithNode.php +++ /dev/null @@ -1,72 +0,0 @@ - - */ -class WithNode extends Node -{ - public function __construct(Node $body, Node $variables = null, $only = false, $lineno, $tag = null) - { - $nodes = ['body' => $body]; - if (null !== $variables) { - $nodes['variables'] = $variables; - } - - parent::__construct($nodes, ['only' => (bool) $only], $lineno, $tag); - } - - public function compile(Compiler $compiler) - { - $compiler->addDebugInfo($this); - - if ($this->hasNode('variables')) { - $node = $this->getNode('variables'); - $varsName = $compiler->getVarName(); - $compiler - ->write(sprintf('$%s = ', $varsName)) - ->subcompile($node) - ->raw(";\n") - ->write(sprintf("if (!twig_test_iterable(\$%s)) {\n", $varsName)) - ->indent() - ->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.', ") - ->repr($node->getTemplateLine()) - ->raw(", \$this->getSourceContext());\n") - ->outdent() - ->write("}\n") - ->write(sprintf("\$%s = twig_to_array(\$%s);\n", $varsName, $varsName)) - ; - - if ($this->getAttribute('only')) { - $compiler->write("\$context = ['_parent' => \$context];\n"); - } else { - $compiler->write("\$context['_parent'] = \$context;\n"); - } - - $compiler->write(sprintf("\$context = \$this->env->mergeGlobals(array_merge(\$context, \$%s));\n", $varsName)); - } else { - $compiler->write("\$context['_parent'] = \$context;\n"); - } - - $compiler - ->subcompile($this->getNode('body')) - ->write("\$context = \$context['_parent'];\n") - ; - } -} - -class_alias('Twig\Node\WithNode', 'Twig_Node_With'); diff --git a/application/third_party/Twig/NodeTraverser.php b/application/third_party/Twig/NodeTraverser.php index bd25d3cc748..5b05cd67f01 100644 --- a/application/third_party/Twig/NodeTraverser.php +++ b/application/third_party/Twig/NodeTraverser.php @@ -3,18 +3,14 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\NodeVisitor\NodeVisitorInterface; - /** - * A node traverser. + * Twig_NodeTraverser is a node traverser. * * It visits all nodes and their children and calls the given visitor for each. * @@ -22,15 +18,16 @@ * * @author Fabien Potencier */ -class NodeTraverser +class Twig_NodeTraverser { protected $env; - protected $visitors = []; + protected $visitors = array(); /** - * @param NodeVisitorInterface[] $visitors + * @param Twig_Environment $env + * @param Twig_NodeVisitorInterface[] $visitors */ - public function __construct(Environment $env, array $visitors = []) + public function __construct(Twig_Environment $env, array $visitors = array()) { $this->env = $env; foreach ($visitors as $visitor) { @@ -38,17 +35,21 @@ public function __construct(Environment $env, array $visitors = []) } } - public function addVisitor(NodeVisitorInterface $visitor) + public function addVisitor(Twig_NodeVisitorInterface $visitor) { + if (!isset($this->visitors[$visitor->getPriority()])) { + $this->visitors[$visitor->getPriority()] = array(); + } + $this->visitors[$visitor->getPriority()][] = $visitor; } /** * Traverses a node and calls the registered visitors. * - * @return \Twig_NodeInterface + * @return Twig_NodeInterface */ - public function traverse(\Twig_NodeInterface $node) + public function traverse(Twig_NodeInterface $node) { ksort($this->visitors); foreach ($this->visitors as $visitors) { @@ -60,7 +61,7 @@ public function traverse(\Twig_NodeInterface $node) return $node; } - protected function traverseForVisitor(NodeVisitorInterface $visitor, \Twig_NodeInterface $node = null) + protected function traverseForVisitor(Twig_NodeVisitorInterface $visitor, Twig_NodeInterface $node = null) { if (null === $node) { return; @@ -69,14 +70,8 @@ protected function traverseForVisitor(NodeVisitorInterface $visitor, \Twig_NodeI $node = $visitor->enterNode($node, $this->env); foreach ($node as $k => $n) { - if (null === $n) { - continue; - } - - if (false !== ($m = $this->traverseForVisitor($visitor, $n)) && null !== $m) { - if ($m !== $n) { - $node->setNode($k, $m); - } + if (false !== $n = $this->traverseForVisitor($visitor, $n)) { + $node->setNode($k, $n); } else { $node->removeNode($k); } @@ -85,5 +80,3 @@ protected function traverseForVisitor(NodeVisitorInterface $visitor, \Twig_NodeI return $visitor->leaveNode($node, $this->env); } } - -class_alias('Twig\NodeTraverser', 'Twig_NodeTraverser'); diff --git a/application/third_party/Twig/NodeVisitor/AbstractNodeVisitor.php b/application/third_party/Twig/NodeVisitor/AbstractNodeVisitor.php deleted file mode 100644 index b66c3c6f116..00000000000 --- a/application/third_party/Twig/NodeVisitor/AbstractNodeVisitor.php +++ /dev/null @@ -1,59 +0,0 @@ - - */ -abstract class AbstractNodeVisitor implements NodeVisitorInterface -{ - final public function enterNode(\Twig_NodeInterface $node, Environment $env) - { - if (!$node instanceof Node) { - throw new \LogicException(sprintf('%s only supports \Twig\Node\Node instances.', __CLASS__)); - } - - return $this->doEnterNode($node, $env); - } - - final public function leaveNode(\Twig_NodeInterface $node, Environment $env) - { - if (!$node instanceof Node) { - throw new \LogicException(sprintf('%s only supports \Twig\Node\Node instances.', __CLASS__)); - } - - return $this->doLeaveNode($node, $env); - } - - /** - * Called before child nodes are visited. - * - * @return Node The modified node - */ - abstract protected function doEnterNode(Node $node, Environment $env); - - /** - * Called after child nodes are visited. - * - * @return Node|false|null The modified node or null if the node must be removed - */ - abstract protected function doLeaveNode(Node $node, Environment $env); -} - -class_alias('Twig\NodeVisitor\AbstractNodeVisitor', 'Twig_BaseNodeVisitor'); diff --git a/application/third_party/Twig/NodeVisitor/EscaperNodeVisitor.php b/application/third_party/Twig/NodeVisitor/EscaperNodeVisitor.php deleted file mode 100644 index f6e16fa7d77..00000000000 --- a/application/third_party/Twig/NodeVisitor/EscaperNodeVisitor.php +++ /dev/null @@ -1,209 +0,0 @@ - - */ -class EscaperNodeVisitor extends AbstractNodeVisitor -{ - protected $statusStack = []; - protected $blocks = []; - protected $safeAnalysis; - protected $traverser; - protected $defaultStrategy = false; - protected $safeVars = []; - - public function __construct() - { - $this->safeAnalysis = new SafeAnalysisNodeVisitor(); - } - - protected function doEnterNode(Node $node, Environment $env) - { - if ($node instanceof ModuleNode) { - if ($env->hasExtension('\Twig\Extension\EscaperExtension') && $defaultStrategy = $env->getExtension('\Twig\Extension\EscaperExtension')->getDefaultStrategy($node->getTemplateName())) { - $this->defaultStrategy = $defaultStrategy; - } - $this->safeVars = []; - $this->blocks = []; - } elseif ($node instanceof AutoEscapeNode) { - $this->statusStack[] = $node->getAttribute('value'); - } elseif ($node instanceof BlockNode) { - $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env); - } elseif ($node instanceof ImportNode) { - $this->safeVars[] = $node->getNode('var')->getAttribute('name'); - } - - return $node; - } - - protected function doLeaveNode(Node $node, Environment $env) - { - if ($node instanceof ModuleNode) { - $this->defaultStrategy = false; - $this->safeVars = []; - $this->blocks = []; - } elseif ($node instanceof FilterExpression) { - return $this->preEscapeFilterNode($node, $env); - } elseif ($node instanceof PrintNode && false !== $type = $this->needEscaping($env)) { - $expression = $node->getNode('expr'); - if ($expression instanceof ConditionalExpression && $this->shouldUnwrapConditional($expression, $env, $type)) { - return new DoNode($this->unwrapConditional($expression, $env, $type), $expression->getTemplateLine()); - } - - return $this->escapePrintNode($node, $env, $type); - } - - if ($node instanceof AutoEscapeNode || $node instanceof BlockNode) { - array_pop($this->statusStack); - } elseif ($node instanceof BlockReferenceNode) { - $this->blocks[$node->getAttribute('name')] = $this->needEscaping($env); - } - - return $node; - } - - private function shouldUnwrapConditional(ConditionalExpression $expression, Environment $env, $type) - { - $expr2Safe = $this->isSafeFor($type, $expression->getNode('expr2'), $env); - $expr3Safe = $this->isSafeFor($type, $expression->getNode('expr3'), $env); - - return $expr2Safe !== $expr3Safe; - } - - private function unwrapConditional(ConditionalExpression $expression, Environment $env, $type) - { - // convert "echo a ? b : c" to "a ? echo b : echo c" recursively - $expr2 = $expression->getNode('expr2'); - if ($expr2 instanceof ConditionalExpression && $this->shouldUnwrapConditional($expr2, $env, $type)) { - $expr2 = $this->unwrapConditional($expr2, $env, $type); - } else { - $expr2 = $this->escapeInlinePrintNode(new InlinePrint($expr2, $expr2->getTemplateLine()), $env, $type); - } - $expr3 = $expression->getNode('expr3'); - if ($expr3 instanceof ConditionalExpression && $this->shouldUnwrapConditional($expr3, $env, $type)) { - $expr3 = $this->unwrapConditional($expr3, $env, $type); - } else { - $expr3 = $this->escapeInlinePrintNode(new InlinePrint($expr3, $expr3->getTemplateLine()), $env, $type); - } - - return new ConditionalExpression($expression->getNode('expr1'), $expr2, $expr3, $expression->getTemplateLine()); - } - - private function escapeInlinePrintNode(InlinePrint $node, Environment $env, $type) - { - $expression = $node->getNode('node'); - - if ($this->isSafeFor($type, $expression, $env)) { - return $node; - } - - return new InlinePrint($this->getEscaperFilter($type, $expression), $node->getTemplateLine()); - } - - protected function escapePrintNode(PrintNode $node, Environment $env, $type) - { - if (false === $type) { - return $node; - } - - $expression = $node->getNode('expr'); - - if ($this->isSafeFor($type, $expression, $env)) { - return $node; - } - - $class = \get_class($node); - - return new $class($this->getEscaperFilter($type, $expression), $node->getTemplateLine()); - } - - protected function preEscapeFilterNode(FilterExpression $filter, Environment $env) - { - $name = $filter->getNode('filter')->getAttribute('value'); - - $type = $env->getFilter($name)->getPreEscape(); - if (null === $type) { - return $filter; - } - - $node = $filter->getNode('node'); - if ($this->isSafeFor($type, $node, $env)) { - return $filter; - } - - $filter->setNode('node', $this->getEscaperFilter($type, $node)); - - return $filter; - } - - protected function isSafeFor($type, \Twig_NodeInterface $expression, $env) - { - $safe = $this->safeAnalysis->getSafe($expression); - - if (null === $safe) { - if (null === $this->traverser) { - $this->traverser = new NodeTraverser($env, [$this->safeAnalysis]); - } - - $this->safeAnalysis->setSafeVars($this->safeVars); - - $this->traverser->traverse($expression); - $safe = $this->safeAnalysis->getSafe($expression); - } - - return \in_array($type, $safe) || \in_array('all', $safe); - } - - protected function needEscaping(Environment $env) - { - if (\count($this->statusStack)) { - return $this->statusStack[\count($this->statusStack) - 1]; - } - - return $this->defaultStrategy ? $this->defaultStrategy : false; - } - - protected function getEscaperFilter($type, \Twig_NodeInterface $node) - { - $line = $node->getTemplateLine(); - $name = new ConstantExpression('escape', $line); - $args = new Node([new ConstantExpression((string) $type, $line), new ConstantExpression(null, $line), new ConstantExpression(true, $line)]); - - return new FilterExpression($node, $name, $args, $line); - } - - public function getPriority() - { - return 0; - } -} - -class_alias('Twig\NodeVisitor\EscaperNodeVisitor', 'Twig_NodeVisitor_Escaper'); diff --git a/application/third_party/Twig/NodeVisitor/NodeVisitorInterface.php b/application/third_party/Twig/NodeVisitor/NodeVisitorInterface.php deleted file mode 100644 index 9b8730b48de..00000000000 --- a/application/third_party/Twig/NodeVisitor/NodeVisitorInterface.php +++ /dev/null @@ -1,50 +0,0 @@ - - */ -interface NodeVisitorInterface -{ - /** - * Called before child nodes are visited. - * - * @return \Twig_NodeInterface The modified node - */ - public function enterNode(\Twig_NodeInterface $node, Environment $env); - - /** - * Called after child nodes are visited. - * - * @return \Twig_NodeInterface|false|null The modified node or null if the node must be removed - */ - public function leaveNode(\Twig_NodeInterface $node, Environment $env); - - /** - * Returns the priority for this visitor. - * - * Priority should be between -10 and 10 (0 is the default). - * - * @return int The priority level - */ - public function getPriority(); -} - -class_alias('Twig\NodeVisitor\NodeVisitorInterface', 'Twig_NodeVisitorInterface'); - -// Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. -class_exists('Twig\Environment'); diff --git a/application/third_party/Twig/NodeVisitor/OptimizerNodeVisitor.php b/application/third_party/Twig/NodeVisitor/OptimizerNodeVisitor.php deleted file mode 100644 index e5ea9b7cc39..00000000000 --- a/application/third_party/Twig/NodeVisitor/OptimizerNodeVisitor.php +++ /dev/null @@ -1,273 +0,0 @@ - - */ -class OptimizerNodeVisitor extends AbstractNodeVisitor -{ - const OPTIMIZE_ALL = -1; - const OPTIMIZE_NONE = 0; - const OPTIMIZE_FOR = 2; - const OPTIMIZE_RAW_FILTER = 4; - const OPTIMIZE_VAR_ACCESS = 8; - - protected $loops = []; - protected $loopsTargets = []; - protected $optimizers; - protected $prependedNodes = []; - protected $inABody = false; - - /** - * @param int $optimizers The optimizer mode - */ - public function __construct($optimizers = -1) - { - if (!\is_int($optimizers) || $optimizers > (self::OPTIMIZE_FOR | self::OPTIMIZE_RAW_FILTER | self::OPTIMIZE_VAR_ACCESS)) { - throw new \InvalidArgumentException(sprintf('Optimizer mode "%s" is not valid.', $optimizers)); - } - - $this->optimizers = $optimizers; - } - - protected function doEnterNode(Node $node, Environment $env) - { - if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) { - $this->enterOptimizeFor($node, $env); - } - - if (\PHP_VERSION_ID < 50400 && self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('\Twig\Extension\SandboxExtension')) { - if ($this->inABody) { - if (!$node instanceof AbstractExpression) { - if ('Twig_Node' !== \get_class($node)) { - array_unshift($this->prependedNodes, []); - } - } else { - $node = $this->optimizeVariables($node, $env); - } - } elseif ($node instanceof BodyNode) { - $this->inABody = true; - } - } - - return $node; - } - - protected function doLeaveNode(Node $node, Environment $env) - { - $expression = $node instanceof AbstractExpression; - - if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) { - $this->leaveOptimizeFor($node, $env); - } - - if (self::OPTIMIZE_RAW_FILTER === (self::OPTIMIZE_RAW_FILTER & $this->optimizers)) { - $node = $this->optimizeRawFilter($node, $env); - } - - $node = $this->optimizePrintNode($node, $env); - - if (self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('\Twig\Extension\SandboxExtension')) { - if ($node instanceof BodyNode) { - $this->inABody = false; - } elseif ($this->inABody) { - if (!$expression && 'Twig_Node' !== \get_class($node) && $prependedNodes = array_shift($this->prependedNodes)) { - $nodes = []; - foreach (array_unique($prependedNodes) as $name) { - $nodes[] = new SetTempNode($name, $node->getTemplateLine()); - } - - $nodes[] = $node; - $node = new Node($nodes); - } - } - } - - return $node; - } - - protected function optimizeVariables(\Twig_NodeInterface $node, Environment $env) - { - if ('Twig_Node_Expression_Name' === \get_class($node) && $node->isSimple()) { - $this->prependedNodes[0][] = $node->getAttribute('name'); - - return new TempNameExpression($node->getAttribute('name'), $node->getTemplateLine()); - } - - return $node; - } - - /** - * Optimizes print nodes. - * - * It replaces: - * - * * "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()" - * - * @return \Twig_NodeInterface - */ - protected function optimizePrintNode(\Twig_NodeInterface $node, Environment $env) - { - if (!$node instanceof PrintNode) { - return $node; - } - - $exprNode = $node->getNode('expr'); - if ( - $exprNode instanceof BlockReferenceExpression || - $exprNode instanceof ParentExpression - ) { - $exprNode->setAttribute('output', true); - - return $exprNode; - } - - return $node; - } - - /** - * Removes "raw" filters. - * - * @return \Twig_NodeInterface - */ - protected function optimizeRawFilter(\Twig_NodeInterface $node, Environment $env) - { - if ($node instanceof FilterExpression && 'raw' == $node->getNode('filter')->getAttribute('value')) { - return $node->getNode('node'); - } - - return $node; - } - - /** - * Optimizes "for" tag by removing the "loop" variable creation whenever possible. - */ - protected function enterOptimizeFor(\Twig_NodeInterface $node, Environment $env) - { - if ($node instanceof ForNode) { - // disable the loop variable by default - $node->setAttribute('with_loop', false); - array_unshift($this->loops, $node); - array_unshift($this->loopsTargets, $node->getNode('value_target')->getAttribute('name')); - array_unshift($this->loopsTargets, $node->getNode('key_target')->getAttribute('name')); - } 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 NameExpression && 'loop' === $node->getAttribute('name')) { - $node->setAttribute('always_defined', true); - $this->addLoopToCurrent(); - } - - // optimize access to loop targets - elseif ($node instanceof NameExpression && \in_array($node->getAttribute('name'), $this->loopsTargets)) { - $node->setAttribute('always_defined', true); - } - - // block reference - elseif ($node instanceof BlockReferenceNode || $node instanceof BlockReferenceExpression) { - $this->addLoopToCurrent(); - } - - // include without the only attribute - elseif ($node instanceof IncludeNode && !$node->getAttribute('only')) { - $this->addLoopToAll(); - } - - // include function without the with_context=false parameter - elseif ($node instanceof FunctionExpression - && 'include' === $node->getAttribute('name') - && (!$node->getNode('arguments')->hasNode('with_context') - || false !== $node->getNode('arguments')->getNode('with_context')->getAttribute('value') - ) - ) { - $this->addLoopToAll(); - } - - // the loop variable is referenced via an attribute - elseif ($node instanceof GetAttrExpression - && (!$node->getNode('attribute') instanceof ConstantExpression - || 'parent' === $node->getNode('attribute')->getAttribute('value') - ) - && (true === $this->loops[0]->getAttribute('with_loop') - || ($node->getNode('node') instanceof NameExpression - && 'loop' === $node->getNode('node')->getAttribute('name') - ) - ) - ) { - $this->addLoopToAll(); - } - } - - /** - * Optimizes "for" tag by removing the "loop" variable creation whenever possible. - */ - protected function leaveOptimizeFor(\Twig_NodeInterface $node, Environment $env) - { - if ($node instanceof ForNode) { - array_shift($this->loops); - array_shift($this->loopsTargets); - array_shift($this->loopsTargets); - } - } - - protected function addLoopToCurrent() - { - $this->loops[0]->setAttribute('with_loop', true); - } - - protected function addLoopToAll() - { - foreach ($this->loops as $loop) { - $loop->setAttribute('with_loop', true); - } - } - - public function getPriority() - { - return 255; - } -} - -class_alias('Twig\NodeVisitor\OptimizerNodeVisitor', 'Twig_NodeVisitor_Optimizer'); diff --git a/application/third_party/Twig/NodeVisitor/SafeAnalysisNodeVisitor.php b/application/third_party/Twig/NodeVisitor/SafeAnalysisNodeVisitor.php deleted file mode 100644 index 97a7a3e6eeb..00000000000 --- a/application/third_party/Twig/NodeVisitor/SafeAnalysisNodeVisitor.php +++ /dev/null @@ -1,164 +0,0 @@ -safeVars = $safeVars; - } - - public function getSafe(\Twig_NodeInterface $node) - { - $hash = spl_object_hash($node); - if (!isset($this->data[$hash])) { - return; - } - - foreach ($this->data[$hash] as $bucket) { - if ($bucket['key'] !== $node) { - continue; - } - - if (\in_array('html_attr', $bucket['value'])) { - $bucket['value'][] = 'html'; - } - - return $bucket['value']; - } - } - - protected function setSafe(\Twig_NodeInterface $node, array $safe) - { - $hash = spl_object_hash($node); - if (isset($this->data[$hash])) { - foreach ($this->data[$hash] as &$bucket) { - if ($bucket['key'] === $node) { - $bucket['value'] = $safe; - - return; - } - } - } - $this->data[$hash][] = [ - 'key' => $node, - 'value' => $safe, - ]; - } - - protected function doEnterNode(Node $node, Environment $env) - { - return $node; - } - - protected function doLeaveNode(Node $node, Environment $env) - { - if ($node instanceof ConstantExpression) { - // constants are marked safe for all - $this->setSafe($node, ['all']); - } elseif ($node instanceof BlockReferenceExpression) { - // blocks are safe by definition - $this->setSafe($node, ['all']); - } elseif ($node instanceof ParentExpression) { - // parent block is safe by definition - $this->setSafe($node, ['all']); - } elseif ($node instanceof ConditionalExpression) { - // intersect safeness of both operands - $safe = $this->intersectSafe($this->getSafe($node->getNode('expr2')), $this->getSafe($node->getNode('expr3'))); - $this->setSafe($node, $safe); - } elseif ($node instanceof FilterExpression) { - // filter expression is safe when the filter is safe - $name = $node->getNode('filter')->getAttribute('value'); - $args = $node->getNode('arguments'); - if (false !== $filter = $env->getFilter($name)) { - $safe = $filter->getSafe($args); - if (null === $safe) { - $safe = $this->intersectSafe($this->getSafe($node->getNode('node')), $filter->getPreservesSafety()); - } - $this->setSafe($node, $safe); - } else { - $this->setSafe($node, []); - } - } elseif ($node instanceof FunctionExpression) { - // function expression is safe when the function is safe - $name = $node->getAttribute('name'); - $args = $node->getNode('arguments'); - $function = $env->getFunction($name); - if (false !== $function) { - $this->setSafe($node, $function->getSafe($args)); - } else { - $this->setSafe($node, []); - } - } elseif ($node instanceof MethodCallExpression) { - if ($node->getAttribute('safe')) { - $this->setSafe($node, ['all']); - } else { - $this->setSafe($node, []); - } - } elseif ($node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression) { - $name = $node->getNode('node')->getAttribute('name'); - // attributes on template instances are safe - if ('_self' == $name || \in_array($name, $this->safeVars)) { - $this->setSafe($node, ['all']); - } else { - $this->setSafe($node, []); - } - } else { - $this->setSafe($node, []); - } - - return $node; - } - - protected function intersectSafe(array $a = null, array $b = null) - { - if (null === $a || null === $b) { - return []; - } - - if (\in_array('all', $a)) { - return $b; - } - - if (\in_array('all', $b)) { - return $a; - } - - return array_intersect($a, $b); - } - - public function getPriority() - { - return 0; - } -} - -class_alias('Twig\NodeVisitor\SafeAnalysisNodeVisitor', 'Twig_NodeVisitor_SafeAnalysis'); diff --git a/application/third_party/Twig/NodeVisitor/SandboxNodeVisitor.php b/application/third_party/Twig/NodeVisitor/SandboxNodeVisitor.php deleted file mode 100644 index c9403398f09..00000000000 --- a/application/third_party/Twig/NodeVisitor/SandboxNodeVisitor.php +++ /dev/null @@ -1,137 +0,0 @@ - - */ -class SandboxNodeVisitor extends AbstractNodeVisitor -{ - protected $inAModule = false; - protected $tags; - protected $filters; - protected $functions; - - private $needsToStringWrap = false; - - protected function doEnterNode(Node $node, Environment $env) - { - if ($node instanceof ModuleNode) { - $this->inAModule = true; - $this->tags = []; - $this->filters = []; - $this->functions = []; - - return $node; - } elseif ($this->inAModule) { - // look for tags - if ($node->getNodeTag() && !isset($this->tags[$node->getNodeTag()])) { - $this->tags[$node->getNodeTag()] = $node; - } - - // look for filters - if ($node instanceof FilterExpression && !isset($this->filters[$node->getNode('filter')->getAttribute('value')])) { - $this->filters[$node->getNode('filter')->getAttribute('value')] = $node; - } - - // look for functions - if ($node instanceof FunctionExpression && !isset($this->functions[$node->getAttribute('name')])) { - $this->functions[$node->getAttribute('name')] = $node; - } - - // the .. operator is equivalent to the range() function - if ($node instanceof RangeBinary && !isset($this->functions['range'])) { - $this->functions['range'] = $node; - } - - if ($node instanceof PrintNode) { - $this->needsToStringWrap = true; - $this->wrapNode($node, 'expr'); - } - - if ($node instanceof SetNode && !$node->getAttribute('capture')) { - $this->needsToStringWrap = true; - } - - // wrap outer nodes that can implicitly call __toString() - if ($this->needsToStringWrap) { - if ($node instanceof ConcatBinary) { - $this->wrapNode($node, 'left'); - $this->wrapNode($node, 'right'); - } - if ($node instanceof FilterExpression) { - $this->wrapNode($node, 'node'); - $this->wrapArrayNode($node, 'arguments'); - } - if ($node instanceof FunctionExpression) { - $this->wrapArrayNode($node, 'arguments'); - } - } - } - - return $node; - } - - protected function doLeaveNode(Node $node, Environment $env) - { - if ($node instanceof ModuleNode) { - $this->inAModule = false; - - $node->getNode('constructor_end')->setNode('_security_check', new Node([new CheckSecurityNode($this->filters, $this->tags, $this->functions), $node->getNode('display_start')])); - } elseif ($this->inAModule) { - if ($node instanceof PrintNode || $node instanceof SetNode) { - $this->needsToStringWrap = false; - } - } - - return $node; - } - - private function wrapNode(Node $node, $name) - { - $expr = $node->getNode($name); - if ($expr instanceof NameExpression || $expr instanceof GetAttrExpression) { - $node->setNode($name, new CheckToStringNode($expr)); - } - } - - private function wrapArrayNode(Node $node, $name) - { - $args = $node->getNode($name); - foreach ($args as $name => $_) { - $this->wrapNode($args, $name); - } - } - - public function getPriority() - { - return 0; - } -} - -class_alias('Twig\NodeVisitor\SandboxNodeVisitor', 'Twig_NodeVisitor_Sandbox'); diff --git a/application/third_party/Twig/Parser.php b/application/third_party/Twig/Parser.php index 0ea102cc811..53ae38f8db9 100644 --- a/application/third_party/Twig/Parser.php +++ b/application/third_party/Twig/Parser.php @@ -3,38 +3,21 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier - * (c) Armin Ronacher + * (c) 2009 Fabien Potencier + * (c) 2009 Armin Ronacher * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\Error\SyntaxError; -use Twig\Node\BlockNode; -use Twig\Node\BlockReferenceNode; -use Twig\Node\BodyNode; -use Twig\Node\Expression\AbstractExpression; -use Twig\Node\MacroNode; -use Twig\Node\ModuleNode; -use Twig\Node\Node; -use Twig\Node\NodeCaptureInterface; -use Twig\Node\NodeOutputInterface; -use Twig\Node\PrintNode; -use Twig\Node\TextNode; -use Twig\NodeVisitor\NodeVisitorInterface; -use Twig\TokenParser\TokenParserInterface; - /** * Default parser implementation. * * @author Fabien Potencier */ -class Parser implements \Twig_ParserInterface +class Twig_Parser implements Twig_ParserInterface { - protected $stack = []; + protected $stack = array(); protected $stream; protected $parent; protected $handlers; @@ -47,10 +30,9 @@ class Parser implements \Twig_ParserInterface protected $reservedMacroNames; protected $importedSymbols; protected $traits; - protected $embeddedTemplates = []; - private $varNameSalt = 0; + protected $embeddedTemplates = array(); - public function __construct(Environment $env) + public function __construct(Twig_Environment $env) { $this->env = $env; } @@ -67,7 +49,7 @@ public function getEnvironment() public function getVarName() { - return sprintf('__internal_%s', hash('sha256', __METHOD__.$this->stream->getSourceContext()->getCode().$this->varNameSalt++)); + return sprintf('__internal_%s', hash('sha256', uniqid(mt_rand(), true), false)); } /** @@ -80,12 +62,15 @@ public function getFilename() return $this->stream->getSourceContext()->getName(); } - public function parse(TokenStream $stream, $test = null, $dropNeedle = false) + /** + * {@inheritdoc} + */ + public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false) { // push all variables into the stack to keep the current state of the parser // using get_object_vars() instead of foreach would lead to https://bugs.php.net/71336 // This hack can be removed when min version if PHP 7.0 - $vars = []; + $vars = array(); foreach ($this as $k => $v) { $vars[$k] = $v; } @@ -105,26 +90,25 @@ public function parse(TokenStream $stream, $test = null, $dropNeedle = false) } if (null === $this->expressionParser) { - $this->expressionParser = new ExpressionParser($this, $this->env); + $this->expressionParser = new Twig_ExpressionParser($this, $this->env); } $this->stream = $stream; $this->parent = null; - $this->blocks = []; - $this->macros = []; - $this->traits = []; - $this->blockStack = []; - $this->importedSymbols = [[]]; - $this->embeddedTemplates = []; - $this->varNameSalt = 0; + $this->blocks = array(); + $this->macros = array(); + $this->traits = array(); + $this->blockStack = array(); + $this->importedSymbols = array(array()); + $this->embeddedTemplates = array(); try { $body = $this->subparse($test, $dropNeedle); if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) { - $body = new Node(); + $body = new Twig_Node(); } - } catch (SyntaxError $e) { + } catch (Twig_Error_Syntax $e) { if (!$e->getSourceContext()) { $e->setSourceContext($this->stream->getSourceContext()); } @@ -136,9 +120,9 @@ public function parse(TokenStream $stream, $test = null, $dropNeedle = false) throw $e; } - $node = new ModuleNode(new BodyNode([$body]), $this->parent, new Node($this->blocks), new Node($this->macros), new Node($this->traits), $this->embeddedTemplates, $stream->getSourceContext()); + $node = new Twig_Node_Module(new Twig_Node_Body(array($body)), $this->parent, new Twig_Node($this->blocks), new Twig_Node($this->macros), new Twig_Node($this->traits), $this->embeddedTemplates, $stream->getSourceContext()); - $traverser = new NodeTraverser($this->env, $this->visitors); + $traverser = new Twig_NodeTraverser($this->env, $this->visitors); $node = $traverser->traverse($node); @@ -153,51 +137,51 @@ public function parse(TokenStream $stream, $test = null, $dropNeedle = false) public function subparse($test, $dropNeedle = false) { $lineno = $this->getCurrentToken()->getLine(); - $rv = []; + $rv = array(); while (!$this->stream->isEOF()) { switch ($this->getCurrentToken()->getType()) { - case Token::TEXT_TYPE: + case Twig_Token::TEXT_TYPE: $token = $this->stream->next(); - $rv[] = new TextNode($token->getValue(), $token->getLine()); + $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine()); break; - case Token::VAR_START_TYPE: + case Twig_Token::VAR_START_TYPE: $token = $this->stream->next(); $expr = $this->expressionParser->parseExpression(); - $this->stream->expect(Token::VAR_END_TYPE); - $rv[] = new PrintNode($expr, $token->getLine()); + $this->stream->expect(Twig_Token::VAR_END_TYPE); + $rv[] = new Twig_Node_Print($expr, $token->getLine()); break; - case Token::BLOCK_START_TYPE: + case Twig_Token::BLOCK_START_TYPE: $this->stream->next(); $token = $this->getCurrentToken(); - if (Token::NAME_TYPE !== $token->getType()) { - throw new SyntaxError('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext()); + if ($token->getType() !== Twig_Token::NAME_TYPE) { + throw new Twig_Error_Syntax('A block must start with a tag name.', $token->getLine(), $this->stream->getSourceContext()); } - if (null !== $test && \call_user_func($test, $token)) { + if (null !== $test && call_user_func($test, $token)) { if ($dropNeedle) { $this->stream->next(); } - if (1 === \count($rv)) { + if (1 === count($rv)) { return $rv[0]; } - return new Node($rv, [], $lineno); + return new Twig_Node($rv, array(), $lineno); } $subparser = $this->handlers->getTokenParser($token->getValue()); if (null === $subparser) { if (null !== $test) { - $e = new SyntaxError(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); + $e = new Twig_Error_Syntax(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); - if (\is_array($test) && isset($test[0]) && $test[0] instanceof TokenParserInterface) { + if (is_array($test) && isset($test[0]) && $test[0] instanceof Twig_TokenParserInterface) { $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno)); } } else { - $e = new SyntaxError(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); + $e = new Twig_Error_Syntax(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); $e->addSuggestions($token->getValue(), array_keys($this->env->getTags())); } @@ -213,15 +197,15 @@ public function subparse($test, $dropNeedle = false) break; default: - throw new SyntaxError('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext()); + throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext()); } } - if (1 === \count($rv)) { + if (1 === count($rv)) { return $rv[0]; } - return new Node($rv, [], $lineno); + return new Twig_Node($rv, array(), $lineno); } /** @@ -237,7 +221,7 @@ public function addHandler($name, $class) /** * @deprecated since 1.27 (to be removed in 2.0) */ - public function addNodeVisitor(NodeVisitorInterface $visitor) + public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED); @@ -251,7 +235,7 @@ public function getBlockStack() public function peekBlockStack() { - return isset($this->blockStack[\count($this->blockStack) - 1]) ? $this->blockStack[\count($this->blockStack) - 1] : null; + return $this->blockStack[count($this->blockStack) - 1]; } public function popBlockStack() @@ -274,9 +258,9 @@ public function getBlock($name) return $this->blocks[$name]; } - public function setBlock($name, BlockNode $value) + public function setBlock($name, Twig_Node_Block $value) { - $this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine()); + $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getTemplateLine()); } public function hasMacro($name) @@ -284,10 +268,10 @@ public function hasMacro($name) return isset($this->macros[$name]); } - public function setMacro($name, MacroNode $node) + public function setMacro($name, Twig_Node_Macro $node) { if ($this->isReservedMacroName($name)) { - throw new SyntaxError(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword.', $name), $node->getTemplateLine(), $this->stream->getSourceContext()); + throw new Twig_Error_Syntax(sprintf('"%s" cannot be used as a macro name as it is a reserved keyword.', $name), $node->getTemplateLine(), $this->stream->getSourceContext()); } $this->macros[$name] = $node; @@ -296,8 +280,8 @@ public function setMacro($name, MacroNode $node) public function isReservedMacroName($name) { if (null === $this->reservedMacroNames) { - $this->reservedMacroNames = []; - $r = new \ReflectionClass($this->env->getBaseTemplateClass()); + $this->reservedMacroNames = array(); + $r = new ReflectionClass($this->env->getBaseTemplateClass()); foreach ($r->getMethods() as $method) { $methodName = strtolower($method->getName()); @@ -307,7 +291,7 @@ public function isReservedMacroName($name) } } - return \in_array(strtolower($name), $this->reservedMacroNames); + return in_array(strtolower($name), $this->reservedMacroNames); } public function addTrait($trait) @@ -317,46 +301,38 @@ public function addTrait($trait) public function hasTraits() { - return \count($this->traits) > 0; + return count($this->traits) > 0; } - public function embedTemplate(ModuleNode $template) + public function embedTemplate(Twig_Node_Module $template) { $template->setIndex(mt_rand()); $this->embeddedTemplates[] = $template; } - public function addImportedSymbol($type, $alias, $name = null, AbstractExpression $node = null) + public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression $node = null) { - $this->importedSymbols[0][$type][$alias] = ['name' => $name, 'node' => $node]; + $this->importedSymbols[0][$type][$alias] = array('name' => $name, 'node' => $node); } public function getImportedSymbol($type, $alias) { - if (null !== $this->peekBlockStack()) { - foreach ($this->importedSymbols as $functions) { - if (isset($functions[$type][$alias])) { - if (\count($this->blockStack) > 1) { - return null; - } - - return $functions[$type][$alias]; - } + foreach ($this->importedSymbols as $functions) { + if (isset($functions[$type][$alias])) { + return $functions[$type][$alias]; } - } else { - return isset($this->importedSymbols[0][$type][$alias]) ? $this->importedSymbols[0][$type][$alias] : null; } } public function isMainScope() { - return 1 === \count($this->importedSymbols); + return 1 === count($this->importedSymbols); } public function pushLocalScope() { - array_unshift($this->importedSymbols, []); + array_unshift($this->importedSymbols, array()); } public function popLocalScope() @@ -365,7 +341,7 @@ public function popLocalScope() } /** - * @return ExpressionParser + * @return Twig_ExpressionParser */ public function getExpressionParser() { @@ -383,7 +359,7 @@ public function setParent($parent) } /** - * @return TokenStream + * @return Twig_TokenStream */ public function getStream() { @@ -391,38 +367,34 @@ public function getStream() } /** - * @return Token + * @return Twig_Token */ public function getCurrentToken() { return $this->stream->getCurrent(); } - protected function filterBodyNodes(\Twig_NodeInterface $node) + protected function filterBodyNodes(Twig_NodeInterface $node) { // check that the body does not contain non-empty output nodes if ( - ($node instanceof TextNode && !ctype_space($node->getAttribute('data'))) + ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data'))) || - (!$node instanceof TextNode && !$node instanceof BlockReferenceNode && $node instanceof NodeOutputInterface) + (!$node instanceof Twig_Node_Text && !$node instanceof Twig_Node_BlockReference && $node instanceof Twig_NodeOutputInterface) ) { - if (false !== strpos((string) $node, \chr(0xEF).\chr(0xBB).\chr(0xBF))) { - $t = substr($node->getAttribute('data'), 3); - if ('' === $t || ctype_space($t)) { - // bypass empty nodes starting with a BOM - return; - } + if (false !== strpos((string) $node, chr(0xEF).chr(0xBB).chr(0xBF))) { + throw new Twig_Error_Syntax('A template that extends another one cannot start with a byte order mark (BOM); it must be removed.', $node->getTemplateLine(), $this->stream->getSourceContext()); } - throw new SyntaxError('A template that extends another one cannot include content outside Twig blocks. Did you forget to put the content inside a {% block %} tag?', $node->getTemplateLine(), $this->stream->getSourceContext()); + throw new Twig_Error_Syntax('A template that extends another one cannot include contents outside Twig blocks. Did you forget to put the contents inside a {% block %} tag?', $node->getTemplateLine(), $this->stream->getSourceContext()); } - // bypass nodes that will "capture" the output - if ($node instanceof NodeCaptureInterface) { + // bypass "set" nodes as they "capture" the output + if ($node instanceof Twig_Node_Set) { return $node; } - if ($node instanceof NodeOutputInterface) { + if ($node instanceof Twig_NodeOutputInterface) { return; } @@ -435,5 +407,3 @@ protected function filterBodyNodes(\Twig_NodeInterface $node) return $node; } } - -class_alias('Twig\Parser', 'Twig_Parser'); diff --git a/application/third_party/Twig/Profiler/Dumper/BaseDumper.php b/application/third_party/Twig/Profiler/Dumper/BaseDumper.php deleted file mode 100644 index d965dc75421..00000000000 --- a/application/third_party/Twig/Profiler/Dumper/BaseDumper.php +++ /dev/null @@ -1,65 +0,0 @@ - - */ -abstract class BaseDumper -{ - private $root; - - public function dump(Profile $profile) - { - return $this->dumpProfile($profile); - } - - abstract protected function formatTemplate(Profile $profile, $prefix); - - abstract protected function formatNonTemplate(Profile $profile, $prefix); - - abstract protected function formatTime(Profile $profile, $percent); - - private function dumpProfile(Profile $profile, $prefix = '', $sibling = false) - { - if ($profile->isRoot()) { - $this->root = $profile->getDuration(); - $start = $profile->getName(); - } else { - if ($profile->isTemplate()) { - $start = $this->formatTemplate($profile, $prefix); - } else { - $start = $this->formatNonTemplate($profile, $prefix); - } - $prefix .= $sibling ? '│ ' : ' '; - } - - $percent = $this->root ? $profile->getDuration() / $this->root * 100 : 0; - - if ($profile->getDuration() * 1000 < 1) { - $str = $start."\n"; - } else { - $str = sprintf("%s %s\n", $start, $this->formatTime($profile, $percent)); - } - - $nCount = \count($profile->getProfiles()); - foreach ($profile as $i => $p) { - $str .= $this->dumpProfile($p, $prefix, $i + 1 !== $nCount); - } - - return $str; - } -} - -class_alias('Twig\Profiler\Dumper\BaseDumper', 'Twig_Profiler_Dumper_Base'); diff --git a/application/third_party/Twig/Profiler/Dumper/BlackfireDumper.php b/application/third_party/Twig/Profiler/Dumper/BlackfireDumper.php deleted file mode 100644 index a1c3c7bce69..00000000000 --- a/application/third_party/Twig/Profiler/Dumper/BlackfireDumper.php +++ /dev/null @@ -1,76 +0,0 @@ - - * - * @final - */ -class BlackfireDumper -{ - public function dump(Profile $profile) - { - $data = []; - $this->dumpProfile('main()', $profile, $data); - $this->dumpChildren('main()', $profile, $data); - - $start = sprintf('%f', microtime(true)); - $str = << $values) { - $str .= "{$name}//{$values['ct']} {$values['wt']} {$values['mu']} {$values['pmu']}\n"; - } - - return $str; - } - - private function dumpChildren($parent, Profile $profile, &$data) - { - foreach ($profile as $p) { - if ($p->isTemplate()) { - $name = $p->getTemplate(); - } else { - $name = sprintf('%s::%s(%s)', $p->getTemplate(), $p->getType(), $p->getName()); - } - $this->dumpProfile(sprintf('%s==>%s', $parent, $name), $p, $data); - $this->dumpChildren($name, $p, $data); - } - } - - private function dumpProfile($edge, Profile $profile, &$data) - { - if (isset($data[$edge])) { - ++$data[$edge]['ct']; - $data[$edge]['wt'] += floor($profile->getDuration() * 1000000); - $data[$edge]['mu'] += $profile->getMemoryUsage(); - $data[$edge]['pmu'] += $profile->getPeakMemoryUsage(); - } else { - $data[$edge] = [ - 'ct' => 1, - 'wt' => floor($profile->getDuration() * 1000000), - 'mu' => $profile->getMemoryUsage(), - 'pmu' => $profile->getPeakMemoryUsage(), - ]; - } - } -} - -class_alias('Twig\Profiler\Dumper\BlackfireDumper', 'Twig_Profiler_Dumper_Blackfire'); diff --git a/application/third_party/Twig/Profiler/Dumper/HtmlDumper.php b/application/third_party/Twig/Profiler/Dumper/HtmlDumper.php deleted file mode 100644 index c70b405b30b..00000000000 --- a/application/third_party/Twig/Profiler/Dumper/HtmlDumper.php +++ /dev/null @@ -1,51 +0,0 @@ - - * - * @final - */ -class HtmlDumper extends BaseDumper -{ - private static $colors = [ - 'block' => '#dfd', - 'macro' => '#ddf', - 'template' => '#ffd', - 'big' => '#d44', - ]; - - public function dump(Profile $profile) - { - return '
'.parent::dump($profile).'
'; - } - - protected function formatTemplate(Profile $profile, $prefix) - { - return sprintf('%s└ %s', $prefix, self::$colors['template'], $profile->getTemplate()); - } - - protected function formatNonTemplate(Profile $profile, $prefix) - { - return sprintf('%s└ %s::%s(%s)', $prefix, $profile->getTemplate(), $profile->getType(), isset(self::$colors[$profile->getType()]) ? self::$colors[$profile->getType()] : 'auto', $profile->getName()); - } - - protected function formatTime(Profile $profile, $percent) - { - return sprintf('%.2fms/%.0f%%', $percent > 20 ? self::$colors['big'] : 'auto', $profile->getDuration() * 1000, $percent); - } -} - -class_alias('Twig\Profiler\Dumper\HtmlDumper', 'Twig_Profiler_Dumper_Html'); diff --git a/application/third_party/Twig/Profiler/Dumper/TextDumper.php b/application/third_party/Twig/Profiler/Dumper/TextDumper.php deleted file mode 100644 index c6b515891e7..00000000000 --- a/application/third_party/Twig/Profiler/Dumper/TextDumper.php +++ /dev/null @@ -1,39 +0,0 @@ - - * - * @final - */ -class TextDumper extends BaseDumper -{ - protected function formatTemplate(Profile $profile, $prefix) - { - return sprintf('%s└ %s', $prefix, $profile->getTemplate()); - } - - protected function formatNonTemplate(Profile $profile, $prefix) - { - return sprintf('%s└ %s::%s(%s)', $prefix, $profile->getTemplate(), $profile->getType(), $profile->getName()); - } - - protected function formatTime(Profile $profile, $percent) - { - return sprintf('%.2fms/%.0f%%', $profile->getDuration() * 1000, $percent); - } -} - -class_alias('Twig\Profiler\Dumper\TextDumper', 'Twig_Profiler_Dumper_Text'); diff --git a/application/third_party/Twig/Profiler/Node/EnterProfileNode.php b/application/third_party/Twig/Profiler/Node/EnterProfileNode.php deleted file mode 100644 index 8ffd3dc78c6..00000000000 --- a/application/third_party/Twig/Profiler/Node/EnterProfileNode.php +++ /dev/null @@ -1,44 +0,0 @@ - - */ -class EnterProfileNode extends Node -{ - public function __construct($extensionName, $type, $name, $varName) - { - parent::__construct([], ['extension_name' => $extensionName, 'name' => $name, 'type' => $type, 'var_name' => $varName]); - } - - public function compile(Compiler $compiler) - { - $compiler - ->write(sprintf('$%s = $this->env->getExtension(', $this->getAttribute('var_name'))) - ->repr($this->getAttribute('extension_name')) - ->raw(");\n") - ->write(sprintf('$%s->enter($%s = new \Twig\Profiler\Profile($this->getTemplateName(), ', $this->getAttribute('var_name'), $this->getAttribute('var_name').'_prof')) - ->repr($this->getAttribute('type')) - ->raw(', ') - ->repr($this->getAttribute('name')) - ->raw("));\n\n") - ; - } -} - -class_alias('Twig\Profiler\Node\EnterProfileNode', 'Twig_Profiler_Node_EnterProfile'); diff --git a/application/third_party/Twig/Profiler/Node/LeaveProfileNode.php b/application/third_party/Twig/Profiler/Node/LeaveProfileNode.php deleted file mode 100644 index 3b7a74d0263..00000000000 --- a/application/third_party/Twig/Profiler/Node/LeaveProfileNode.php +++ /dev/null @@ -1,38 +0,0 @@ - - */ -class LeaveProfileNode extends Node -{ - public function __construct($varName) - { - parent::__construct([], ['var_name' => $varName]); - } - - public function compile(Compiler $compiler) - { - $compiler - ->write("\n") - ->write(sprintf("\$%s->leave(\$%s);\n\n", $this->getAttribute('var_name'), $this->getAttribute('var_name').'_prof')) - ; - } -} - -class_alias('Twig\Profiler\Node\LeaveProfileNode', 'Twig_Profiler_Node_LeaveProfile'); diff --git a/application/third_party/Twig/Profiler/NodeVisitor/ProfilerNodeVisitor.php b/application/third_party/Twig/Profiler/NodeVisitor/ProfilerNodeVisitor.php deleted file mode 100644 index 41ca9e1f297..00000000000 --- a/application/third_party/Twig/Profiler/NodeVisitor/ProfilerNodeVisitor.php +++ /dev/null @@ -1,80 +0,0 @@ - - * - * @final - */ -class ProfilerNodeVisitor extends AbstractNodeVisitor -{ - private $extensionName; - - public function __construct($extensionName) - { - $this->extensionName = $extensionName; - } - - protected function doEnterNode(Node $node, Environment $env) - { - return $node; - } - - protected function doLeaveNode(Node $node, Environment $env) - { - if ($node instanceof ModuleNode) { - $varName = $this->getVarName(); - $node->setNode('display_start', new Node([new EnterProfileNode($this->extensionName, Profile::TEMPLATE, $node->getTemplateName(), $varName), $node->getNode('display_start')])); - $node->setNode('display_end', new Node([new LeaveProfileNode($varName), $node->getNode('display_end')])); - } elseif ($node instanceof BlockNode) { - $varName = $this->getVarName(); - $node->setNode('body', new BodyNode([ - new EnterProfileNode($this->extensionName, Profile::BLOCK, $node->getAttribute('name'), $varName), - $node->getNode('body'), - new LeaveProfileNode($varName), - ])); - } elseif ($node instanceof MacroNode) { - $varName = $this->getVarName(); - $node->setNode('body', new BodyNode([ - new EnterProfileNode($this->extensionName, Profile::MACRO, $node->getAttribute('name'), $varName), - $node->getNode('body'), - new LeaveProfileNode($varName), - ])); - } - - return $node; - } - - private function getVarName() - { - return sprintf('__internal_%s', hash('sha256', $this->extensionName)); - } - - public function getPriority() - { - return 0; - } -} - -class_alias('Twig\Profiler\NodeVisitor\ProfilerNodeVisitor', 'Twig_Profiler_NodeVisitor_Profiler'); diff --git a/application/third_party/Twig/Profiler/Profile.php b/application/third_party/Twig/Profiler/Profile.php index d83da40af38..93bdbb62ba9 100644 --- a/application/third_party/Twig/Profiler/Profile.php +++ b/application/third_party/Twig/Profiler/Profile.php @@ -3,20 +3,18 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2015 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Profiler; - /** * @author Fabien Potencier * * @final */ -class Profile implements \IteratorAggregate, \Serializable +class Twig_Profiler_Profile implements IteratorAggregate, Serializable { const ROOT = 'ROOT'; const BLOCK = 'block'; @@ -26,9 +24,9 @@ class Profile implements \IteratorAggregate, \Serializable private $template; private $name; private $type; - private $starts = []; - private $ends = []; - private $profiles = []; + private $starts = array(); + private $ends = array(); + private $profiles = array(); public function __construct($template = 'main', $type = self::ROOT, $name = 'main') { @@ -78,7 +76,7 @@ public function getProfiles() return $this->profiles; } - public function addProfile(self $profile) + public function addProfile(Twig_Profiler_Profile $profile) { $this->profiles[] = $profile; } @@ -86,7 +84,7 @@ public function addProfile(self $profile) /** * Returns the duration in microseconds. * - * @return float + * @return int */ public function getDuration() { @@ -128,11 +126,11 @@ public function getPeakMemoryUsage() */ public function enter() { - $this->starts = [ + $this->starts = array( 'wt' => microtime(true), 'mu' => memory_get_usage(), 'pmu' => memory_get_peak_usage(), - ]; + ); } /** @@ -140,49 +138,25 @@ public function enter() */ public function leave() { - $this->ends = [ + $this->ends = array( 'wt' => microtime(true), 'mu' => memory_get_usage(), 'pmu' => memory_get_peak_usage(), - ]; - } - - public function reset() - { - $this->starts = $this->ends = $this->profiles = []; - $this->enter(); + ); } public function getIterator() { - return new \ArrayIterator($this->profiles); + return new ArrayIterator($this->profiles); } public function serialize() { - return serialize($this->__serialize()); + return serialize(array($this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles)); } public function unserialize($data) { - $this->__unserialize(unserialize($data)); - } - - /** - * @internal - */ - public function __serialize() - { - return [$this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles]; - } - - /** - * @internal - */ - public function __unserialize(array $data) - { - list($this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles) = $data; + list($this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles) = unserialize($data); } } - -class_alias('Twig\Profiler\Profile', 'Twig_Profiler_Profile'); diff --git a/application/third_party/Twig/RuntimeLoader/ContainerRuntimeLoader.php b/application/third_party/Twig/RuntimeLoader/ContainerRuntimeLoader.php deleted file mode 100644 index 04a6602f229..00000000000 --- a/application/third_party/Twig/RuntimeLoader/ContainerRuntimeLoader.php +++ /dev/null @@ -1,41 +0,0 @@ - - * @author Robin Chalas - */ -class ContainerRuntimeLoader implements RuntimeLoaderInterface -{ - private $container; - - public function __construct(ContainerInterface $container) - { - $this->container = $container; - } - - public function load($class) - { - if ($this->container->has($class)) { - return $this->container->get($class); - } - } -} - -class_alias('Twig\RuntimeLoader\ContainerRuntimeLoader', 'Twig_ContainerRuntimeLoader'); diff --git a/application/third_party/Twig/RuntimeLoader/FactoryRuntimeLoader.php b/application/third_party/Twig/RuntimeLoader/FactoryRuntimeLoader.php deleted file mode 100644 index 43b5f24ebac..00000000000 --- a/application/third_party/Twig/RuntimeLoader/FactoryRuntimeLoader.php +++ /dev/null @@ -1,41 +0,0 @@ - - */ -class FactoryRuntimeLoader implements RuntimeLoaderInterface -{ - private $map; - - /** - * @param array $map An array where keys are class names and values factory callables - */ - public function __construct($map = []) - { - $this->map = $map; - } - - public function load($class) - { - if (isset($this->map[$class])) { - $runtimeFactory = $this->map[$class]; - - return $runtimeFactory(); - } - } -} - -class_alias('Twig\RuntimeLoader\FactoryRuntimeLoader', 'Twig_FactoryRuntimeLoader'); diff --git a/application/third_party/Twig/RuntimeLoader/RuntimeLoaderInterface.php b/application/third_party/Twig/RuntimeLoader/RuntimeLoaderInterface.php deleted file mode 100644 index 4eb5ad85999..00000000000 --- a/application/third_party/Twig/RuntimeLoader/RuntimeLoaderInterface.php +++ /dev/null @@ -1,31 +0,0 @@ - - */ -interface RuntimeLoaderInterface -{ - /** - * Creates the runtime implementation of a Twig element (filter/function/test). - * - * @param string $class A runtime class - * - * @return object|null The runtime instance or null if the loader does not know how to create the runtime for this class - */ - public function load($class); -} - -class_alias('Twig\RuntimeLoader\RuntimeLoaderInterface', 'Twig_RuntimeLoaderInterface'); diff --git a/application/third_party/Twig/Sandbox/SecurityError.php b/application/third_party/Twig/Sandbox/SecurityError.php index 5f96d46bd84..015bfaea22b 100644 --- a/application/third_party/Twig/Sandbox/SecurityError.php +++ b/application/third_party/Twig/Sandbox/SecurityError.php @@ -3,23 +3,17 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - -use Twig\Error\Error; - /** * Exception thrown when a security error occurs at runtime. * * @author Fabien Potencier */ -class SecurityError extends Error +class Twig_Sandbox_SecurityError extends Twig_Error { } - -class_alias('Twig\Sandbox\SecurityError', 'Twig_Sandbox_SecurityError'); diff --git a/application/third_party/Twig/Sandbox/SecurityNotAllowedFilterError.php b/application/third_party/Twig/Sandbox/SecurityNotAllowedFilterError.php index fa0fdee72f3..99faba9dd37 100644 --- a/application/third_party/Twig/Sandbox/SecurityNotAllowedFilterError.php +++ b/application/third_party/Twig/Sandbox/SecurityNotAllowedFilterError.php @@ -3,24 +3,22 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - /** * Exception thrown when a not allowed filter is used in a template. * * @author Martin Hasoň */ -class SecurityNotAllowedFilterError extends SecurityError +class Twig_Sandbox_SecurityNotAllowedFilterError extends Twig_Sandbox_SecurityError { private $filterName; - public function __construct($message, $functionName, $lineno = -1, $filename = null, \Exception $previous = null) + public function __construct($message, $functionName, $lineno = -1, $filename = null, Exception $previous = null) { parent::__construct($message, $lineno, $filename, $previous); $this->filterName = $functionName; @@ -31,5 +29,3 @@ public function getFilterName() return $this->filterName; } } - -class_alias('Twig\Sandbox\SecurityNotAllowedFilterError', 'Twig_Sandbox_SecurityNotAllowedFilterError'); diff --git a/application/third_party/Twig/Sandbox/SecurityNotAllowedFunctionError.php b/application/third_party/Twig/Sandbox/SecurityNotAllowedFunctionError.php index 8f23f93acd9..05cf488af89 100644 --- a/application/third_party/Twig/Sandbox/SecurityNotAllowedFunctionError.php +++ b/application/third_party/Twig/Sandbox/SecurityNotAllowedFunctionError.php @@ -3,24 +3,22 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - /** * Exception thrown when a not allowed function is used in a template. * * @author Martin Hasoň */ -class SecurityNotAllowedFunctionError extends SecurityError +class Twig_Sandbox_SecurityNotAllowedFunctionError extends Twig_Sandbox_SecurityError { private $functionName; - public function __construct($message, $functionName, $lineno = -1, $filename = null, \Exception $previous = null) + public function __construct($message, $functionName, $lineno = -1, $filename = null, Exception $previous = null) { parent::__construct($message, $lineno, $filename, $previous); $this->functionName = $functionName; @@ -31,5 +29,3 @@ public function getFunctionName() return $this->functionName; } } - -class_alias('Twig\Sandbox\SecurityNotAllowedFunctionError', 'Twig_Sandbox_SecurityNotAllowedFunctionError'); diff --git a/application/third_party/Twig/Sandbox/SecurityNotAllowedMethodError.php b/application/third_party/Twig/Sandbox/SecurityNotAllowedMethodError.php index 62e13f49bde..5b352d952f7 100644 --- a/application/third_party/Twig/Sandbox/SecurityNotAllowedMethodError.php +++ b/application/third_party/Twig/Sandbox/SecurityNotAllowedMethodError.php @@ -3,25 +3,23 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - /** * Exception thrown when a not allowed class method is used in a template. * * @author Kit Burton-Senior */ -class SecurityNotAllowedMethodError extends SecurityError +class Twig_Sandbox_SecurityNotAllowedMethodError extends Twig_Sandbox_SecurityError { private $className; private $methodName; - public function __construct($message, $className, $methodName, $lineno = -1, $filename = null, \Exception $previous = null) + public function __construct($message, $className, $methodName, $lineno = -1, $filename = null, Exception $previous = null) { parent::__construct($message, $lineno, $filename, $previous); $this->className = $className; @@ -38,5 +36,3 @@ public function getMethodName() return $this->methodName; } } - -class_alias('Twig\Sandbox\SecurityNotAllowedMethodError', 'Twig_Sandbox_SecurityNotAllowedMethodError'); diff --git a/application/third_party/Twig/Sandbox/SecurityNotAllowedPropertyError.php b/application/third_party/Twig/Sandbox/SecurityNotAllowedPropertyError.php index 3bf530574f8..8b4cbc35baa 100644 --- a/application/third_party/Twig/Sandbox/SecurityNotAllowedPropertyError.php +++ b/application/third_party/Twig/Sandbox/SecurityNotAllowedPropertyError.php @@ -3,25 +3,23 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - /** * Exception thrown when a not allowed class property is used in a template. * * @author Kit Burton-Senior */ -class SecurityNotAllowedPropertyError extends SecurityError +class Twig_Sandbox_SecurityNotAllowedPropertyError extends Twig_Sandbox_SecurityError { private $className; private $propertyName; - public function __construct($message, $className, $propertyName, $lineno = -1, $filename = null, \Exception $previous = null) + public function __construct($message, $className, $propertyName, $lineno = -1, $filename = null, Exception $previous = null) { parent::__construct($message, $lineno, $filename, $previous); $this->className = $className; @@ -38,5 +36,3 @@ public function getPropertyName() return $this->propertyName; } } - -class_alias('Twig\Sandbox\SecurityNotAllowedPropertyError', 'Twig_Sandbox_SecurityNotAllowedPropertyError'); diff --git a/application/third_party/Twig/Sandbox/SecurityNotAllowedTagError.php b/application/third_party/Twig/Sandbox/SecurityNotAllowedTagError.php index de283b40cd7..b3bb5e8e2b8 100644 --- a/application/third_party/Twig/Sandbox/SecurityNotAllowedTagError.php +++ b/application/third_party/Twig/Sandbox/SecurityNotAllowedTagError.php @@ -3,24 +3,22 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - /** * Exception thrown when a not allowed tag is used in a template. * * @author Martin Hasoň */ -class SecurityNotAllowedTagError extends SecurityError +class Twig_Sandbox_SecurityNotAllowedTagError extends Twig_Sandbox_SecurityError { private $tagName; - public function __construct($message, $tagName, $lineno = -1, $filename = null, \Exception $previous = null) + public function __construct($message, $tagName, $lineno = -1, $filename = null, Exception $previous = null) { parent::__construct($message, $lineno, $filename, $previous); $this->tagName = $tagName; @@ -31,5 +29,3 @@ public function getTagName() return $this->tagName; } } - -class_alias('Twig\Sandbox\SecurityNotAllowedTagError', 'Twig_Sandbox_SecurityNotAllowedTagError'); diff --git a/application/third_party/Twig/Sandbox/SecurityPolicy.php b/application/third_party/Twig/Sandbox/SecurityPolicy.php index 31b6c348332..121fc30f658 100644 --- a/application/third_party/Twig/Sandbox/SecurityPolicy.php +++ b/application/third_party/Twig/Sandbox/SecurityPolicy.php @@ -3,16 +3,12 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - -use Twig\Markup; - /** * Represents a security policy which need to be enforced when sandbox mode is enabled. * @@ -20,7 +16,7 @@ * * @author Fabien Potencier */ -class SecurityPolicy implements SecurityPolicyInterface +class Twig_Sandbox_SecurityPolicy implements Twig_Sandbox_SecurityPolicyInterface { protected $allowedTags; protected $allowedFilters; @@ -28,7 +24,7 @@ class SecurityPolicy implements SecurityPolicyInterface protected $allowedProperties; protected $allowedFunctions; - public function __construct(array $allowedTags = [], array $allowedFilters = [], array $allowedMethods = [], array $allowedProperties = [], array $allowedFunctions = []) + public function __construct(array $allowedTags = array(), array $allowedFilters = array(), array $allowedMethods = array(), array $allowedProperties = array(), array $allowedFunctions = array()) { $this->allowedTags = $allowedTags; $this->allowedFilters = $allowedFilters; @@ -49,9 +45,9 @@ public function setAllowedFilters(array $filters) public function setAllowedMethods(array $methods) { - $this->allowedMethods = []; + $this->allowedMethods = array(); foreach ($methods as $class => $m) { - $this->allowedMethods[$class] = array_map('strtolower', \is_array($m) ? $m : [$m]); + $this->allowedMethods[$class] = array_map('strtolower', is_array($m) ? $m : array($m)); } } @@ -68,43 +64,43 @@ public function setAllowedFunctions(array $functions) public function checkSecurity($tags, $filters, $functions) { foreach ($tags as $tag) { - if (!\in_array($tag, $this->allowedTags)) { - throw new SecurityNotAllowedTagError(sprintf('Tag "%s" is not allowed.', $tag), $tag); + if (!in_array($tag, $this->allowedTags)) { + throw new Twig_Sandbox_SecurityNotAllowedTagError(sprintf('Tag "%s" is not allowed.', $tag), $tag); } } foreach ($filters as $filter) { - if (!\in_array($filter, $this->allowedFilters)) { - throw new SecurityNotAllowedFilterError(sprintf('Filter "%s" is not allowed.', $filter), $filter); + if (!in_array($filter, $this->allowedFilters)) { + throw new Twig_Sandbox_SecurityNotAllowedFilterError(sprintf('Filter "%s" is not allowed.', $filter), $filter); } } foreach ($functions as $function) { - if (!\in_array($function, $this->allowedFunctions)) { - throw new SecurityNotAllowedFunctionError(sprintf('Function "%s" is not allowed.', $function), $function); + if (!in_array($function, $this->allowedFunctions)) { + throw new Twig_Sandbox_SecurityNotAllowedFunctionError(sprintf('Function "%s" is not allowed.', $function), $function); } } } public function checkMethodAllowed($obj, $method) { - if ($obj instanceof \Twig_TemplateInterface || $obj instanceof Markup) { - return; + if ($obj instanceof Twig_TemplateInterface || $obj instanceof Twig_Markup) { + return true; } $allowed = false; $method = strtolower($method); foreach ($this->allowedMethods as $class => $methods) { if ($obj instanceof $class) { - $allowed = \in_array($method, $methods); + $allowed = in_array($method, $methods); break; } } if (!$allowed) { - $class = \get_class($obj); - throw new SecurityNotAllowedMethodError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method); + $class = get_class($obj); + throw new Twig_Sandbox_SecurityNotAllowedMethodError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method); } } @@ -113,17 +109,15 @@ public function checkPropertyAllowed($obj, $property) $allowed = false; foreach ($this->allowedProperties as $class => $properties) { if ($obj instanceof $class) { - $allowed = \in_array($property, \is_array($properties) ? $properties : [$properties]); + $allowed = in_array($property, is_array($properties) ? $properties : array($properties)); break; } } if (!$allowed) { - $class = \get_class($obj); - throw new SecurityNotAllowedPropertyError(sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $class), $class, $property); + $class = get_class($obj); + throw new Twig_Sandbox_SecurityNotAllowedPropertyError(sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $class), $class, $property); } } } - -class_alias('Twig\Sandbox\SecurityPolicy', 'Twig_Sandbox_SecurityPolicy'); diff --git a/application/third_party/Twig/Sandbox/SecurityPolicyInterface.php b/application/third_party/Twig/Sandbox/SecurityPolicyInterface.php index a31863f6c27..6ab48e3cc98 100644 --- a/application/third_party/Twig/Sandbox/SecurityPolicyInterface.php +++ b/application/third_party/Twig/Sandbox/SecurityPolicyInterface.php @@ -3,20 +3,18 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2009 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Sandbox; - /** - * Interface that all security policy classes must implements. + * Interfaces that all security policy classes must implements. * * @author Fabien Potencier */ -interface SecurityPolicyInterface +interface Twig_Sandbox_SecurityPolicyInterface { public function checkSecurity($tags, $filters, $functions); @@ -24,5 +22,3 @@ public function checkMethodAllowed($obj, $method); public function checkPropertyAllowed($obj, $method); } - -class_alias('Twig\Sandbox\SecurityPolicyInterface', 'Twig_Sandbox_SecurityPolicyInterface'); diff --git a/application/third_party/Twig/Source.php b/application/third_party/Twig/Source.php index 32a82163f4b..efe0f1497b7 100644 --- a/application/third_party/Twig/Source.php +++ b/application/third_party/Twig/Source.php @@ -3,14 +3,12 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2016 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - /** * Holds information about a non-compiled Twig template. * @@ -18,7 +16,7 @@ * * @author Fabien Potencier */ -class Source +class Twig_Source { private $code; private $name; @@ -51,5 +49,3 @@ public function getPath() return $this->path; } } - -class_alias('Twig\Source', 'Twig_Source'); diff --git a/application/third_party/Twig/Template.php b/application/third_party/Twig/Template.php index 3f7447c126c..c09ab7d732e 100644 --- a/application/third_party/Twig/Template.php +++ b/application/third_party/Twig/Template.php @@ -3,45 +3,38 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier - * (c) Armin Ronacher + * (c) 2009 Fabien Potencier + * (c) 2009 Armin Ronacher * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\Error\Error; -use Twig\Error\LoaderError; -use Twig\Error\RuntimeError; - /** * Default base class for compiled templates. * * This class is an implementation detail of how template compilation currently * works, which might change. It should never be used directly. Use $twig->load() - * instead, which returns an instance of \Twig\TemplateWrapper. + * instead, which returns an instance of Twig_TemplateWrapper. * * @author Fabien Potencier * * @internal */ -abstract class Template implements \Twig_TemplateInterface +abstract class Twig_Template implements Twig_TemplateInterface { /** * @internal */ - protected static $cache = []; + protected static $cache = array(); protected $parent; - protected $parents = []; + protected $parents = array(); protected $env; - protected $blocks = []; - protected $traits = []; - protected $sandbox; + protected $blocks = array(); + protected $traits = array(); - public function __construct(Environment $env) + public function __construct(Twig_Environment $env) { $this->env = $env; } @@ -65,10 +58,12 @@ abstract public function getTemplateName(); * Returns debug information about the template. * * @return array Debug information + * + * @internal */ public function getDebugInfo() { - return []; + return array(); } /** @@ -88,11 +83,11 @@ public function getSource() /** * Returns information about the original template source code. * - * @return Source + * @return Twig_Source */ public function getSourceContext() { - return new Source('', $this->getTemplateName()); + return new Twig_Source('', $this->getTemplateName()); } /** @@ -113,7 +108,7 @@ public function getEnvironment() * * @param array $context * - * @return \Twig_TemplateInterface|TemplateWrapper|false The parent template or false if there is no parent + * @return Twig_TemplateInterface|false The parent template or false if there is no parent * * @internal */ @@ -130,14 +125,14 @@ public function getParent(array $context) return false; } - if ($parent instanceof self || $parent instanceof TemplateWrapper) { - return $this->parents[$parent->getSourceContext()->getName()] = $parent; + if ($parent instanceof self) { + return $this->parents[$parent->getTemplateName()] = $parent; } if (!isset($this->parents[$parent])) { $this->parents[$parent] = $this->loadTemplate($parent); } - } catch (LoaderError $e) { + } catch (Twig_Error_Loader $e) { $e->setSourceContext(null); $e->guess(); @@ -166,8 +161,10 @@ public function isTraitable() * @param string $name The block name to display from the parent * @param array $context The context * @param array $blocks The current set of blocks + * + * @internal */ - public function displayParentBlock($name, array $context, array $blocks = []) + public function displayParentBlock($name, array $context, array $blocks = array()) { $name = (string) $name; @@ -176,7 +173,7 @@ public function displayParentBlock($name, array $context, array $blocks = []) } elseif (false !== $parent = $this->getParent($context)) { $parent->displayBlock($name, $context, $blocks, false); } else { - throw new RuntimeError(sprintf('The template has no parent and no traits defining the "%s" block.', $name), -1, $this->getSourceContext()); + throw new Twig_Error_Runtime(sprintf('The template has no parent and no traits defining the "%s" block.', $name), -1, $this->getSourceContext()); } } @@ -190,8 +187,10 @@ public function displayParentBlock($name, array $context, array $blocks = []) * @param array $context The context * @param array $blocks The current set of blocks * @param bool $useBlocks Whether to use the current set of blocks + * + * @internal */ - public function displayBlock($name, array $context, array $blocks = [], $useBlocks = true) + public function displayBlock($name, array $context, array $blocks = array(), $useBlocks = true) { $name = (string) $name; @@ -208,34 +207,32 @@ public function displayBlock($name, array $context, array $blocks = [], $useBloc // avoid RCEs when sandbox is enabled if (null !== $template && !$template instanceof self) { - throw new \LogicException('A block must be a method on a \Twig\Template instance.'); + throw new LogicException('A block must be a method on a Twig_Template instance.'); } if (null !== $template) { try { $template->$block($context, $blocks); - } catch (Error $e) { + } catch (Twig_Error $e) { if (!$e->getSourceContext()) { $e->setSourceContext($template->getSourceContext()); } - // this is mostly useful for \Twig\Error\LoaderError exceptions - // see \Twig\Error\LoaderError - if (-1 === $e->getTemplateLine()) { + // this is mostly useful for Twig_Error_Loader exceptions + // see Twig_Error_Loader + if (false === $e->getTemplateLine()) { + $e->setTemplateLine(-1); $e->guess(); } throw $e; - } catch (\Exception $e) { - $e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getSourceContext(), $e); - $e->guess(); - - throw $e; + } catch (Exception $e) { + throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getSourceContext(), $e); } } elseif (false !== $parent = $this->getParent($context)) { $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks), false); } else { - @trigger_error(sprintf('Silent display of undefined block "%s" in template "%s" is deprecated since version 1.29 and will throw an exception in 2.0. Use the "block(\'%s\') is defined" expression to test for block existence.', $name, $this->getTemplateName(), $name), E_USER_DEPRECATED); + @trigger_error(sprintf('Silent display of undefined block "%s" in template "%s" is deprecated since version 1.29 and will throw an exception in 2.0.', $name, $this->getTemplateName()), E_USER_DEPRECATED); } } @@ -250,14 +247,12 @@ public function displayBlock($name, array $context, array $blocks = [], $useBloc * @param array $blocks The current set of blocks * * @return string The rendered block + * + * @internal */ - public function renderParentBlock($name, array $context, array $blocks = []) + public function renderParentBlock($name, array $context, array $blocks = array()) { - if ($this->env->isDebug()) { - ob_start(); - } else { - ob_start(function () { return ''; }); - } + ob_start(); $this->displayParentBlock($name, $context, $blocks); return ob_get_clean(); @@ -275,14 +270,12 @@ public function renderParentBlock($name, array $context, array $blocks = []) * @param bool $useBlocks Whether to use the current set of blocks * * @return string The rendered block + * + * @internal */ - public function renderBlock($name, array $context, array $blocks = [], $useBlocks = true) + public function renderBlock($name, array $context, array $blocks = array(), $useBlocks = true) { - if ($this->env->isDebug()) { - ob_start(); - } else { - ob_start(function () { return ''; }); - } + ob_start(); $this->displayBlock($name, $context, $blocks, $useBlocks); return ob_get_clean(); @@ -299,8 +292,10 @@ public function renderBlock($name, array $context, array $blocks = [], $useBlock * @param array $blocks The current set of blocks * * @return bool true if the block exists, false otherwise + * + * @internal */ - public function hasBlock($name, array $context = null, array $blocks = []) + public function hasBlock($name, array $context = null, array $blocks = array()) { if (null === $context) { @trigger_error('The '.__METHOD__.' method is internal and should never be called; calling it directly is deprecated since version 1.28 and won\'t be possible anymore in 2.0.', E_USER_DEPRECATED); @@ -333,8 +328,10 @@ public function hasBlock($name, array $context = null, array $blocks = []) * @param array $blocks The current set of blocks * * @return array An array of block names + * + * @internal */ - public function getBlockNames(array $context = null, array $blocks = []) + public function getBlockNames(array $context = null, array $blocks = array()) { if (null === $context) { @trigger_error('The '.__METHOD__.' method is internal and should never be called; calling it directly is deprecated since version 1.28 and won\'t be possible anymore in 2.0.', E_USER_DEPRECATED); @@ -351,36 +348,28 @@ public function getBlockNames(array $context = null, array $blocks = []) return array_unique($names); } - /** - * @return Template|TemplateWrapper - */ protected function loadTemplate($template, $templateName = null, $line = null, $index = null) { try { - if (\is_array($template)) { + if (is_array($template)) { return $this->env->resolveTemplate($template); } - if ($template instanceof self || $template instanceof TemplateWrapper) { + if ($template instanceof self) { return $template; } - if ($template === $this->getTemplateName()) { - $class = \get_class($this); - if (false !== $pos = strrpos($class, '___', -1)) { - $class = substr($class, 0, $pos); - } - - return $this->env->loadClass($class, $template, $index); + if ($template instanceof Twig_TemplateWrapper) { + return $template; } return $this->env->loadTemplate($template, $index); - } catch (Error $e) { + } catch (Twig_Error $e) { if (!$e->getSourceContext()) { - $e->setSourceContext($templateName ? new Source('', $templateName) : $this->getSourceContext()); + $e->setSourceContext($templateName ? new Twig_Source('', $templateName) : $this->getSourceContext()); } - if ($e->getTemplateLine() > 0) { + if ($e->getTemplateLine()) { throw $e; } @@ -394,16 +383,6 @@ protected function loadTemplate($template, $templateName = null, $line = null, $ } } - /** - * @internal - * - * @return Template - */ - protected function unwrap() - { - return $this; - } - /** * Returns all blocks. * @@ -411,34 +390,38 @@ protected function unwrap() * directly. * * @return array An array of blocks + * + * @internal */ public function getBlocks() { return $this->blocks; } - public function display(array $context, array $blocks = []) + /** + * {@inheritdoc} + */ + public function display(array $context, array $blocks = array()) { $this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks)); } + /** + * {@inheritdoc} + */ public function render(array $context) { $level = ob_get_level(); - if ($this->env->isDebug()) { - ob_start(); - } else { - ob_start(function () { return ''; }); - } + ob_start(); try { $this->display($context); - } catch (\Exception $e) { + } catch (Exception $e) { while (ob_get_level() > $level) { ob_end_clean(); } throw $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { while (ob_get_level() > $level) { ob_end_clean(); } @@ -449,27 +432,25 @@ public function render(array $context) return ob_get_clean(); } - protected function displayWithErrorHandling(array $context, array $blocks = []) + protected function displayWithErrorHandling(array $context, array $blocks = array()) { try { $this->doDisplay($context, $blocks); - } catch (Error $e) { + } catch (Twig_Error $e) { if (!$e->getSourceContext()) { $e->setSourceContext($this->getSourceContext()); } - // this is mostly useful for \Twig\Error\LoaderError exceptions - // see \Twig\Error\LoaderError - if (-1 === $e->getTemplateLine()) { + // this is mostly useful for Twig_Error_Loader exceptions + // see Twig_Error_Loader + if (false === $e->getTemplateLine()) { + $e->setTemplateLine(-1); $e->guess(); } throw $e; - } catch (\Exception $e) { - $e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getSourceContext(), $e); - $e->guess(); - - throw $e; + } catch (Exception $e) { + throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getSourceContext(), $e); } } @@ -479,7 +460,7 @@ protected function displayWithErrorHandling(array $context, array $blocks = []) * @param array $context An array of parameters to pass to the template * @param array $blocks An array of blocks to pass to the template */ - abstract protected function doDisplay(array $context, array $blocks = []); + abstract protected function doDisplay(array $context, array $blocks = array()); /** * Returns a variable from the context. @@ -498,18 +479,18 @@ abstract protected function doDisplay(array $context, array $blocks = []); * * @return mixed The content of the context variable * - * @throws RuntimeError if the variable does not exist and Twig is running in strict mode + * @throws Twig_Error_Runtime if the variable does not exist and Twig is running in strict mode * * @internal */ final protected function getContext($context, $item, $ignoreStrictCheck = false) { - if (!\array_key_exists($item, $context)) { + if (!array_key_exists($item, $context)) { if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { return; } - throw new RuntimeError(sprintf('Variable "%s" does not exist.', $item), -1, $this->getSourceContext()); + throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist.', $item), -1, $this->getSourceContext()); } return $context[$item]; @@ -521,24 +502,24 @@ final protected function getContext($context, $item, $ignoreStrictCheck = false) * @param mixed $object The object or array from where to get the item * @param mixed $item The item to get from the array or object * @param array $arguments An array of arguments to pass if the item is an object method - * @param string $type The type of attribute (@see \Twig\Template constants) + * @param string $type The type of attribute (@see Twig_Template constants) * @param bool $isDefinedTest Whether this is only a defined check * @param bool $ignoreStrictCheck Whether to ignore the strict attribute check or not * * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true * - * @throws RuntimeError if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false + * @throws Twig_Error_Runtime if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false * * @internal */ - protected function getAttribute($object, $item, array $arguments = [], $type = self::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false) + protected function getAttribute($object, $item, array $arguments = array(), $type = self::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false) { // array if (self::METHOD_CALL !== $type) { - $arrayItem = \is_bool($item) || \is_float($item) ? (int) $item : $item; + $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item; - if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, (array) $object))) - || ($object instanceof \ArrayAccess && isset($object[$arrayItem])) + if ((is_array($object) && (isset($object[$arrayItem]) || array_key_exists($arrayItem, $object))) + || ($object instanceof ArrayAccess && isset($object[$arrayItem])) ) { if ($isDefinedTest) { return true; @@ -547,7 +528,7 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s return $object[$arrayItem]; } - if (self::ARRAY_CALL === $type || !\is_object($object)) { + if (self::ARRAY_CALL === $type || !is_object($object)) { if ($isDefinedTest) { return false; } @@ -556,11 +537,11 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s return; } - if ($object instanceof \ArrayAccess) { - $message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, \get_class($object)); - } elseif (\is_object($object)) { - $message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, \get_class($object)); - } elseif (\is_array($object)) { + if ($object instanceof ArrayAccess) { + $message = sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.', $arrayItem, get_class($object)); + } elseif (is_object($object)) { + $message = sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.', $item, get_class($object)); + } elseif (is_array($object)) { if (empty($object)) { $message = sprintf('Key "%s" does not exist as the array is empty.', $arrayItem); } else { @@ -570,19 +551,19 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s if (null === $object) { $message = sprintf('Impossible to access a key ("%s") on a null variable.', $item); } else { - $message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s").', $item, \gettype($object), $object); + $message = sprintf('Impossible to access a key ("%s") on a %s variable ("%s").', $item, gettype($object), $object); } } elseif (null === $object) { $message = sprintf('Impossible to access an attribute ("%s") on a null variable.', $item); } else { - $message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").', $item, \gettype($object), $object); + $message = sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").', $item, gettype($object), $object); } - throw new RuntimeError($message, -1, $this->getSourceContext()); + throw new Twig_Error_Runtime($message, -1, $this->getSourceContext()); } } - if (!\is_object($object)) { + if (!is_object($object)) { if ($isDefinedTest) { return false; } @@ -593,40 +574,38 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s if (null === $object) { $message = sprintf('Impossible to invoke a method ("%s") on a null variable.', $item); - } elseif (\is_array($object)) { - $message = sprintf('Impossible to invoke a method ("%s") on an array.', $item); } else { - $message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").', $item, \gettype($object), $object); + $message = sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").', $item, gettype($object), $object); } - throw new RuntimeError($message, -1, $this->getSourceContext()); + throw new Twig_Error_Runtime($message, -1, $this->getSourceContext()); } // object property - if (self::METHOD_CALL !== $type && !$object instanceof self) { // \Twig\Template does not have public properties, and we don't want to allow access to internal ones - if (isset($object->$item) || \array_key_exists((string) $item, (array) $object)) { + if (self::METHOD_CALL !== $type && !$object instanceof self) { // Twig_Template does not have public properties, and we don't want to allow access to internal ones + if (isset($object->$item) || array_key_exists((string) $item, $object)) { if ($isDefinedTest) { return true; } - if ($this->env->hasExtension('\Twig\Extension\SandboxExtension')) { - $this->env->getExtension('\Twig\Extension\SandboxExtension')->checkPropertyAllowed($object, $item); + if ($this->env->hasExtension('Twig_Extension_Sandbox')) { + $this->env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item); } return $object->$item; } } - $class = \get_class($object); + $class = get_class($object); // object method if (!isset(self::$cache[$class])) { // get_class_methods returns all methods accessible in the scope, but we only want public ones to be accessible in templates if ($object instanceof self) { - $ref = new \ReflectionClass($class); - $methods = []; + $ref = new ReflectionClass($class); + $methods = array(); - foreach ($ref->getMethods(\ReflectionMethod::IS_PUBLIC) as $refMethod) { + foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $refMethod) { // Accessing the environment from templates is forbidden to prevent untrusted changes to the environment if ('getenvironment' !== strtolower($refMethod->name)) { $methods[] = $refMethod->name; @@ -638,7 +617,7 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s // sort values to have consistent behavior, so that "get" methods win precedence over "is" methods sort($methods); - $cache = []; + $cache = array(); foreach ($methods as $method) { $cache[$method] = $method; @@ -654,14 +633,11 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s continue; } - // skip get() and is() methods (in which case, $name is empty) - if ($name) { - if (!isset($cache[$name])) { - $cache[$name] = $method; - } - if (!isset($cache[$lcName])) { - $cache[$lcName] = $method; - } + if (!isset($cache[$name])) { + $cache[$name] = $method; + } + if (!isset($cache[$lcName])) { + $cache[$lcName] = $method; } } self::$cache[$class] = $cache; @@ -684,15 +660,15 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s return; } - throw new RuntimeError(sprintf('Neither the property "%1$s" nor one of the methods "%1$s()", "get%1$s()"/"is%1$s()" or "__call()" exist and have public access in class "%2$s".', $item, $class), -1, $this->getSourceContext()); + throw new Twig_Error_Runtime(sprintf('Neither the property "%1$s" nor one of the methods "%1$s()", "get%1$s()"/"is%1$s()" or "__call()" exist and have public access in class "%2$s".', $item, $class), -1, $this->getSourceContext()); } if ($isDefinedTest) { return true; } - if ($this->env->hasExtension('\Twig\Extension\SandboxExtension')) { - $this->env->getExtension('\Twig\Extension\SandboxExtension')->checkMethodAllowed($object, $method); + if ($this->env->hasExtension('Twig_Extension_Sandbox')) { + $this->env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method); } // Some objects throw exceptions when they have __call, and the method we try @@ -701,9 +677,9 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s if (!$arguments) { $ret = $object->$method(); } else { - $ret = \call_user_func_array([$object, $method], $arguments); + $ret = call_user_func_array(array($object, $method), $arguments); } - } catch (\BadMethodCallException $e) { + } catch (BadMethodCallException $e) { if ($call && ($ignoreStrictCheck || !$this->env->isStrictVariables())) { return; } @@ -711,9 +687,9 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s } // @deprecated in 1.28 - if ($object instanceof \Twig_TemplateInterface) { + if ($object instanceof Twig_TemplateInterface) { $self = $object->getTemplateName() === $this->getTemplateName(); - $message = sprintf('Calling "%s" on template "%s" from template "%s" is deprecated since version 1.28 and won\'t be supported anymore in 2.0.', $item, $object->getTemplateName(), $this->getTemplateName()); + $message = sprintf('Calling "%s" on template "%s" from template "%s" is deprecated since version 1.28 and won\'t be supported anymore in 2.0.', $method, $object->getTemplateName(), $this->getTemplateName()); if ('renderBlock' === $method || 'displayBlock' === $method) { $message .= sprintf(' Use block("%s"%s) instead).', $arguments[0], $self ? '' : ', template'); } elseif ('hasBlock' === $method) { @@ -723,11 +699,9 @@ protected function getAttribute($object, $item, array $arguments = [], $type = s } @trigger_error($message, E_USER_DEPRECATED); - return '' === $ret ? '' : new Markup($ret, $this->env->getCharset()); + return $ret === '' ? '' : new Twig_Markup($ret, $this->env->getCharset()); } return $ret; } } - -class_alias('Twig\Template', 'Twig_Template'); diff --git a/application/third_party/Twig/TemplateWrapper.php b/application/third_party/Twig/TemplateWrapper.php index e2654094e4e..2db61cdad3b 100644 --- a/application/third_party/Twig/TemplateWrapper.php +++ b/application/third_party/Twig/TemplateWrapper.php @@ -3,31 +3,29 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2016 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - /** * Exposes a template to userland. * * @author Fabien Potencier */ -final class TemplateWrapper +final class Twig_TemplateWrapper { private $env; private $template; /** * This method is for internal use only and should never be called - * directly (use Twig\Environment::load() instead). + * directly (use Twig_Environment::load() instead). * * @internal */ - public function __construct(Environment $env, Template $template) + public function __construct(Twig_Environment $env, Twig_Template $template) { $this->env = $env; $this->template = $template; @@ -40,11 +38,9 @@ public function __construct(Environment $env, Template $template) * * @return string The rendered template */ - public function render($context = []) + public function render($context = array()) { - // using func_get_args() allows to not expose the blocks argument - // as it should only be used by internal code - return $this->template->render($context, \func_num_args() > 1 ? func_get_arg(1) : []); + return $this->template->render($context); } /** @@ -52,11 +48,9 @@ public function render($context = []) * * @param array $context An array of parameters to pass to the template */ - public function display($context = []) + public function display($context = array()) { - // using func_get_args() allows to not expose the blocks argument - // as it should only be used by internal code - $this->template->display($context, \func_num_args() > 1 ? func_get_arg(1) : []); + $this->template->display($context); } /** @@ -67,7 +61,7 @@ public function display($context = []) * * @return bool */ - public function hasBlock($name, $context = []) + public function hasBlock($name, $context = array()) { return $this->template->hasBlock($name, $context); } @@ -79,7 +73,7 @@ public function hasBlock($name, $context = []) * * @return string[] An array of defined template block names */ - public function getBlockNames($context = []) + public function getBlockNames($context = array()) { return $this->template->getBlockNames($context); } @@ -92,24 +86,20 @@ public function getBlockNames($context = []) * * @return string The rendered block */ - public function renderBlock($name, $context = []) + public function renderBlock($name, $context = array()) { $context = $this->env->mergeGlobals($context); $level = ob_get_level(); - if ($this->env->isDebug()) { - ob_start(); - } else { - ob_start(function () { return ''; }); - } + ob_start(); try { $this->template->displayBlock($name, $context); - } catch (\Exception $e) { + } catch (Exception $e) { while (ob_get_level() > $level) { ob_end_clean(); } throw $e; - } catch (\Throwable $e) { + } catch (Throwable $e) { while (ob_get_level() > $level) { ob_end_clean(); } @@ -126,36 +116,16 @@ public function renderBlock($name, $context = []) * @param string $name The block name to render * @param array $context An array of parameters to pass to the template */ - public function displayBlock($name, $context = []) + public function displayBlock($name, $context = array()) { $this->template->displayBlock($name, $this->env->mergeGlobals($context)); } /** - * @return Source + * @return Twig_Source */ public function getSourceContext() { return $this->template->getSourceContext(); } - - /** - * @return string - */ - public function getTemplateName() - { - return $this->template->getTemplateName(); - } - - /** - * @internal - * - * @return Template - */ - public function unwrap() - { - return $this->template; - } } - -class_alias('Twig\TemplateWrapper', 'Twig_TemplateWrapper'); diff --git a/application/third_party/Twig/Test/IntegrationTestCase.php b/application/third_party/Twig/Test/IntegrationTestCase.php index 36b36075867..93314ea15a1 100644 --- a/application/third_party/Twig/Test/IntegrationTestCase.php +++ b/application/third_party/Twig/Test/IntegrationTestCase.php @@ -3,33 +3,19 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier + * (c) 2010 Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig\Test; - -use PHPUnit\Framework\TestCase; -use Twig\Environment; -use Twig\Error\Error; -use Twig\Extension\ExtensionInterface; -use Twig\Loader\ArrayLoader; -use Twig\Loader\SourceContextLoaderInterface; -use Twig\RuntimeLoader\RuntimeLoaderInterface; -use Twig\Source; -use Twig\TwigFilter; -use Twig\TwigFunction; -use Twig\TwigTest; - /** * Integration test helper. * * @author Fabien Potencier * @author Karma Dordrak */ -abstract class IntegrationTestCase extends TestCase +abstract class Twig_Test_IntegrationTestCase extends PHPUnit_Framework_TestCase { /** * @return string @@ -37,43 +23,35 @@ abstract class IntegrationTestCase extends TestCase abstract protected function getFixturesDir(); /** - * @return RuntimeLoaderInterface[] - */ - protected function getRuntimeLoaders() - { - return []; - } - - /** - * @return ExtensionInterface[] + * @return Twig_ExtensionInterface[] */ protected function getExtensions() { - return []; + return array(); } /** - * @return TwigFilter[] + * @return Twig_SimpleFilter[] */ protected function getTwigFilters() { - return []; + return array(); } /** - * @return TwigFunction[] + * @return Twig_SimpleFunction[] */ protected function getTwigFunctions() { - return []; + return array(); } /** - * @return TwigTest[] + * @return Twig_SimpleTest[] */ protected function getTwigTests() { - return []; + return array(); } /** @@ -96,9 +74,9 @@ public function testLegacyIntegration($file, $message, $condition, $templates, $ public function getTests($name, $legacyTests = false) { $fixturesDir = realpath($this->getFixturesDir()); - $tests = []; + $tests = array(); - foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($fixturesDir), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fixturesDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { if (!preg_match('/\.test$/', $file)) { continue; } @@ -114,7 +92,7 @@ public function getTests($name, $legacyTests = false) $condition = $match[2]; $templates = self::parseTemplates($match[3]); $exception = $match[5]; - $outputs = [[null, $match[4], null, '']]; + $outputs = array(array(null, $match[4], null, '')); } elseif (preg_match('/--TEST--\s*(.*?)\s*(?:--CONDITION--\s*(.*))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)--DATA--.*?--EXPECT--.*/s', $test, $match)) { $message = $match[1]; $condition = $match[2]; @@ -122,15 +100,15 @@ public function getTests($name, $legacyTests = false) $exception = false; preg_match_all('/--DATA--(.*?)(?:--CONFIG--(.*?))?--EXPECT--(.*?)(?=\-\-DATA\-\-|$)/s', $test, $outputs, PREG_SET_ORDER); } else { - throw new \InvalidArgumentException(sprintf('Test "%s" is not valid.', str_replace($fixturesDir.'/', '', $file))); + throw new InvalidArgumentException(sprintf('Test "%s" is not valid.', str_replace($fixturesDir.'/', '', $file))); } - $tests[] = [str_replace($fixturesDir.'/', '', $file), $message, $condition, $templates, $exception, $outputs]; + $tests[] = array(str_replace($fixturesDir.'/', '', $file), $message, $condition, $templates, $exception, $outputs); } if ($legacyTests && empty($tests)) { // add a dummy test to avoid a PHPUnit message - return [['not', '-', '', [], '', []]]; + return array(array('not', '-', '', array(), '', array())); } return $tests; @@ -143,10 +121,6 @@ public function getLegacyTests() protected function doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs) { - if (!$outputs) { - $this->markTestSkipped('no tests to run'); - } - if ($condition) { eval('$ret = '.$condition.';'); if (!$ret) { @@ -154,19 +128,15 @@ protected function doIntegrationTest($file, $message, $condition, $templates, $e } } - $loader = new ArrayLoader($templates); + $loader = new Twig_Loader_Array($templates); foreach ($outputs as $i => $match) { - $config = array_merge([ + $config = array_merge(array( 'cache' => false, 'strict_variables' => true, - ], $match[2] ? eval($match[2].';') : []); - $twig = new Environment($loader, $config); + ), $match[2] ? eval($match[2].';') : array()); + $twig = new Twig_Environment($loader, $config); $twig->addGlobal('global', 'global'); - foreach ($this->getRuntimeLoaders() as $runtimeLoader) { - $twig->addRuntimeLoader($runtimeLoader); - } - foreach ($this->getExtensions() as $extension) { $twig->addExtension($extension); } @@ -183,43 +153,46 @@ protected function doIntegrationTest($file, $message, $condition, $templates, $e $twig->addFunction($function); } - $p = new \ReflectionProperty($twig, 'templateClassPrefix'); - $p->setAccessible(true); - $p->setValue($twig, '__TwigTemplate_'.hash('sha256', uniqid(mt_rand(), true), false).'_'); + // avoid using the same PHP class name for different cases + // only for PHP 5.2+ + if (PHP_VERSION_ID >= 50300) { + $p = new ReflectionProperty($twig, 'templateClassPrefix'); + $p->setAccessible(true); + $p->setValue($twig, '__TwigTemplate_'.hash('sha256', uniqid(mt_rand(), true), false).'_'); + } try { - $template = $twig->load('index.twig'); - } catch (\Exception $e) { + $template = $twig->loadTemplate('index.twig'); + } catch (Exception $e) { if (false !== $exception) { $message = $e->getMessage(); - $this->assertSame(trim($exception), trim(sprintf('%s: %s', \get_class($e), $message))); - $last = substr($message, \strlen($message) - 1); - $this->assertTrue('.' === $last || '?' === $last, 'Exception message must end with a dot or a question mark.'); + $this->assertSame(trim($exception), trim(sprintf('%s: %s', get_class($e), $message))); + $last = substr($message, strlen($message) - 1); + $this->assertTrue('.' === $last || '?' === $last, $message, 'Exception message must end with a dot or a question mark.'); return; } - throw new Error(sprintf('%s: %s', \get_class($e), $e->getMessage()), -1, null, $e); + throw new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e); } try { $output = trim($template->render(eval($match[1].';')), "\n "); - } catch (\Exception $e) { + } catch (Exception $e) { if (false !== $exception) { - $this->assertSame(trim($exception), trim(sprintf('%s: %s', \get_class($e), $e->getMessage()))); + $this->assertSame(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage()))); return; } - $e = new Error(sprintf('%s: %s', \get_class($e), $e->getMessage()), -1, null, $e); + $e = new Twig_Error(sprintf('%s: %s', get_class($e), $e->getMessage()), -1, $file, $e); - $output = trim(sprintf('%s: %s', \get_class($e), $e->getMessage())); + $output = trim(sprintf('%s: %s', get_class($e), $e->getMessage())); } if (false !== $exception) { list($class) = explode(':', $exception); - $constraintClass = class_exists('PHPUnit\Framework\Constraint\Exception') ? 'PHPUnit\Framework\Constraint\Exception' : 'PHPUnit_Framework_Constraint_Exception'; - $this->assertThat(null, new $constraintClass($class)); + $this->assertThat(null, new PHPUnit_Framework_Constraint_Exception($class)); } $expected = trim($match[3], "\n "); @@ -230,8 +203,8 @@ protected function doIntegrationTest($file, $message, $condition, $templates, $e foreach (array_keys($templates) as $name) { echo "Template: $name\n"; $loader = $twig->getLoader(); - if (!$loader instanceof SourceContextLoaderInterface) { - $source = new Source($loader->getSource($name), $name); + if (!$loader instanceof Twig_SourceContextLoaderInterface) { + $source = new Twig_Source($loader->getSource($name), $name); } else { $source = $loader->getSourceContext($name); } @@ -244,7 +217,7 @@ protected function doIntegrationTest($file, $message, $condition, $templates, $e protected static function parseTemplates($test) { - $templates = []; + $templates = array(); preg_match_all('/--TEMPLATE(?:\((.*?)\))?--(.*?)(?=\-\-TEMPLATE|$)/s', $test, $matches, PREG_SET_ORDER); foreach ($matches as $match) { $templates[($match[1] ? $match[1] : 'index.twig')] = $match[2]; @@ -253,5 +226,3 @@ protected static function parseTemplates($test) return $templates; } } - -class_alias('Twig\Test\IntegrationTestCase', 'Twig_Test_IntegrationTestCase'); diff --git a/application/third_party/Twig/Test/NodeTestCase.php b/application/third_party/Twig/Test/NodeTestCase.php index f3358cb9a36..a6b550cf8cd 100644 --- a/application/third_party/Twig/Test/NodeTestCase.php +++ b/application/third_party/Twig/Test/NodeTestCase.php @@ -8,16 +8,7 @@ * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ - -namespace Twig\Test; - -use PHPUnit\Framework\TestCase; -use Twig\Compiler; -use Twig\Environment; -use Twig\Loader\ArrayLoader; -use Twig\Node\Node; - -abstract class NodeTestCase extends TestCase +abstract class Twig_Test_NodeTestCase extends PHPUnit_Framework_TestCase { abstract public function getTests(); @@ -29,7 +20,7 @@ public function testCompile($node, $source, $environment = null, $isPattern = fa $this->assertNodeCompilation($source, $node, $environment, $isPattern); } - public function assertNodeCompilation($source, Node $node, Environment $environment = null, $isPattern = false) + public function assertNodeCompilation($source, Twig_Node $node, Twig_Environment $environment = null, $isPattern = false) { $compiler = $this->getCompiler($environment); $compiler->compile($node); @@ -41,25 +32,25 @@ public function assertNodeCompilation($source, Node $node, Environment $environm } } - protected function getCompiler(Environment $environment = null) + protected function getCompiler(Twig_Environment $environment = null) { - return new Compiler(null === $environment ? $this->getEnvironment() : $environment); + return new Twig_Compiler(null === $environment ? $this->getEnvironment() : $environment); } protected function getEnvironment() { - return new Environment(new ArrayLoader([])); + return new Twig_Environment(new Twig_Loader_Array(array())); } protected function getVariableGetter($name, $line = false) { $line = $line > 0 ? "// line {$line}\n" : ''; - if (\PHP_VERSION_ID >= 70000) { - return sprintf('%s($context["%s"] ?? null)', $line, $name); + if (PHP_VERSION_ID >= 70000) { + return sprintf('%s($context["%s"] ?? null)', $line, $name, $name); } - if (\PHP_VERSION_ID >= 50400) { + if (PHP_VERSION_ID >= 50400) { return sprintf('%s(isset($context["%s"]) ? $context["%s"] : null)', $line, $name, $name); } @@ -68,12 +59,10 @@ protected function getVariableGetter($name, $line = false) protected function getAttributeGetter() { - if (\function_exists('twig_template_get_attributes')) { + if (function_exists('twig_template_get_attributes')) { return 'twig_template_get_attributes($this, '; } return '$this->getAttribute('; } } - -class_alias('Twig\Test\NodeTestCase', 'Twig_Test_NodeTestCase'); diff --git a/application/third_party/Twig/Token.php b/application/third_party/Twig/Token.php index a0bb11af15e..67b5787c053 100644 --- a/application/third_party/Twig/Token.php +++ b/application/third_party/Twig/Token.php @@ -3,15 +3,13 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier - * (c) Armin Ronacher + * (c) 2009 Fabien Potencier + * (c) 2009 Armin Ronacher * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - /** * Represents a Token. * @@ -19,7 +17,7 @@ * * @final */ -class Token +class Twig_Token { protected $value; protected $type; @@ -38,7 +36,6 @@ class Token const PUNCTUATION_TYPE = 9; const INTERPOLATION_START_TYPE = 10; const INTERPOLATION_END_TYPE = 11; - const ARROW_TYPE = 12; /** * @param int $type The type of the token @@ -65,21 +62,21 @@ public function __toString() * * type and value (or array of possible values) * * just value (or array of possible values) (NAME_TYPE is used as type) * - * @param array|string|int $type The type to test + * @param array|int $type The type to test * @param array|string|null $values The token value * * @return bool */ public function test($type, $values = null) { - if (null === $values && !\is_int($type)) { + if (null === $values && !is_int($type)) { $values = $type; $type = self::NAME_TYPE; } return ($this->type === $type) && ( null === $values || - (\is_array($values) && \in_array($this->value, $values)) || + (is_array($values) && in_array($this->value, $values)) || $this->value == $values ); } @@ -158,14 +155,11 @@ public static function typeToString($type, $short = false) case self::INTERPOLATION_END_TYPE: $name = 'INTERPOLATION_END_TYPE'; break; - case self::ARROW_TYPE: - $name = 'ARROW_TYPE'; - break; default: - throw new \LogicException(sprintf('Token of type "%s" does not exist.', $type)); + throw new LogicException(sprintf('Token of type "%s" does not exist.', $type)); } - return $short ? $name : 'Twig\Token::'.$name; + return $short ? $name : 'Twig_Token::'.$name; } /** @@ -204,12 +198,8 @@ public static function typeToEnglish($type) return 'begin of string interpolation'; case self::INTERPOLATION_END_TYPE: return 'end of string interpolation'; - case self::ARROW_TYPE: - return 'arrow function'; default: - throw new \LogicException(sprintf('Token of type "%s" does not exist.', $type)); + throw new LogicException(sprintf('Token of type "%s" does not exist.', $type)); } } } - -class_alias('Twig\Token', 'Twig_Token'); diff --git a/application/third_party/Twig/TokenParser/AbstractTokenParser.php b/application/third_party/Twig/TokenParser/AbstractTokenParser.php deleted file mode 100644 index 2c2f90b7f11..00000000000 --- a/application/third_party/Twig/TokenParser/AbstractTokenParser.php +++ /dev/null @@ -1,34 +0,0 @@ - - */ -abstract class AbstractTokenParser implements TokenParserInterface -{ - /** - * @var Parser - */ - protected $parser; - - public function setParser(Parser $parser) - { - $this->parser = $parser; - } -} - -class_alias('Twig\TokenParser\AbstractTokenParser', 'Twig_TokenParser'); diff --git a/application/third_party/Twig/TokenParser/ApplyTokenParser.php b/application/third_party/Twig/TokenParser/ApplyTokenParser.php deleted file mode 100644 index 879879a2b01..00000000000 --- a/application/third_party/Twig/TokenParser/ApplyTokenParser.php +++ /dev/null @@ -1,58 +0,0 @@ -getLine(); - $name = $this->parser->getVarName(); - - $ref = new TempNameExpression($name, $lineno); - $ref->setAttribute('always_defined', true); - - $filter = $this->parser->getExpressionParser()->parseFilterExpressionRaw($ref, $this->getTag()); - - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideApplyEnd'], true); - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - - return new Node([ - new SetNode(true, $ref, $body, $lineno, $this->getTag()), - new PrintNode($filter, $lineno, $this->getTag()), - ]); - } - - public function decideApplyEnd(Token $token) - { - return $token->test('endapply'); - } - - public function getTag() - { - return 'apply'; - } -} diff --git a/application/third_party/Twig/TokenParser/AutoEscapeTokenParser.php b/application/third_party/Twig/TokenParser/AutoEscapeTokenParser.php deleted file mode 100644 index 2cd0cc69d73..00000000000 --- a/application/third_party/Twig/TokenParser/AutoEscapeTokenParser.php +++ /dev/null @@ -1,88 +0,0 @@ -getLine(); - $stream = $this->parser->getStream(); - - if ($stream->test(Token::BLOCK_END_TYPE)) { - $value = 'html'; - } else { - $expr = $this->parser->getExpressionParser()->parseExpression(); - if (!$expr instanceof ConstantExpression) { - throw new SyntaxError('An escaping strategy must be a string or a bool.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - $value = $expr->getAttribute('value'); - - $compat = true === $value || false === $value; - - if (true === $value) { - $value = 'html'; - } - - if ($compat && $stream->test(Token::NAME_TYPE)) { - @trigger_error('Using the autoescape tag with "true" or "false" before the strategy name is deprecated since version 1.21.', E_USER_DEPRECATED); - - if (false === $value) { - throw new SyntaxError('Unexpected escaping strategy as you set autoescaping to false.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - - $value = $stream->next()->getValue(); - } - } - - $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); - $stream->expect(Token::BLOCK_END_TYPE); - - return new AutoEscapeNode($value, $body, $lineno, $this->getTag()); - } - - public function decideBlockEnd(Token $token) - { - return $token->test('endautoescape'); - } - - public function getTag() - { - return 'autoescape'; - } -} - -class_alias('Twig\TokenParser\AutoEscapeTokenParser', 'Twig_TokenParser_AutoEscape'); diff --git a/application/third_party/Twig/TokenParser/BlockTokenParser.php b/application/third_party/Twig/TokenParser/BlockTokenParser.php deleted file mode 100644 index caf11f0b726..00000000000 --- a/application/third_party/Twig/TokenParser/BlockTokenParser.php +++ /dev/null @@ -1,80 +0,0 @@ - - * {% block title %}{% endblock %} - My Webpage - * {% endblock %} - * - * @final - */ -class BlockTokenParser extends AbstractTokenParser -{ - public function parse(Token $token) - { - $lineno = $token->getLine(); - $stream = $this->parser->getStream(); - $name = $stream->expect(Token::NAME_TYPE)->getValue(); - if ($this->parser->hasBlock($name)) { - throw new SyntaxError(sprintf("The block '%s' has already been defined line %d.", $name, $this->parser->getBlock($name)->getTemplateLine()), $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - $this->parser->setBlock($name, $block = new BlockNode($name, new Node([]), $lineno)); - $this->parser->pushLocalScope(); - $this->parser->pushBlockStack($name); - - if ($stream->nextIf(Token::BLOCK_END_TYPE)) { - $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); - if ($token = $stream->nextIf(Token::NAME_TYPE)) { - $value = $token->getValue(); - - if ($value != $name) { - throw new SyntaxError(sprintf('Expected endblock for block "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - } - } else { - $body = new Node([ - new PrintNode($this->parser->getExpressionParser()->parseExpression(), $lineno), - ]); - } - $stream->expect(Token::BLOCK_END_TYPE); - - $block->setNode('body', $body); - $this->parser->popBlockStack(); - $this->parser->popLocalScope(); - - return new BlockReferenceNode($name, $lineno, $this->getTag()); - } - - public function decideBlockEnd(Token $token) - { - return $token->test('endblock'); - } - - public function getTag() - { - return 'block'; - } -} - -class_alias('Twig\TokenParser\BlockTokenParser', 'Twig_TokenParser_Block'); diff --git a/application/third_party/Twig/TokenParser/DeprecatedTokenParser.php b/application/third_party/Twig/TokenParser/DeprecatedTokenParser.php deleted file mode 100644 index 6575cff167d..00000000000 --- a/application/third_party/Twig/TokenParser/DeprecatedTokenParser.php +++ /dev/null @@ -1,44 +0,0 @@ - - * - * @final - */ -class DeprecatedTokenParser extends AbstractTokenParser -{ - public function parse(Token $token) - { - $expr = $this->parser->getExpressionParser()->parseExpression(); - - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - - return new DeprecatedNode($expr, $token->getLine(), $this->getTag()); - } - - public function getTag() - { - return 'deprecated'; - } -} - -class_alias('Twig\TokenParser\DeprecatedTokenParser', 'Twig_TokenParser_Deprecated'); diff --git a/application/third_party/Twig/TokenParser/DoTokenParser.php b/application/third_party/Twig/TokenParser/DoTokenParser.php deleted file mode 100644 index e1eae10f230..00000000000 --- a/application/third_party/Twig/TokenParser/DoTokenParser.php +++ /dev/null @@ -1,39 +0,0 @@ -parser->getExpressionParser()->parseExpression(); - - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - - return new DoNode($expr, $token->getLine(), $this->getTag()); - } - - public function getTag() - { - return 'do'; - } -} - -class_alias('Twig\TokenParser\DoTokenParser', 'Twig_TokenParser_Do'); diff --git a/application/third_party/Twig/TokenParser/EmbedTokenParser.php b/application/third_party/Twig/TokenParser/EmbedTokenParser.php deleted file mode 100644 index 973ff2e45b1..00000000000 --- a/application/third_party/Twig/TokenParser/EmbedTokenParser.php +++ /dev/null @@ -1,74 +0,0 @@ -parser->getStream(); - - $parent = $this->parser->getExpressionParser()->parseExpression(); - - list($variables, $only, $ignoreMissing) = $this->parseArguments(); - - $parentToken = $fakeParentToken = new Token(Token::STRING_TYPE, '__parent__', $token->getLine()); - if ($parent instanceof ConstantExpression) { - $parentToken = new Token(Token::STRING_TYPE, $parent->getAttribute('value'), $token->getLine()); - } elseif ($parent instanceof NameExpression) { - $parentToken = new Token(Token::NAME_TYPE, $parent->getAttribute('name'), $token->getLine()); - } - - // inject a fake parent to make the parent() function work - $stream->injectTokens([ - new Token(Token::BLOCK_START_TYPE, '', $token->getLine()), - new Token(Token::NAME_TYPE, 'extends', $token->getLine()), - $parentToken, - new Token(Token::BLOCK_END_TYPE, '', $token->getLine()), - ]); - - $module = $this->parser->parse($stream, [$this, 'decideBlockEnd'], true); - - // override the parent with the correct one - if ($fakeParentToken === $parentToken) { - $module->setNode('parent', $parent); - } - - $this->parser->embedTemplate($module); - - $stream->expect(Token::BLOCK_END_TYPE); - - return new EmbedNode($module->getTemplateName(), $module->getAttribute('index'), $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag()); - } - - public function decideBlockEnd(Token $token) - { - return $token->test('endembed'); - } - - public function getTag() - { - return 'embed'; - } -} - -class_alias('Twig\TokenParser\EmbedTokenParser', 'Twig_TokenParser_Embed'); diff --git a/application/third_party/Twig/TokenParser/ExtendsTokenParser.php b/application/third_party/Twig/TokenParser/ExtendsTokenParser.php deleted file mode 100644 index e66789a7bdc..00000000000 --- a/application/third_party/Twig/TokenParser/ExtendsTokenParser.php +++ /dev/null @@ -1,54 +0,0 @@ -parser->getStream(); - - if ($this->parser->peekBlockStack()) { - throw new SyntaxError('Cannot use "extend" in a block.', $token->getLine(), $stream->getSourceContext()); - } elseif (!$this->parser->isMainScope()) { - throw new SyntaxError('Cannot use "extend" in a macro.', $token->getLine(), $stream->getSourceContext()); - } - - if (null !== $this->parser->getParent()) { - throw new SyntaxError('Multiple extends tags are forbidden.', $token->getLine(), $stream->getSourceContext()); - } - $this->parser->setParent($this->parser->getExpressionParser()->parseExpression()); - - $stream->expect(Token::BLOCK_END_TYPE); - - return new Node(); - } - - public function getTag() - { - return 'extends'; - } -} - -class_alias('Twig\TokenParser\ExtendsTokenParser', 'Twig_TokenParser_Extends'); diff --git a/application/third_party/Twig/TokenParser/FilterTokenParser.php b/application/third_party/Twig/TokenParser/FilterTokenParser.php deleted file mode 100644 index dc07dcfa41e..00000000000 --- a/application/third_party/Twig/TokenParser/FilterTokenParser.php +++ /dev/null @@ -1,59 +0,0 @@ -parser->getVarName(); - $ref = new BlockReferenceExpression(new ConstantExpression($name, $token->getLine()), null, $token->getLine(), $this->getTag()); - - $filter = $this->parser->getExpressionParser()->parseFilterExpressionRaw($ref, $this->getTag()); - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - - $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - - $block = new BlockNode($name, $body, $token->getLine()); - $this->parser->setBlock($name, $block); - - return new PrintNode($filter, $token->getLine(), $this->getTag()); - } - - public function decideBlockEnd(Token $token) - { - return $token->test('endfilter'); - } - - public function getTag() - { - return 'filter'; - } -} - -class_alias('Twig\TokenParser\FilterTokenParser', 'Twig_TokenParser_Filter'); diff --git a/application/third_party/Twig/TokenParser/FlushTokenParser.php b/application/third_party/Twig/TokenParser/FlushTokenParser.php deleted file mode 100644 index b25524fa8da..00000000000 --- a/application/third_party/Twig/TokenParser/FlushTokenParser.php +++ /dev/null @@ -1,39 +0,0 @@ -parser->getStream()->expect(Token::BLOCK_END_TYPE); - - return new FlushNode($token->getLine(), $this->getTag()); - } - - public function getTag() - { - return 'flush'; - } -} - -class_alias('Twig\TokenParser\FlushTokenParser', 'Twig_TokenParser_Flush'); diff --git a/application/third_party/Twig/TokenParser/ForTokenParser.php b/application/third_party/Twig/TokenParser/ForTokenParser.php deleted file mode 100644 index 69278d98ed3..00000000000 --- a/application/third_party/Twig/TokenParser/ForTokenParser.php +++ /dev/null @@ -1,136 +0,0 @@ - - * {% for user in users %} - *
  • {{ user.username|e }}
  • - * {% endfor %} - * - * - * @final - */ -class ForTokenParser extends AbstractTokenParser -{ - public function parse(Token $token) - { - $lineno = $token->getLine(); - $stream = $this->parser->getStream(); - $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); - $stream->expect(Token::OPERATOR_TYPE, 'in'); - $seq = $this->parser->getExpressionParser()->parseExpression(); - - $ifexpr = null; - if ($stream->nextIf(Token::NAME_TYPE, 'if')) { - $ifexpr = $this->parser->getExpressionParser()->parseExpression(); - } - - $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideForFork']); - if ('else' == $stream->next()->getValue()) { - $stream->expect(Token::BLOCK_END_TYPE); - $else = $this->parser->subparse([$this, 'decideForEnd'], true); - } else { - $else = null; - } - $stream->expect(Token::BLOCK_END_TYPE); - - if (\count($targets) > 1) { - $keyTarget = $targets->getNode(0); - $keyTarget = new AssignNameExpression($keyTarget->getAttribute('name'), $keyTarget->getTemplateLine()); - $valueTarget = $targets->getNode(1); - $valueTarget = new AssignNameExpression($valueTarget->getAttribute('name'), $valueTarget->getTemplateLine()); - } else { - $keyTarget = new AssignNameExpression('_key', $lineno); - $valueTarget = $targets->getNode(0); - $valueTarget = new AssignNameExpression($valueTarget->getAttribute('name'), $valueTarget->getTemplateLine()); - } - - if ($ifexpr) { - $this->checkLoopUsageCondition($stream, $ifexpr); - $this->checkLoopUsageBody($stream, $body); - } - - return new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, $lineno, $this->getTag()); - } - - public function decideForFork(Token $token) - { - return $token->test(['else', 'endfor']); - } - - public function decideForEnd(Token $token) - { - return $token->test('endfor'); - } - - // the loop variable cannot be used in the condition - protected function checkLoopUsageCondition(TokenStream $stream, \Twig_NodeInterface $node) - { - if ($node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression && 'loop' == $node->getNode('node')->getAttribute('name')) { - throw new SyntaxError('The "loop" variable cannot be used in a looping condition.', $node->getTemplateLine(), $stream->getSourceContext()); - } - - foreach ($node as $n) { - if (!$n) { - continue; - } - - $this->checkLoopUsageCondition($stream, $n); - } - } - - // check usage of non-defined loop-items - // it does not catch all problems (for instance when a for is included into another or when the variable is used in an include) - protected function checkLoopUsageBody(TokenStream $stream, \Twig_NodeInterface $node) - { - if ($node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression && 'loop' == $node->getNode('node')->getAttribute('name')) { - $attribute = $node->getNode('attribute'); - if ($attribute instanceof ConstantExpression && \in_array($attribute->getAttribute('value'), ['length', 'revindex0', 'revindex', 'last'])) { - throw new SyntaxError(sprintf('The "loop.%s" variable is not defined when looping with a condition.', $attribute->getAttribute('value')), $node->getTemplateLine(), $stream->getSourceContext()); - } - } - - // should check for parent.loop.XXX usage - if ($node instanceof ForNode) { - return; - } - - foreach ($node as $n) { - if (!$n) { - continue; - } - - $this->checkLoopUsageBody($stream, $n); - } - } - - public function getTag() - { - return 'for'; - } -} - -class_alias('Twig\TokenParser\ForTokenParser', 'Twig_TokenParser_For'); diff --git a/application/third_party/Twig/TokenParser/FromTokenParser.php b/application/third_party/Twig/TokenParser/FromTokenParser.php deleted file mode 100644 index 4cce650d617..00000000000 --- a/application/third_party/Twig/TokenParser/FromTokenParser.php +++ /dev/null @@ -1,72 +0,0 @@ -parser->getExpressionParser()->parseExpression(); - $stream = $this->parser->getStream(); - $stream->expect(Token::NAME_TYPE, 'import'); - - $targets = []; - do { - $name = $stream->expect(Token::NAME_TYPE)->getValue(); - - $alias = $name; - if ($stream->nextIf('as')) { - $alias = $stream->expect(Token::NAME_TYPE)->getValue(); - } - - $targets[$name] = $alias; - - if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) { - break; - } - } while (true); - - $stream->expect(Token::BLOCK_END_TYPE); - - $var = new AssignNameExpression($this->parser->getVarName(), $token->getLine()); - $node = new ImportNode($macro, $var, $token->getLine(), $this->getTag()); - - foreach ($targets as $name => $alias) { - if ($this->parser->isReservedMacroName($name)) { - throw new SyntaxError(sprintf('"%s" cannot be an imported macro as it is a reserved keyword.', $name), $token->getLine(), $stream->getSourceContext()); - } - - $this->parser->addImportedSymbol('function', $alias, 'get'.$name, $var); - } - - return $node; - } - - public function getTag() - { - return 'from'; - } -} - -class_alias('Twig\TokenParser\FromTokenParser', 'Twig_TokenParser_From'); diff --git a/application/third_party/Twig/TokenParser/IfTokenParser.php b/application/third_party/Twig/TokenParser/IfTokenParser.php deleted file mode 100644 index 2631a20cec5..00000000000 --- a/application/third_party/Twig/TokenParser/IfTokenParser.php +++ /dev/null @@ -1,91 +0,0 @@ - - * {% for user in users %} - *
  • {{ user.username|e }}
  • - * {% endfor %} - * - * {% endif %} - * - * @final - */ -class IfTokenParser extends AbstractTokenParser -{ - public function parse(Token $token) - { - $lineno = $token->getLine(); - $expr = $this->parser->getExpressionParser()->parseExpression(); - $stream = $this->parser->getStream(); - $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideIfFork']); - $tests = [$expr, $body]; - $else = null; - - $end = false; - while (!$end) { - switch ($stream->next()->getValue()) { - case 'else': - $stream->expect(Token::BLOCK_END_TYPE); - $else = $this->parser->subparse([$this, 'decideIfEnd']); - break; - - case 'elseif': - $expr = $this->parser->getExpressionParser()->parseExpression(); - $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideIfFork']); - $tests[] = $expr; - $tests[] = $body; - break; - - case 'endif': - $end = true; - break; - - default: - throw new SyntaxError(sprintf('Unexpected end of template. Twig was looking for the following tags "else", "elseif", or "endif" to close the "if" block started at line %d).', $lineno), $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - } - - $stream->expect(Token::BLOCK_END_TYPE); - - return new IfNode(new Node($tests), $else, $lineno, $this->getTag()); - } - - public function decideIfFork(Token $token) - { - return $token->test(['elseif', 'else', 'endif']); - } - - public function decideIfEnd(Token $token) - { - return $token->test(['endif']); - } - - public function getTag() - { - return 'if'; - } -} - -class_alias('Twig\TokenParser\IfTokenParser', 'Twig_TokenParser_If'); diff --git a/application/third_party/Twig/TokenParser/ImportTokenParser.php b/application/third_party/Twig/TokenParser/ImportTokenParser.php deleted file mode 100644 index 88395b92489..00000000000 --- a/application/third_party/Twig/TokenParser/ImportTokenParser.php +++ /dev/null @@ -1,45 +0,0 @@ -parser->getExpressionParser()->parseExpression(); - $this->parser->getStream()->expect(Token::NAME_TYPE, 'as'); - $var = new AssignNameExpression($this->parser->getStream()->expect(Token::NAME_TYPE)->getValue(), $token->getLine()); - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - - $this->parser->addImportedSymbol('template', $var->getAttribute('name')); - - return new ImportNode($macro, $var, $token->getLine(), $this->getTag()); - } - - public function getTag() - { - return 'import'; - } -} - -class_alias('Twig\TokenParser\ImportTokenParser', 'Twig_TokenParser_Import'); diff --git a/application/third_party/Twig/TokenParser/IncludeTokenParser.php b/application/third_party/Twig/TokenParser/IncludeTokenParser.php deleted file mode 100644 index 57aa4cf41af..00000000000 --- a/application/third_party/Twig/TokenParser/IncludeTokenParser.php +++ /dev/null @@ -1,68 +0,0 @@ -parser->getExpressionParser()->parseExpression(); - - list($variables, $only, $ignoreMissing) = $this->parseArguments(); - - return new IncludeNode($expr, $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag()); - } - - protected function parseArguments() - { - $stream = $this->parser->getStream(); - - $ignoreMissing = false; - if ($stream->nextIf(Token::NAME_TYPE, 'ignore')) { - $stream->expect(Token::NAME_TYPE, 'missing'); - - $ignoreMissing = true; - } - - $variables = null; - if ($stream->nextIf(Token::NAME_TYPE, 'with')) { - $variables = $this->parser->getExpressionParser()->parseExpression(); - } - - $only = false; - if ($stream->nextIf(Token::NAME_TYPE, 'only')) { - $only = true; - } - - $stream->expect(Token::BLOCK_END_TYPE); - - return [$variables, $only, $ignoreMissing]; - } - - public function getTag() - { - return 'include'; - } -} - -class_alias('Twig\TokenParser\IncludeTokenParser', 'Twig_TokenParser_Include'); diff --git a/application/third_party/Twig/TokenParser/MacroTokenParser.php b/application/third_party/Twig/TokenParser/MacroTokenParser.php deleted file mode 100644 index a0d66e7bea8..00000000000 --- a/application/third_party/Twig/TokenParser/MacroTokenParser.php +++ /dev/null @@ -1,68 +0,0 @@ - - * {% endmacro %} - * - * @final - */ -class MacroTokenParser extends AbstractTokenParser -{ - public function parse(Token $token) - { - $lineno = $token->getLine(); - $stream = $this->parser->getStream(); - $name = $stream->expect(Token::NAME_TYPE)->getValue(); - - $arguments = $this->parser->getExpressionParser()->parseArguments(true, true); - - $stream->expect(Token::BLOCK_END_TYPE); - $this->parser->pushLocalScope(); - $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); - if ($token = $stream->nextIf(Token::NAME_TYPE)) { - $value = $token->getValue(); - - if ($value != $name) { - throw new SyntaxError(sprintf('Expected endmacro for macro "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - } - $this->parser->popLocalScope(); - $stream->expect(Token::BLOCK_END_TYPE); - - $this->parser->setMacro($name, new MacroNode($name, new BodyNode([$body]), $arguments, $lineno, $this->getTag())); - - return new Node(); - } - - public function decideBlockEnd(Token $token) - { - return $token->test('endmacro'); - } - - public function getTag() - { - return 'macro'; - } -} - -class_alias('Twig\TokenParser\MacroTokenParser', 'Twig_TokenParser_Macro'); diff --git a/application/third_party/Twig/TokenParser/SandboxTokenParser.php b/application/third_party/Twig/TokenParser/SandboxTokenParser.php deleted file mode 100644 index 0f3ad9e3e6c..00000000000 --- a/application/third_party/Twig/TokenParser/SandboxTokenParser.php +++ /dev/null @@ -1,67 +0,0 @@ -parser->getStream(); - $stream->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); - $stream->expect(Token::BLOCK_END_TYPE); - - // in a sandbox tag, only include tags are allowed - if (!$body instanceof IncludeNode) { - foreach ($body as $node) { - if ($node instanceof TextNode && ctype_space($node->getAttribute('data'))) { - continue; - } - - if (!$node instanceof IncludeNode) { - throw new SyntaxError('Only "include" tags are allowed within a "sandbox" section.', $node->getTemplateLine(), $stream->getSourceContext()); - } - } - } - - return new SandboxNode($body, $token->getLine(), $this->getTag()); - } - - public function decideBlockEnd(Token $token) - { - return $token->test('endsandbox'); - } - - public function getTag() - { - return 'sandbox'; - } -} - -class_alias('Twig\TokenParser\SandboxTokenParser', 'Twig_TokenParser_Sandbox'); diff --git a/application/third_party/Twig/TokenParser/SetTokenParser.php b/application/third_party/Twig/TokenParser/SetTokenParser.php deleted file mode 100644 index eebebc69851..00000000000 --- a/application/third_party/Twig/TokenParser/SetTokenParser.php +++ /dev/null @@ -1,74 +0,0 @@ -getLine(); - $stream = $this->parser->getStream(); - $names = $this->parser->getExpressionParser()->parseAssignmentExpression(); - - $capture = false; - if ($stream->nextIf(Token::OPERATOR_TYPE, '=')) { - $values = $this->parser->getExpressionParser()->parseMultitargetExpression(); - - $stream->expect(Token::BLOCK_END_TYPE); - - if (\count($names) !== \count($values)) { - throw new SyntaxError('When using set, you must have the same number of variables and assignments.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - } else { - $capture = true; - - if (\count($names) > 1) { - throw new SyntaxError('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - - $stream->expect(Token::BLOCK_END_TYPE); - - $values = $this->parser->subparse([$this, 'decideBlockEnd'], true); - $stream->expect(Token::BLOCK_END_TYPE); - } - - return new SetNode($capture, $names, $values, $lineno, $this->getTag()); - } - - public function decideBlockEnd(Token $token) - { - return $token->test('endset'); - } - - public function getTag() - { - return 'set'; - } -} - -class_alias('Twig\TokenParser\SetTokenParser', 'Twig_TokenParser_Set'); diff --git a/application/third_party/Twig/TokenParser/SpacelessTokenParser.php b/application/third_party/Twig/TokenParser/SpacelessTokenParser.php deleted file mode 100644 index 5b5656bc64f..00000000000 --- a/application/third_party/Twig/TokenParser/SpacelessTokenParser.php +++ /dev/null @@ -1,53 +0,0 @@ - - * foo - * - * {% endspaceless %} - * {# output will be
    foo
    #} - * - * @final - */ -class SpacelessTokenParser extends AbstractTokenParser -{ - public function parse(Token $token) - { - $lineno = $token->getLine(); - - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - $body = $this->parser->subparse([$this, 'decideSpacelessEnd'], true); - $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); - - return new SpacelessNode($body, $lineno, $this->getTag()); - } - - public function decideSpacelessEnd(Token $token) - { - return $token->test('endspaceless'); - } - - public function getTag() - { - return 'spaceless'; - } -} - -class_alias('Twig\TokenParser\SpacelessTokenParser', 'Twig_TokenParser_Spaceless'); diff --git a/application/third_party/Twig/TokenParser/TokenParserInterface.php b/application/third_party/Twig/TokenParser/TokenParserInterface.php deleted file mode 100644 index 4b603b213ff..00000000000 --- a/application/third_party/Twig/TokenParser/TokenParserInterface.php +++ /dev/null @@ -1,51 +0,0 @@ - - */ -interface TokenParserInterface -{ - /** - * Sets the parser associated with this token parser. - */ - public function setParser(Parser $parser); - - /** - * Parses a token and returns a node. - * - * @return \Twig_NodeInterface - * - * @throws SyntaxError - */ - public function parse(Token $token); - - /** - * Gets the tag name associated with this token parser. - * - * @return string The tag name - */ - public function getTag(); -} - -class_alias('Twig\TokenParser\TokenParserInterface', 'Twig_TokenParserInterface'); - -// Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. -class_exists('Twig\Token'); -class_exists('Twig\Parser'); diff --git a/application/third_party/Twig/TokenParser/UseTokenParser.php b/application/third_party/Twig/TokenParser/UseTokenParser.php deleted file mode 100644 index d2e39aabeea..00000000000 --- a/application/third_party/Twig/TokenParser/UseTokenParser.php +++ /dev/null @@ -1,75 +0,0 @@ -parser->getExpressionParser()->parseExpression(); - $stream = $this->parser->getStream(); - - if (!$template instanceof ConstantExpression) { - throw new SyntaxError('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); - } - - $targets = []; - if ($stream->nextIf('with')) { - do { - $name = $stream->expect(Token::NAME_TYPE)->getValue(); - - $alias = $name; - if ($stream->nextIf('as')) { - $alias = $stream->expect(Token::NAME_TYPE)->getValue(); - } - - $targets[$name] = new ConstantExpression($alias, -1); - - if (!$stream->nextIf(Token::PUNCTUATION_TYPE, ',')) { - break; - } - } while (true); - } - - $stream->expect(Token::BLOCK_END_TYPE); - - $this->parser->addTrait(new Node(['template' => $template, 'targets' => new Node($targets)])); - - return new Node(); - } - - public function getTag() - { - return 'use'; - } -} - -class_alias('Twig\TokenParser\UseTokenParser', 'Twig_TokenParser_Use'); diff --git a/application/third_party/Twig/TokenParser/WithTokenParser.php b/application/third_party/Twig/TokenParser/WithTokenParser.php deleted file mode 100644 index 411e2b4a139..00000000000 --- a/application/third_party/Twig/TokenParser/WithTokenParser.php +++ /dev/null @@ -1,57 +0,0 @@ - - * - * @final - */ -class WithTokenParser extends AbstractTokenParser -{ - public function parse(Token $token) - { - $stream = $this->parser->getStream(); - - $variables = null; - $only = false; - if (!$stream->test(Token::BLOCK_END_TYPE)) { - $variables = $this->parser->getExpressionParser()->parseExpression(); - $only = $stream->nextIf(Token::NAME_TYPE, 'only'); - } - - $stream->expect(Token::BLOCK_END_TYPE); - - $body = $this->parser->subparse([$this, 'decideWithEnd'], true); - - $stream->expect(Token::BLOCK_END_TYPE); - - return new WithNode($body, $variables, $only, $token->getLine(), $this->getTag()); - } - - public function decideWithEnd(Token $token) - { - return $token->test('endwith'); - } - - public function getTag() - { - return 'with'; - } -} - -class_alias('Twig\TokenParser\WithTokenParser', 'Twig_TokenParser_With'); diff --git a/application/third_party/Twig/TokenStream.php b/application/third_party/Twig/TokenStream.php index 4597816959b..a1bcf44b323 100644 --- a/application/third_party/Twig/TokenStream.php +++ b/application/third_party/Twig/TokenStream.php @@ -3,17 +3,13 @@ /* * This file is part of Twig. * - * (c) Fabien Potencier - * (c) Armin Ronacher + * (c) 2009 Fabien Potencier + * (c) 2009 Armin Ronacher * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ -namespace Twig; - -use Twig\Error\SyntaxError; - /** * Represents a token stream. * @@ -21,7 +17,7 @@ * * @author Fabien Potencier */ -class TokenStream +class Twig_TokenStream { protected $tokens; protected $current = 0; @@ -36,11 +32,11 @@ class TokenStream */ public function __construct(array $tokens, $name = null, $source = null) { - if (!$name instanceof Source) { + if (!$name instanceof Twig_Source) { if (null !== $name || null !== $source) { - @trigger_error(sprintf('Passing a string as the $name argument of %s() is deprecated since version 1.27. Pass a \Twig\Source instance instead.', __METHOD__), E_USER_DEPRECATED); + @trigger_error(sprintf('Passing a string as the $name argument of %s() is deprecated since version 1.27. Pass a Twig_Source instance instead.', __METHOD__), E_USER_DEPRECATED); } - $this->source = new Source($source, $name); + $this->source = new Twig_Source($source, $name); } else { $this->source = $name; } @@ -58,18 +54,18 @@ public function __toString() public function injectTokens(array $tokens) { - $this->tokens = array_merge(\array_slice($this->tokens, 0, $this->current), $tokens, \array_slice($this->tokens, $this->current)); + $this->tokens = array_merge(array_slice($this->tokens, 0, $this->current), $tokens, array_slice($this->tokens, $this->current)); } /** * Sets the pointer to the next token and returns the old one. * - * @return Token + * @return Twig_Token */ public function next() { if (!isset($this->tokens[++$this->current])) { - throw new SyntaxError('Unexpected end of template.', $this->tokens[$this->current - 1]->getLine(), $this->source); + throw new Twig_Error_Syntax('Unexpected end of template.', $this->tokens[$this->current - 1]->getLine(), $this->source); } return $this->tokens[$this->current - 1]; @@ -78,7 +74,7 @@ public function next() /** * Tests a token, sets the pointer to the next one and returns it or throws a syntax error. * - * @return Token|null The next token if the condition is true, null otherwise + * @return Twig_Token|null The next token if the condition is true, null otherwise */ public function nextIf($primary, $secondary = null) { @@ -90,18 +86,17 @@ public function nextIf($primary, $secondary = null) /** * Tests a token and returns it or throws a syntax error. * - * @return Token + * @return Twig_Token */ public function expect($type, $value = null, $message = null) { $token = $this->tokens[$this->current]; if (!$token->test($type, $value)) { $line = $token->getLine(); - throw new SyntaxError(sprintf('%sUnexpected token "%s"%s ("%s" expected%s).', + throw new Twig_Error_Syntax(sprintf('%sUnexpected token "%s" of value "%s" ("%s" expected%s).', $message ? $message.'. ' : '', - Token::typeToEnglish($token->getType()), - $token->getValue() ? sprintf(' of value "%s"', $token->getValue()) : '', - Token::typeToEnglish($type), $value ? sprintf(' with value "%s"', $value) : ''), + Twig_Token::typeToEnglish($token->getType()), $token->getValue(), + Twig_Token::typeToEnglish($type), $value ? sprintf(' with value "%s"', $value) : ''), $line, $this->source ); @@ -116,12 +111,12 @@ public function expect($type, $value = null, $message = null) * * @param int $number * - * @return Token + * @return Twig_Token */ public function look($number = 1) { if (!isset($this->tokens[$this->current + $number])) { - throw new SyntaxError('Unexpected end of template.', $this->tokens[$this->current + $number - 1]->getLine(), $this->source); + throw new Twig_Error_Syntax('Unexpected end of template.', $this->tokens[$this->current + $number - 1]->getLine(), $this->source); } return $this->tokens[$this->current + $number]; @@ -144,11 +139,11 @@ public function test($primary, $secondary = null) */ public function isEOF() { - return Token::EOF_TYPE === $this->tokens[$this->current]->getType(); + return $this->tokens[$this->current]->getType() === Twig_Token::EOF_TYPE; } /** - * @return Token + * @return Twig_Token */ public function getCurrent() { @@ -188,7 +183,7 @@ public function getSource() /** * Gets the source associated with this stream. * - * @return Source + * @return Twig_Source * * @internal */ @@ -197,5 +192,3 @@ public function getSourceContext() return $this->source; } } - -class_alias('Twig\TokenStream', 'Twig_TokenStream'); diff --git a/application/third_party/Twig/TwigFilter.php b/application/third_party/Twig/TwigFilter.php deleted file mode 100644 index 089a6d1b889..00000000000 --- a/application/third_party/Twig/TwigFilter.php +++ /dev/null @@ -1,128 +0,0 @@ - - */ -class TwigFilter -{ - protected $name; - protected $callable; - protected $options; - protected $arguments = []; - - public function __construct($name, $callable, array $options = []) - { - $this->name = $name; - $this->callable = $callable; - $this->options = array_merge([ - 'needs_environment' => false, - 'needs_context' => false, - 'is_variadic' => false, - 'is_safe' => null, - 'is_safe_callback' => null, - 'pre_escape' => null, - 'preserves_safety' => null, - 'node_class' => '\Twig\Node\Expression\FilterExpression', - 'deprecated' => false, - 'alternative' => null, - ], $options); - } - - public function getName() - { - return $this->name; - } - - public function getCallable() - { - return $this->callable; - } - - public function getNodeClass() - { - return $this->options['node_class']; - } - - public function setArguments($arguments) - { - $this->arguments = $arguments; - } - - public function getArguments() - { - return $this->arguments; - } - - public function needsEnvironment() - { - return $this->options['needs_environment']; - } - - public function needsContext() - { - return $this->options['needs_context']; - } - - public function getSafe(Node $filterArgs) - { - if (null !== $this->options['is_safe']) { - return $this->options['is_safe']; - } - - if (null !== $this->options['is_safe_callback']) { - return \call_user_func($this->options['is_safe_callback'], $filterArgs); - } - } - - public function getPreservesSafety() - { - return $this->options['preserves_safety']; - } - - public function getPreEscape() - { - return $this->options['pre_escape']; - } - - public function isVariadic() - { - return $this->options['is_variadic']; - } - - public function isDeprecated() - { - return (bool) $this->options['deprecated']; - } - - public function getDeprecatedVersion() - { - return $this->options['deprecated']; - } - - public function getAlternative() - { - return $this->options['alternative']; - } -} - -class_alias('Twig\TwigFilter', 'Twig_SimpleFilter'); - -// Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. -class_exists('Twig\Node\Node'); diff --git a/application/third_party/Twig/TwigFunction.php b/application/third_party/Twig/TwigFunction.php deleted file mode 100644 index 374f07071e6..00000000000 --- a/application/third_party/Twig/TwigFunction.php +++ /dev/null @@ -1,118 +0,0 @@ - - */ -class TwigFunction -{ - protected $name; - protected $callable; - protected $options; - protected $arguments = []; - - public function __construct($name, $callable, array $options = []) - { - $this->name = $name; - $this->callable = $callable; - $this->options = array_merge([ - 'needs_environment' => false, - 'needs_context' => false, - 'is_variadic' => false, - 'is_safe' => null, - 'is_safe_callback' => null, - 'node_class' => '\Twig\Node\Expression\FunctionExpression', - 'deprecated' => false, - 'alternative' => null, - ], $options); - } - - public function getName() - { - return $this->name; - } - - public function getCallable() - { - return $this->callable; - } - - public function getNodeClass() - { - return $this->options['node_class']; - } - - public function setArguments($arguments) - { - $this->arguments = $arguments; - } - - public function getArguments() - { - return $this->arguments; - } - - public function needsEnvironment() - { - return $this->options['needs_environment']; - } - - public function needsContext() - { - return $this->options['needs_context']; - } - - public function getSafe(Node $functionArgs) - { - if (null !== $this->options['is_safe']) { - return $this->options['is_safe']; - } - - if (null !== $this->options['is_safe_callback']) { - return \call_user_func($this->options['is_safe_callback'], $functionArgs); - } - - return []; - } - - public function isVariadic() - { - return $this->options['is_variadic']; - } - - public function isDeprecated() - { - return (bool) $this->options['deprecated']; - } - - public function getDeprecatedVersion() - { - return $this->options['deprecated']; - } - - public function getAlternative() - { - return $this->options['alternative']; - } -} - -class_alias('Twig\TwigFunction', 'Twig_SimpleFunction'); - -// Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. -class_exists('Twig\Node\Node'); diff --git a/application/third_party/Twig/TwigTest.php b/application/third_party/Twig/TwigTest.php deleted file mode 100644 index 5054965fe9a..00000000000 --- a/application/third_party/Twig/TwigTest.php +++ /dev/null @@ -1,87 +0,0 @@ - - */ -class TwigTest -{ - protected $name; - protected $callable; - protected $options; - - private $arguments = []; - - public function __construct($name, $callable, array $options = []) - { - $this->name = $name; - $this->callable = $callable; - $this->options = array_merge([ - 'is_variadic' => false, - 'node_class' => '\Twig\Node\Expression\TestExpression', - 'deprecated' => false, - 'alternative' => null, - ], $options); - } - - public function getName() - { - return $this->name; - } - - public function getCallable() - { - return $this->callable; - } - - public function getNodeClass() - { - return $this->options['node_class']; - } - - public function isVariadic() - { - return $this->options['is_variadic']; - } - - public function isDeprecated() - { - return (bool) $this->options['deprecated']; - } - - public function getDeprecatedVersion() - { - return $this->options['deprecated']; - } - - public function getAlternative() - { - return $this->options['alternative']; - } - - public function setArguments($arguments) - { - $this->arguments = $arguments; - } - - public function getArguments() - { - return $this->arguments; - } -} - -class_alias('Twig\TwigTest', 'Twig_SimpleTest'); diff --git a/application/third_party/Twig/Util/DeprecationCollector.php b/application/third_party/Twig/Util/DeprecationCollector.php index 09917e927c1..1e517f5c01f 100644 --- a/application/third_party/Twig/Util/DeprecationCollector.php +++ b/application/third_party/Twig/Util/DeprecationCollector.php @@ -9,23 +9,17 @@ * file that was distributed with this source code. */ -namespace Twig\Util; - -use Twig\Environment; -use Twig\Error\SyntaxError; -use Twig\Source; - /** * @author Fabien Potencier * * @final */ -class DeprecationCollector +class Twig_Util_DeprecationCollector { private $twig; private $deprecations; - public function __construct(Environment $twig) + public function __construct(Twig_Environment $twig) { $this->twig = $twig; } @@ -40,32 +34,32 @@ public function __construct(Environment $twig) */ public function collectDir($dir, $ext = '.twig') { - $iterator = new \RegexIterator( - new \RecursiveIteratorIterator( - new \RecursiveDirectoryIterator($dir), \RecursiveIteratorIterator::LEAVES_ONLY + $iterator = new RegexIterator( + new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY ), '{'.preg_quote($ext).'$}' ); - return $this->collect(new TemplateDirIterator($iterator)); + return $this->collect(new Twig_Util_TemplateDirIterator($iterator)); } /** * Returns deprecations for passed templates. * - * @param \Traversable $iterator An iterator of templates (where keys are template names and values the contents of the template) + * @param Iterator $iterator An iterator of templates (where keys are template names and values the contents of the template) * * @return array An array of deprecations */ - public function collect(\Traversable $iterator) + public function collect(Iterator $iterator) { - $this->deprecations = []; + $this->deprecations = array(); - set_error_handler([$this, 'errorHandler']); + set_error_handler(array($this, 'errorHandler')); foreach ($iterator as $name => $contents) { try { - $this->twig->parse($this->twig->tokenize(new Source($contents, $name))); - } catch (SyntaxError $e) { + $this->twig->parse($this->twig->tokenize($contents, $name)); + } catch (Twig_Error_Syntax $e) { // ignore templates containing syntax errors } } @@ -73,7 +67,7 @@ public function collect(\Traversable $iterator) restore_error_handler(); $deprecations = $this->deprecations; - $this->deprecations = []; + $this->deprecations = array(); return $deprecations; } @@ -88,5 +82,3 @@ public function errorHandler($type, $msg) } } } - -class_alias('Twig\Util\DeprecationCollector', 'Twig_Util_DeprecationCollector'); diff --git a/application/third_party/Twig/Util/TemplateDirIterator.php b/application/third_party/Twig/Util/TemplateDirIterator.php index 1ab0dac59d5..3fb8932780d 100644 --- a/application/third_party/Twig/Util/TemplateDirIterator.php +++ b/application/third_party/Twig/Util/TemplateDirIterator.php @@ -9,12 +9,10 @@ * file that was distributed with this source code. */ -namespace Twig\Util; - /** * @author Fabien Potencier */ -class TemplateDirIterator extends \IteratorIterator +class Twig_Util_TemplateDirIterator extends IteratorIterator { public function current() { @@ -26,5 +24,3 @@ public function key() return (string) parent::key(); } } - -class_alias('Twig\Util\TemplateDirIterator', 'Twig_Util_TemplateDirIterator'); diff --git a/third_party/Twig/ETwigViewRenderer.php b/third_party/Twig/ETwigViewRenderer.php index edc64b238b5..97426cd80c8 100644 --- a/third_party/Twig/ETwigViewRenderer.php +++ b/third_party/Twig/ETwigViewRenderer.php @@ -92,7 +92,7 @@ function init() //$loader = new Twig_Loader_Filesystem($this->_paths); // LSHack - $loader = new Twig\Loader\FilesystemLoader(); + $loader = new Twig_Loader_Filesystem(); $defaultOptions = array( 'autoescape' => false, // false because other way Twig escapes all HTML in templates @@ -110,7 +110,7 @@ function init() // Adding global 'void' function (usage: {{void(App.clientScript.registerScriptFile(...))}}) // (@see ETwigViewRendererVoidFunction below for details) - $this->_twig->addFunction(new Twig\TwigFunction('void', 'ETwigViewRendererVoidFunction')); + $this->_twig->addFunction(new Twig_SimpleFunction('void', 'ETwigViewRendererVoidFunction')); // Adding custom globals (objects or static classes) if (!empty($this->globals)) { @@ -255,12 +255,7 @@ public function getTwig() */ private function _addCustom($classType, $elements) { - if ($classType === 'Function') { - $classFunction = 'Twig_Simple' . $classType; - } elseif ($classType === 'Filter') { - $classFunction = '\Twig\TwigFilter'; - } - // Twig_SimpleFilter + $classFunction = 'Twig_Simple' . $classType; foreach ($elements as $name => $func) { $twigElement = null; @@ -269,22 +264,19 @@ private function _addCustom($classType, $elements) // Just a name of function case is_string($func): $twigElement = new $classFunction($name, $func); - break; + break; // Name of function + options array case is_array($func) && is_string($func[0]) && isset($func[1]) && is_array($func[1]): $twigElement = new $classFunction($name, $func[0], $func[1]); - break; + break; } if ($twigElement !== null) { - //if ($classType == 'Filter') { - //echo '
    '; var_dump($twigElement); echo '
    ';die; - //} $this->_twig->{'add'.$classType}($twigElement); } else { throw new CException(Yii::t('yiiext', - 'Incorrect options for "{classType}" [{name}]', - array('{classType}'=>$classType, '{name}'=>$name))); + 'Incorrect options for "{classType}" [{name}]', + array('{classType}'=>$classType, '{name}'=>$name))); } } }