diff --git a/.gitignore b/.gitignore index 5f15152..3bc7284 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ /._sync_504320134e4a.db-shm /._sync_504320134e4a.db-wal /.owncloudsync.log -/.sync-exclude.lst +#/.sync-exclude.lst # Linux *~ @@ -18,5 +18,5 @@ desktop.ini ._* # Composer -/composer.phar -/vendor +#/composer.phar +#/vendor diff --git a/.sync-exclude.lst b/.sync-exclude.lst new file mode 100644 index 0000000..adf086c --- /dev/null +++ b/.sync-exclude.lst @@ -0,0 +1,3 @@ +.htaccess +.git +.gitignore diff --git a/themes/Travelify-tr00/styles/style.css b/themes/Travelify-tr00/styles/style.css index 5d5f3ca..571e4e0 100644 --- a/themes/Travelify-tr00/styles/style.css +++ b/themes/Travelify-tr00/styles/style.css @@ -2520,8 +2520,10 @@ blockquote { font-size: 1rem; } #main-nav { - background-image: url(../images/temno.png); + /*background-image: url(../images/temno.png);*/ border: none; + background: black; + color: darkred; } header, #main { @@ -2537,6 +2539,7 @@ header .hgroup-right { } header .hgroup-right img { height: 100%; + float: right; } header .hgroup-wrap { padding-right: 200px; diff --git a/vendor/autoload.php b/vendor/autoload.php new file mode 100644 index 0000000..d1c575a --- /dev/null +++ b/vendor/autoload.php @@ -0,0 +1,7 @@ + + * Jordi Boggiano + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Composer\Autoload; + +/** + * ClassLoader implements a PSR-0, PSR-4 and classmap class loader. + * + * $loader = new \Composer\Autoload\ClassLoader(); + * + * // register classes with namespaces + * $loader->add('Symfony\Component', __DIR__.'/component'); + * $loader->add('Symfony', __DIR__.'/framework'); + * + * // activate the autoloader + * $loader->register(); + * + * // to enable searching the include path (eg. for PEAR packages) + * $loader->setUseIncludePath(true); + * + * In this example, if you try to use a class in the Symfony\Component + * namespace or one of its children (Symfony\Component\Console for instance), + * the autoloader will first look for the class under the component/ + * directory, and it will then fallback to the framework/ directory if not + * found before giving up. + * + * This class is loosely based on the Symfony UniversalClassLoader. + * + * @author Fabien Potencier + * @author Jordi Boggiano + * @see http://www.php-fig.org/psr/psr-0/ + * @see http://www.php-fig.org/psr/psr-4/ + */ +class ClassLoader +{ + // PSR-4 + private $prefixLengthsPsr4 = array(); + private $prefixDirsPsr4 = array(); + private $fallbackDirsPsr4 = array(); + + // PSR-0 + private $prefixesPsr0 = array(); + private $fallbackDirsPsr0 = array(); + + private $useIncludePath = false; + private $classMap = array(); + private $classMapAuthoritative = false; + private $missingClasses = array(); + private $apcuPrefix; + + public function getPrefixes() + { + if (!empty($this->prefixesPsr0)) { + return call_user_func_array('array_merge', $this->prefixesPsr0); + } + + return array(); + } + + public function getPrefixesPsr4() + { + return $this->prefixDirsPsr4; + } + + public function getFallbackDirs() + { + return $this->fallbackDirsPsr0; + } + + public function getFallbackDirsPsr4() + { + return $this->fallbackDirsPsr4; + } + + public function getClassMap() + { + return $this->classMap; + } + + /** + * @param array $classMap Class to filename map + */ + public function addClassMap(array $classMap) + { + if ($this->classMap) { + $this->classMap = array_merge($this->classMap, $classMap); + } else { + $this->classMap = $classMap; + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, either + * appending or prepending to the ones previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 root directories + * @param bool $prepend Whether to prepend the directories + */ + public function add($prefix, $paths, $prepend = false) + { + if (!$prefix) { + if ($prepend) { + $this->fallbackDirsPsr0 = array_merge( + (array) $paths, + $this->fallbackDirsPsr0 + ); + } else { + $this->fallbackDirsPsr0 = array_merge( + $this->fallbackDirsPsr0, + (array) $paths + ); + } + + return; + } + + $first = $prefix[0]; + if (!isset($this->prefixesPsr0[$first][$prefix])) { + $this->prefixesPsr0[$first][$prefix] = (array) $paths; + + return; + } + if ($prepend) { + $this->prefixesPsr0[$first][$prefix] = array_merge( + (array) $paths, + $this->prefixesPsr0[$first][$prefix] + ); + } else { + $this->prefixesPsr0[$first][$prefix] = array_merge( + $this->prefixesPsr0[$first][$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, either + * appending or prepending to the ones previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + * @param bool $prepend Whether to prepend the directories + * + * @throws \InvalidArgumentException + */ + public function addPsr4($prefix, $paths, $prepend = false) + { + if (!$prefix) { + // Register directories for the root namespace. + if ($prepend) { + $this->fallbackDirsPsr4 = array_merge( + (array) $paths, + $this->fallbackDirsPsr4 + ); + } else { + $this->fallbackDirsPsr4 = array_merge( + $this->fallbackDirsPsr4, + (array) $paths + ); + } + } elseif (!isset($this->prefixDirsPsr4[$prefix])) { + // Register directories for a new namespace. + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } elseif ($prepend) { + // Prepend directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + (array) $paths, + $this->prefixDirsPsr4[$prefix] + ); + } else { + // Append directories for an already registered namespace. + $this->prefixDirsPsr4[$prefix] = array_merge( + $this->prefixDirsPsr4[$prefix], + (array) $paths + ); + } + } + + /** + * Registers a set of PSR-0 directories for a given prefix, + * replacing any others previously set for this prefix. + * + * @param string $prefix The prefix + * @param array|string $paths The PSR-0 base directories + */ + public function set($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr0 = (array) $paths; + } else { + $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths; + } + } + + /** + * Registers a set of PSR-4 directories for a given namespace, + * replacing any others previously set for this namespace. + * + * @param string $prefix The prefix/namespace, with trailing '\\' + * @param array|string $paths The PSR-4 base directories + * + * @throws \InvalidArgumentException + */ + public function setPsr4($prefix, $paths) + { + if (!$prefix) { + $this->fallbackDirsPsr4 = (array) $paths; + } else { + $length = strlen($prefix); + if ('\\' !== $prefix[$length - 1]) { + throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator."); + } + $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length; + $this->prefixDirsPsr4[$prefix] = (array) $paths; + } + } + + /** + * Turns on searching the include path for class files. + * + * @param bool $useIncludePath + */ + public function setUseIncludePath($useIncludePath) + { + $this->useIncludePath = $useIncludePath; + } + + /** + * Can be used to check if the autoloader uses the include path to check + * for classes. + * + * @return bool + */ + public function getUseIncludePath() + { + return $this->useIncludePath; + } + + /** + * Turns off searching the prefix and fallback directories for classes + * that have not been registered with the class map. + * + * @param bool $classMapAuthoritative + */ + public function setClassMapAuthoritative($classMapAuthoritative) + { + $this->classMapAuthoritative = $classMapAuthoritative; + } + + /** + * Should class lookup fail if not found in the current class map? + * + * @return bool + */ + public function isClassMapAuthoritative() + { + return $this->classMapAuthoritative; + } + + /** + * APCu prefix to use to cache found/not-found classes, if the extension is enabled. + * + * @param string|null $apcuPrefix + */ + public function setApcuPrefix($apcuPrefix) + { + $this->apcuPrefix = function_exists('apcu_fetch') && filter_var(ini_get('apc.enabled'), FILTER_VALIDATE_BOOLEAN) ? $apcuPrefix : null; + } + + /** + * The APCu prefix in use, or null if APCu caching is not enabled. + * + * @return string|null + */ + public function getApcuPrefix() + { + return $this->apcuPrefix; + } + + /** + * Registers this instance as an autoloader. + * + * @param bool $prepend Whether to prepend the autoloader or not + */ + public function register($prepend = false) + { + spl_autoload_register(array($this, 'loadClass'), true, $prepend); + } + + /** + * Unregisters this instance as an autoloader. + */ + public function unregister() + { + spl_autoload_unregister(array($this, 'loadClass')); + } + + /** + * Loads the given class or interface. + * + * @param string $class The name of the class + * @return bool|null True if loaded, null otherwise + */ + public function loadClass($class) + { + if ($file = $this->findFile($class)) { + includeFile($file); + + return true; + } + } + + /** + * Finds the path to the file where the class is defined. + * + * @param string $class The name of the class + * + * @return string|false The path if found, false otherwise + */ + public function findFile($class) + { + // class map lookup + if (isset($this->classMap[$class])) { + return $this->classMap[$class]; + } + if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) { + return false; + } + if (null !== $this->apcuPrefix) { + $file = apcu_fetch($this->apcuPrefix.$class, $hit); + if ($hit) { + return $file; + } + } + + $file = $this->findFileWithExtension($class, '.php'); + + // Search for Hack files if we are running on HHVM + if (false === $file && defined('HHVM_VERSION')) { + $file = $this->findFileWithExtension($class, '.hh'); + } + + if (null !== $this->apcuPrefix) { + apcu_add($this->apcuPrefix.$class, $file); + } + + if (false === $file) { + // Remember that this class does not exist. + $this->missingClasses[$class] = true; + } + + return $file; + } + + private function findFileWithExtension($class, $ext) + { + // PSR-4 lookup + $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext; + + $first = $class[0]; + if (isset($this->prefixLengthsPsr4[$first])) { + $subPath = $class; + while (false !== $lastPos = strrpos($subPath, '\\')) { + $subPath = substr($subPath, 0, $lastPos); + $search = $subPath . '\\'; + if (isset($this->prefixDirsPsr4[$search])) { + $pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1); + foreach ($this->prefixDirsPsr4[$search] as $dir) { + if (file_exists($file = $dir . $pathEnd)) { + return $file; + } + } + } + } + } + + // PSR-4 fallback dirs + foreach ($this->fallbackDirsPsr4 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) { + return $file; + } + } + + // PSR-0 lookup + if (false !== $pos = strrpos($class, '\\')) { + // namespaced class name + $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1) + . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR); + } else { + // PEAR-like class name + $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext; + } + + if (isset($this->prefixesPsr0[$first])) { + foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) { + if (0 === strpos($class, $prefix)) { + foreach ($dirs as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + } + } + } + + // PSR-0 fallback dirs + foreach ($this->fallbackDirsPsr0 as $dir) { + if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) { + return $file; + } + } + + // PSR-0 include paths. + if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) { + return $file; + } + + return false; + } +} + +/** + * Scope isolated include. + * + * Prevents access to $this/self from included files. + */ +function includeFile($file) +{ + include $file; +} diff --git a/vendor/composer/LICENSE b/vendor/composer/LICENSE new file mode 100644 index 0000000..f27399a --- /dev/null +++ b/vendor/composer/LICENSE @@ -0,0 +1,21 @@ + +Copyright (c) Nils Adermann, Jordi Boggiano + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + diff --git a/vendor/composer/autoload_classmap.php b/vendor/composer/autoload_classmap.php new file mode 100644 index 0000000..fc4a5de --- /dev/null +++ b/vendor/composer/autoload_classmap.php @@ -0,0 +1,412 @@ + $baseDir . '/plugins/PicoDeprecated/lib/AbstractPicoCompatPlugin.php', + 'AbstractPicoPlugin' => $vendorDir . '/picocms/pico/lib/AbstractPicoPlugin.php', + 'AbstractPicoPluginApiCompatPlugin' => $baseDir . '/plugins/PicoDeprecated/lib/AbstractPicoPluginApiCompatPlugin.php', + 'Parsedown' => $vendorDir . '/erusev/parsedown/Parsedown.php', + 'ParsedownExtra' => $vendorDir . '/erusev/parsedown-extra/ParsedownExtra.php', + 'Pico' => $vendorDir . '/picocms/pico/lib/Pico.php', + 'PicoCompatPluginInterface' => $baseDir . '/plugins/PicoDeprecated/lib/PicoCompatPluginInterface.php', + 'PicoDeprecated' => $baseDir . '/plugins/PicoDeprecated/PicoDeprecated.php', + 'PicoMainCompatPlugin' => $baseDir . '/plugins/PicoDeprecated/plugins/PicoMainCompatPlugin.php', + 'PicoPluginApi0CompatPlugin' => $baseDir . '/plugins/PicoDeprecated/plugins/PicoPluginApi0CompatPlugin.php', + 'PicoPluginApi1CompatPlugin' => $baseDir . '/plugins/PicoDeprecated/plugins/PicoPluginApi1CompatPlugin.php', + 'PicoPluginApi2CompatPlugin' => $baseDir . '/plugins/PicoDeprecated/plugins/PicoPluginApi2CompatPlugin.php', + 'PicoPluginApiCompatPluginInterface' => $baseDir . '/plugins/PicoDeprecated/lib/PicoPluginApiCompatPluginInterface.php', + 'PicoPluginInterface' => $vendorDir . '/picocms/pico/lib/PicoPluginInterface.php', + 'PicoThemeApi0CompatPlugin' => $baseDir . '/plugins/PicoDeprecated/plugins/PicoThemeApi0CompatPlugin.php', + 'PicoThemeApi1CompatPlugin' => $baseDir . '/plugins/PicoDeprecated/plugins/PicoThemeApi1CompatPlugin.php', + 'PicoThemeApi2CompatPlugin' => $baseDir . '/plugins/PicoDeprecated/plugins/PicoThemeApi2CompatPlugin.php', + 'PicoTwigExtension' => $vendorDir . '/picocms/pico/lib/PicoTwigExtension.php', + 'Pico\\Composer\\Installer\\PluginInstaller' => $vendorDir . '/picocms/composer-installer/src/Installer/PluginInstaller.php', + 'Symfony\\Component\\Yaml\\Dumper' => $vendorDir . '/symfony/yaml/Dumper.php', + 'Symfony\\Component\\Yaml\\Escaper' => $vendorDir . '/symfony/yaml/Escaper.php', + 'Symfony\\Component\\Yaml\\Exception\\DumpException' => $vendorDir . '/symfony/yaml/Exception/DumpException.php', + 'Symfony\\Component\\Yaml\\Exception\\ExceptionInterface' => $vendorDir . '/symfony/yaml/Exception/ExceptionInterface.php', + 'Symfony\\Component\\Yaml\\Exception\\ParseException' => $vendorDir . '/symfony/yaml/Exception/ParseException.php', + 'Symfony\\Component\\Yaml\\Exception\\RuntimeException' => $vendorDir . '/symfony/yaml/Exception/RuntimeException.php', + 'Symfony\\Component\\Yaml\\Inline' => $vendorDir . '/symfony/yaml/Inline.php', + 'Symfony\\Component\\Yaml\\Parser' => $vendorDir . '/symfony/yaml/Parser.php', + 'Symfony\\Component\\Yaml\\Unescaper' => $vendorDir . '/symfony/yaml/Unescaper.php', + 'Symfony\\Component\\Yaml\\Yaml' => $vendorDir . '/symfony/yaml/Yaml.php', + 'Symfony\\Polyfill\\Ctype\\Ctype' => $vendorDir . '/symfony/polyfill-ctype/Ctype.php', + 'Twig\\Cache\\CacheInterface' => $vendorDir . '/twig/twig/src/Cache/CacheInterface.php', + 'Twig\\Cache\\FilesystemCache' => $vendorDir . '/twig/twig/src/Cache/FilesystemCache.php', + 'Twig\\Cache\\NullCache' => $vendorDir . '/twig/twig/src/Cache/NullCache.php', + 'Twig\\Compiler' => $vendorDir . '/twig/twig/src/Compiler.php', + 'Twig\\Environment' => $vendorDir . '/twig/twig/src/Environment.php', + 'Twig\\Error\\Error' => $vendorDir . '/twig/twig/src/Error/Error.php', + 'Twig\\Error\\LoaderError' => $vendorDir . '/twig/twig/src/Error/LoaderError.php', + 'Twig\\Error\\RuntimeError' => $vendorDir . '/twig/twig/src/Error/RuntimeError.php', + 'Twig\\Error\\SyntaxError' => $vendorDir . '/twig/twig/src/Error/SyntaxError.php', + 'Twig\\ExpressionParser' => $vendorDir . '/twig/twig/src/ExpressionParser.php', + 'Twig\\Extension\\AbstractExtension' => $vendorDir . '/twig/twig/src/Extension/AbstractExtension.php', + 'Twig\\Extension\\CoreExtension' => $vendorDir . '/twig/twig/src/Extension/CoreExtension.php', + 'Twig\\Extension\\DebugExtension' => $vendorDir . '/twig/twig/src/Extension/DebugExtension.php', + 'Twig\\Extension\\EscaperExtension' => $vendorDir . '/twig/twig/src/Extension/EscaperExtension.php', + 'Twig\\Extension\\ExtensionInterface' => $vendorDir . '/twig/twig/src/Extension/ExtensionInterface.php', + 'Twig\\Extension\\GlobalsInterface' => $vendorDir . '/twig/twig/src/Extension/GlobalsInterface.php', + 'Twig\\Extension\\InitRuntimeInterface' => $vendorDir . '/twig/twig/src/Extension/InitRuntimeInterface.php', + 'Twig\\Extension\\OptimizerExtension' => $vendorDir . '/twig/twig/src/Extension/OptimizerExtension.php', + 'Twig\\Extension\\ProfilerExtension' => $vendorDir . '/twig/twig/src/Extension/ProfilerExtension.php', + 'Twig\\Extension\\RuntimeExtensionInterface' => $vendorDir . '/twig/twig/src/Extension/RuntimeExtensionInterface.php', + 'Twig\\Extension\\SandboxExtension' => $vendorDir . '/twig/twig/src/Extension/SandboxExtension.php', + 'Twig\\Extension\\StagingExtension' => $vendorDir . '/twig/twig/src/Extension/StagingExtension.php', + 'Twig\\Extension\\StringLoaderExtension' => $vendorDir . '/twig/twig/src/Extension/StringLoaderExtension.php', + 'Twig\\FileExtensionEscapingStrategy' => $vendorDir . '/twig/twig/src/FileExtensionEscapingStrategy.php', + 'Twig\\Lexer' => $vendorDir . '/twig/twig/src/Lexer.php', + 'Twig\\Loader\\ArrayLoader' => $vendorDir . '/twig/twig/src/Loader/ArrayLoader.php', + 'Twig\\Loader\\ChainLoader' => $vendorDir . '/twig/twig/src/Loader/ChainLoader.php', + 'Twig\\Loader\\ExistsLoaderInterface' => $vendorDir . '/twig/twig/src/Loader/ExistsLoaderInterface.php', + 'Twig\\Loader\\FilesystemLoader' => $vendorDir . '/twig/twig/src/Loader/FilesystemLoader.php', + 'Twig\\Loader\\LoaderInterface' => $vendorDir . '/twig/twig/src/Loader/LoaderInterface.php', + 'Twig\\Loader\\SourceContextLoaderInterface' => $vendorDir . '/twig/twig/src/Loader/SourceContextLoaderInterface.php', + 'Twig\\Markup' => $vendorDir . '/twig/twig/src/Markup.php', + 'Twig\\NodeTraverser' => $vendorDir . '/twig/twig/src/NodeTraverser.php', + 'Twig\\NodeVisitor\\AbstractNodeVisitor' => $vendorDir . '/twig/twig/src/NodeVisitor/AbstractNodeVisitor.php', + 'Twig\\NodeVisitor\\EscaperNodeVisitor' => $vendorDir . '/twig/twig/src/NodeVisitor/EscaperNodeVisitor.php', + 'Twig\\NodeVisitor\\NodeVisitorInterface' => $vendorDir . '/twig/twig/src/NodeVisitor/NodeVisitorInterface.php', + 'Twig\\NodeVisitor\\OptimizerNodeVisitor' => $vendorDir . '/twig/twig/src/NodeVisitor/OptimizerNodeVisitor.php', + 'Twig\\NodeVisitor\\SafeAnalysisNodeVisitor' => $vendorDir . '/twig/twig/src/NodeVisitor/SafeAnalysisNodeVisitor.php', + 'Twig\\NodeVisitor\\SandboxNodeVisitor' => $vendorDir . '/twig/twig/src/NodeVisitor/SandboxNodeVisitor.php', + 'Twig\\Node\\AutoEscapeNode' => $vendorDir . '/twig/twig/src/Node/AutoEscapeNode.php', + 'Twig\\Node\\BlockNode' => $vendorDir . '/twig/twig/src/Node/BlockNode.php', + 'Twig\\Node\\BlockReferenceNode' => $vendorDir . '/twig/twig/src/Node/BlockReferenceNode.php', + 'Twig\\Node\\BodyNode' => $vendorDir . '/twig/twig/src/Node/BodyNode.php', + 'Twig\\Node\\CheckSecurityNode' => $vendorDir . '/twig/twig/src/Node/CheckSecurityNode.php', + 'Twig\\Node\\DeprecatedNode' => $vendorDir . '/twig/twig/src/Node/DeprecatedNode.php', + 'Twig\\Node\\DoNode' => $vendorDir . '/twig/twig/src/Node/DoNode.php', + 'Twig\\Node\\EmbedNode' => $vendorDir . '/twig/twig/src/Node/EmbedNode.php', + 'Twig\\Node\\Expression\\AbstractExpression' => $vendorDir . '/twig/twig/src/Node/Expression/AbstractExpression.php', + 'Twig\\Node\\Expression\\ArrayExpression' => $vendorDir . '/twig/twig/src/Node/Expression/ArrayExpression.php', + 'Twig\\Node\\Expression\\AssignNameExpression' => $vendorDir . '/twig/twig/src/Node/Expression/AssignNameExpression.php', + 'Twig\\Node\\Expression\\Binary\\AbstractBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/AbstractBinary.php', + 'Twig\\Node\\Expression\\Binary\\AddBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/AddBinary.php', + 'Twig\\Node\\Expression\\Binary\\AndBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/AndBinary.php', + 'Twig\\Node\\Expression\\Binary\\BitwiseAndBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/BitwiseAndBinary.php', + 'Twig\\Node\\Expression\\Binary\\BitwiseOrBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/BitwiseOrBinary.php', + 'Twig\\Node\\Expression\\Binary\\BitwiseXorBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/BitwiseXorBinary.php', + 'Twig\\Node\\Expression\\Binary\\ConcatBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/ConcatBinary.php', + 'Twig\\Node\\Expression\\Binary\\DivBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/DivBinary.php', + 'Twig\\Node\\Expression\\Binary\\EndsWithBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/EndsWithBinary.php', + 'Twig\\Node\\Expression\\Binary\\EqualBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/EqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\FloorDivBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/FloorDivBinary.php', + 'Twig\\Node\\Expression\\Binary\\GreaterBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/GreaterBinary.php', + 'Twig\\Node\\Expression\\Binary\\GreaterEqualBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/GreaterEqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\InBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/InBinary.php', + 'Twig\\Node\\Expression\\Binary\\LessBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/LessBinary.php', + 'Twig\\Node\\Expression\\Binary\\LessEqualBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/LessEqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\MatchesBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/MatchesBinary.php', + 'Twig\\Node\\Expression\\Binary\\ModBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/ModBinary.php', + 'Twig\\Node\\Expression\\Binary\\MulBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/MulBinary.php', + 'Twig\\Node\\Expression\\Binary\\NotEqualBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/NotEqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\NotInBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/NotInBinary.php', + 'Twig\\Node\\Expression\\Binary\\OrBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/OrBinary.php', + 'Twig\\Node\\Expression\\Binary\\PowerBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/PowerBinary.php', + 'Twig\\Node\\Expression\\Binary\\RangeBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/RangeBinary.php', + 'Twig\\Node\\Expression\\Binary\\StartsWithBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/StartsWithBinary.php', + 'Twig\\Node\\Expression\\Binary\\SubBinary' => $vendorDir . '/twig/twig/src/Node/Expression/Binary/SubBinary.php', + 'Twig\\Node\\Expression\\BlockReferenceExpression' => $vendorDir . '/twig/twig/src/Node/Expression/BlockReferenceExpression.php', + 'Twig\\Node\\Expression\\CallExpression' => $vendorDir . '/twig/twig/src/Node/Expression/CallExpression.php', + 'Twig\\Node\\Expression\\ConditionalExpression' => $vendorDir . '/twig/twig/src/Node/Expression/ConditionalExpression.php', + 'Twig\\Node\\Expression\\ConstantExpression' => $vendorDir . '/twig/twig/src/Node/Expression/ConstantExpression.php', + 'Twig\\Node\\Expression\\FilterExpression' => $vendorDir . '/twig/twig/src/Node/Expression/FilterExpression.php', + 'Twig\\Node\\Expression\\Filter\\DefaultFilter' => $vendorDir . '/twig/twig/src/Node/Expression/Filter/DefaultFilter.php', + 'Twig\\Node\\Expression\\FunctionExpression' => $vendorDir . '/twig/twig/src/Node/Expression/FunctionExpression.php', + 'Twig\\Node\\Expression\\GetAttrExpression' => $vendorDir . '/twig/twig/src/Node/Expression/GetAttrExpression.php', + 'Twig\\Node\\Expression\\MethodCallExpression' => $vendorDir . '/twig/twig/src/Node/Expression/MethodCallExpression.php', + 'Twig\\Node\\Expression\\NameExpression' => $vendorDir . '/twig/twig/src/Node/Expression/NameExpression.php', + 'Twig\\Node\\Expression\\NullCoalesceExpression' => $vendorDir . '/twig/twig/src/Node/Expression/NullCoalesceExpression.php', + 'Twig\\Node\\Expression\\ParentExpression' => $vendorDir . '/twig/twig/src/Node/Expression/ParentExpression.php', + 'Twig\\Node\\Expression\\TempNameExpression' => $vendorDir . '/twig/twig/src/Node/Expression/TempNameExpression.php', + 'Twig\\Node\\Expression\\TestExpression' => $vendorDir . '/twig/twig/src/Node/Expression/TestExpression.php', + 'Twig\\Node\\Expression\\Test\\ConstantTest' => $vendorDir . '/twig/twig/src/Node/Expression/Test/ConstantTest.php', + 'Twig\\Node\\Expression\\Test\\DefinedTest' => $vendorDir . '/twig/twig/src/Node/Expression/Test/DefinedTest.php', + 'Twig\\Node\\Expression\\Test\\DivisiblebyTest' => $vendorDir . '/twig/twig/src/Node/Expression/Test/DivisiblebyTest.php', + 'Twig\\Node\\Expression\\Test\\EvenTest' => $vendorDir . '/twig/twig/src/Node/Expression/Test/EvenTest.php', + 'Twig\\Node\\Expression\\Test\\NullTest' => $vendorDir . '/twig/twig/src/Node/Expression/Test/NullTest.php', + 'Twig\\Node\\Expression\\Test\\OddTest' => $vendorDir . '/twig/twig/src/Node/Expression/Test/OddTest.php', + 'Twig\\Node\\Expression\\Test\\SameasTest' => $vendorDir . '/twig/twig/src/Node/Expression/Test/SameasTest.php', + 'Twig\\Node\\Expression\\Unary\\AbstractUnary' => $vendorDir . '/twig/twig/src/Node/Expression/Unary/AbstractUnary.php', + 'Twig\\Node\\Expression\\Unary\\NegUnary' => $vendorDir . '/twig/twig/src/Node/Expression/Unary/NegUnary.php', + 'Twig\\Node\\Expression\\Unary\\NotUnary' => $vendorDir . '/twig/twig/src/Node/Expression/Unary/NotUnary.php', + 'Twig\\Node\\Expression\\Unary\\PosUnary' => $vendorDir . '/twig/twig/src/Node/Expression/Unary/PosUnary.php', + 'Twig\\Node\\FlushNode' => $vendorDir . '/twig/twig/src/Node/FlushNode.php', + 'Twig\\Node\\ForLoopNode' => $vendorDir . '/twig/twig/src/Node/ForLoopNode.php', + 'Twig\\Node\\ForNode' => $vendorDir . '/twig/twig/src/Node/ForNode.php', + 'Twig\\Node\\IfNode' => $vendorDir . '/twig/twig/src/Node/IfNode.php', + 'Twig\\Node\\ImportNode' => $vendorDir . '/twig/twig/src/Node/ImportNode.php', + 'Twig\\Node\\IncludeNode' => $vendorDir . '/twig/twig/src/Node/IncludeNode.php', + 'Twig\\Node\\MacroNode' => $vendorDir . '/twig/twig/src/Node/MacroNode.php', + 'Twig\\Node\\ModuleNode' => $vendorDir . '/twig/twig/src/Node/ModuleNode.php', + 'Twig\\Node\\Node' => $vendorDir . '/twig/twig/src/Node/Node.php', + 'Twig\\Node\\NodeCaptureInterface' => $vendorDir . '/twig/twig/src/Node/NodeCaptureInterface.php', + 'Twig\\Node\\NodeOutputInterface' => $vendorDir . '/twig/twig/src/Node/NodeOutputInterface.php', + 'Twig\\Node\\PrintNode' => $vendorDir . '/twig/twig/src/Node/PrintNode.php', + 'Twig\\Node\\SandboxNode' => $vendorDir . '/twig/twig/src/Node/SandboxNode.php', + 'Twig\\Node\\SandboxedPrintNode' => $vendorDir . '/twig/twig/src/Node/SandboxedPrintNode.php', + 'Twig\\Node\\SetNode' => $vendorDir . '/twig/twig/src/Node/SetNode.php', + 'Twig\\Node\\SetTempNode' => $vendorDir . '/twig/twig/src/Node/SetTempNode.php', + 'Twig\\Node\\SpacelessNode' => $vendorDir . '/twig/twig/src/Node/SpacelessNode.php', + 'Twig\\Node\\TextNode' => $vendorDir . '/twig/twig/src/Node/TextNode.php', + 'Twig\\Node\\WithNode' => $vendorDir . '/twig/twig/src/Node/WithNode.php', + 'Twig\\Parser' => $vendorDir . '/twig/twig/src/Parser.php', + 'Twig\\Profiler\\Dumper\\BaseDumper' => $vendorDir . '/twig/twig/src/Profiler/Dumper/BaseDumper.php', + 'Twig\\Profiler\\Dumper\\BlackfireDumper' => $vendorDir . '/twig/twig/src/Profiler/Dumper/BlackfireDumper.php', + 'Twig\\Profiler\\Dumper\\HtmlDumper' => $vendorDir . '/twig/twig/src/Profiler/Dumper/HtmlDumper.php', + 'Twig\\Profiler\\Dumper\\TextDumper' => $vendorDir . '/twig/twig/src/Profiler/Dumper/TextDumper.php', + 'Twig\\Profiler\\NodeVisitor\\ProfilerNodeVisitor' => $vendorDir . '/twig/twig/src/Profiler/NodeVisitor/ProfilerNodeVisitor.php', + 'Twig\\Profiler\\Node\\EnterProfileNode' => $vendorDir . '/twig/twig/src/Profiler/Node/EnterProfileNode.php', + 'Twig\\Profiler\\Node\\LeaveProfileNode' => $vendorDir . '/twig/twig/src/Profiler/Node/LeaveProfileNode.php', + 'Twig\\Profiler\\Profile' => $vendorDir . '/twig/twig/src/Profiler/Profile.php', + 'Twig\\RuntimeLoader\\ContainerRuntimeLoader' => $vendorDir . '/twig/twig/src/RuntimeLoader/ContainerRuntimeLoader.php', + 'Twig\\RuntimeLoader\\FactoryRuntimeLoader' => $vendorDir . '/twig/twig/src/RuntimeLoader/FactoryRuntimeLoader.php', + 'Twig\\RuntimeLoader\\RuntimeLoaderInterface' => $vendorDir . '/twig/twig/src/RuntimeLoader/RuntimeLoaderInterface.php', + 'Twig\\Sandbox\\SecurityError' => $vendorDir . '/twig/twig/src/Sandbox/SecurityError.php', + 'Twig\\Sandbox\\SecurityNotAllowedFilterError' => $vendorDir . '/twig/twig/src/Sandbox/SecurityNotAllowedFilterError.php', + 'Twig\\Sandbox\\SecurityNotAllowedFunctionError' => $vendorDir . '/twig/twig/src/Sandbox/SecurityNotAllowedFunctionError.php', + 'Twig\\Sandbox\\SecurityNotAllowedMethodError' => $vendorDir . '/twig/twig/src/Sandbox/SecurityNotAllowedMethodError.php', + 'Twig\\Sandbox\\SecurityNotAllowedPropertyError' => $vendorDir . '/twig/twig/src/Sandbox/SecurityNotAllowedPropertyError.php', + 'Twig\\Sandbox\\SecurityNotAllowedTagError' => $vendorDir . '/twig/twig/src/Sandbox/SecurityNotAllowedTagError.php', + 'Twig\\Sandbox\\SecurityPolicy' => $vendorDir . '/twig/twig/src/Sandbox/SecurityPolicy.php', + 'Twig\\Sandbox\\SecurityPolicyInterface' => $vendorDir . '/twig/twig/src/Sandbox/SecurityPolicyInterface.php', + 'Twig\\Source' => $vendorDir . '/twig/twig/src/Source.php', + 'Twig\\Template' => $vendorDir . '/twig/twig/src/Template.php', + 'Twig\\TemplateWrapper' => $vendorDir . '/twig/twig/src/TemplateWrapper.php', + 'Twig\\Test\\IntegrationTestCase' => $vendorDir . '/twig/twig/src/Test/IntegrationTestCase.php', + 'Twig\\Test\\NodeTestCase' => $vendorDir . '/twig/twig/src/Test/NodeTestCase.php', + 'Twig\\Token' => $vendorDir . '/twig/twig/src/Token.php', + 'Twig\\TokenParser\\AbstractTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/AbstractTokenParser.php', + 'Twig\\TokenParser\\AutoEscapeTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/AutoEscapeTokenParser.php', + 'Twig\\TokenParser\\BlockTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/BlockTokenParser.php', + 'Twig\\TokenParser\\DeprecatedTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/DeprecatedTokenParser.php', + 'Twig\\TokenParser\\DoTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/DoTokenParser.php', + 'Twig\\TokenParser\\EmbedTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/EmbedTokenParser.php', + 'Twig\\TokenParser\\ExtendsTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/ExtendsTokenParser.php', + 'Twig\\TokenParser\\FilterTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/FilterTokenParser.php', + 'Twig\\TokenParser\\FlushTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/FlushTokenParser.php', + 'Twig\\TokenParser\\ForTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/ForTokenParser.php', + 'Twig\\TokenParser\\FromTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/FromTokenParser.php', + 'Twig\\TokenParser\\IfTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/IfTokenParser.php', + 'Twig\\TokenParser\\ImportTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/ImportTokenParser.php', + 'Twig\\TokenParser\\IncludeTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/IncludeTokenParser.php', + 'Twig\\TokenParser\\MacroTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/MacroTokenParser.php', + 'Twig\\TokenParser\\SandboxTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/SandboxTokenParser.php', + 'Twig\\TokenParser\\SetTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/SetTokenParser.php', + 'Twig\\TokenParser\\SpacelessTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/SpacelessTokenParser.php', + 'Twig\\TokenParser\\TokenParserInterface' => $vendorDir . '/twig/twig/src/TokenParser/TokenParserInterface.php', + 'Twig\\TokenParser\\UseTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/UseTokenParser.php', + 'Twig\\TokenParser\\WithTokenParser' => $vendorDir . '/twig/twig/src/TokenParser/WithTokenParser.php', + 'Twig\\TokenStream' => $vendorDir . '/twig/twig/src/TokenStream.php', + 'Twig\\TwigFilter' => $vendorDir . '/twig/twig/src/TwigFilter.php', + 'Twig\\TwigFunction' => $vendorDir . '/twig/twig/src/TwigFunction.php', + 'Twig\\TwigTest' => $vendorDir . '/twig/twig/src/TwigTest.php', + 'Twig\\Util\\DeprecationCollector' => $vendorDir . '/twig/twig/src/Util/DeprecationCollector.php', + 'Twig\\Util\\TemplateDirIterator' => $vendorDir . '/twig/twig/src/Util/TemplateDirIterator.php', + 'Twig_Autoloader' => $vendorDir . '/twig/twig/lib/Twig/Autoloader.php', + 'Twig_BaseNodeVisitor' => $vendorDir . '/twig/twig/lib/Twig/BaseNodeVisitor.php', + 'Twig_CacheInterface' => $vendorDir . '/twig/twig/lib/Twig/CacheInterface.php', + 'Twig_Cache_Filesystem' => $vendorDir . '/twig/twig/lib/Twig/Cache/Filesystem.php', + 'Twig_Cache_Null' => $vendorDir . '/twig/twig/lib/Twig/Cache/Null.php', + 'Twig_Compiler' => $vendorDir . '/twig/twig/lib/Twig/Compiler.php', + 'Twig_CompilerInterface' => $vendorDir . '/twig/twig/lib/Twig/CompilerInterface.php', + 'Twig_ContainerRuntimeLoader' => $vendorDir . '/twig/twig/lib/Twig/ContainerRuntimeLoader.php', + 'Twig_Environment' => $vendorDir . '/twig/twig/lib/Twig/Environment.php', + 'Twig_Error' => $vendorDir . '/twig/twig/lib/Twig/Error.php', + 'Twig_Error_Loader' => $vendorDir . '/twig/twig/lib/Twig/Error/Loader.php', + 'Twig_Error_Runtime' => $vendorDir . '/twig/twig/lib/Twig/Error/Runtime.php', + 'Twig_Error_Syntax' => $vendorDir . '/twig/twig/lib/Twig/Error/Syntax.php', + 'Twig_ExistsLoaderInterface' => $vendorDir . '/twig/twig/lib/Twig/ExistsLoaderInterface.php', + 'Twig_ExpressionParser' => $vendorDir . '/twig/twig/lib/Twig/ExpressionParser.php', + 'Twig_Extension' => $vendorDir . '/twig/twig/lib/Twig/Extension.php', + 'Twig_ExtensionInterface' => $vendorDir . '/twig/twig/lib/Twig/ExtensionInterface.php', + 'Twig_Extension_Core' => $vendorDir . '/twig/twig/lib/Twig/Extension/Core.php', + 'Twig_Extension_Debug' => $vendorDir . '/twig/twig/lib/Twig/Extension/Debug.php', + 'Twig_Extension_Escaper' => $vendorDir . '/twig/twig/lib/Twig/Extension/Escaper.php', + 'Twig_Extension_GlobalsInterface' => $vendorDir . '/twig/twig/lib/Twig/Extension/GlobalsInterface.php', + 'Twig_Extension_InitRuntimeInterface' => $vendorDir . '/twig/twig/lib/Twig/Extension/InitRuntimeInterface.php', + 'Twig_Extension_Optimizer' => $vendorDir . '/twig/twig/lib/Twig/Extension/Optimizer.php', + 'Twig_Extension_Profiler' => $vendorDir . '/twig/twig/lib/Twig/Extension/Profiler.php', + 'Twig_Extension_Sandbox' => $vendorDir . '/twig/twig/lib/Twig/Extension/Sandbox.php', + 'Twig_Extension_Staging' => $vendorDir . '/twig/twig/lib/Twig/Extension/Staging.php', + 'Twig_Extension_StringLoader' => $vendorDir . '/twig/twig/lib/Twig/Extension/StringLoader.php', + 'Twig_FactoryRuntimeLoader' => $vendorDir . '/twig/twig/lib/Twig/FactoryRuntimeLoader.php', + 'Twig_FileExtensionEscapingStrategy' => $vendorDir . '/twig/twig/lib/Twig/FileExtensionEscapingStrategy.php', + 'Twig_Filter' => $vendorDir . '/twig/twig/lib/Twig/Filter.php', + 'Twig_FilterCallableInterface' => $vendorDir . '/twig/twig/lib/Twig/FilterCallableInterface.php', + 'Twig_FilterInterface' => $vendorDir . '/twig/twig/lib/Twig/FilterInterface.php', + 'Twig_Filter_Function' => $vendorDir . '/twig/twig/lib/Twig/Filter/Function.php', + 'Twig_Filter_Method' => $vendorDir . '/twig/twig/lib/Twig/Filter/Method.php', + 'Twig_Filter_Node' => $vendorDir . '/twig/twig/lib/Twig/Filter/Node.php', + 'Twig_Function' => $vendorDir . '/twig/twig/lib/Twig/Function.php', + 'Twig_FunctionCallableInterface' => $vendorDir . '/twig/twig/lib/Twig/FunctionCallableInterface.php', + 'Twig_FunctionInterface' => $vendorDir . '/twig/twig/lib/Twig/FunctionInterface.php', + 'Twig_Function_Function' => $vendorDir . '/twig/twig/lib/Twig/Function/Function.php', + 'Twig_Function_Method' => $vendorDir . '/twig/twig/lib/Twig/Function/Method.php', + 'Twig_Function_Node' => $vendorDir . '/twig/twig/lib/Twig/Function/Node.php', + 'Twig_Lexer' => $vendorDir . '/twig/twig/lib/Twig/Lexer.php', + 'Twig_LexerInterface' => $vendorDir . '/twig/twig/lib/Twig/LexerInterface.php', + 'Twig_LoaderInterface' => $vendorDir . '/twig/twig/lib/Twig/LoaderInterface.php', + 'Twig_Loader_Array' => $vendorDir . '/twig/twig/lib/Twig/Loader/Array.php', + 'Twig_Loader_Chain' => $vendorDir . '/twig/twig/lib/Twig/Loader/Chain.php', + 'Twig_Loader_Filesystem' => $vendorDir . '/twig/twig/lib/Twig/Loader/Filesystem.php', + 'Twig_Loader_String' => $vendorDir . '/twig/twig/lib/Twig/Loader/String.php', + 'Twig_Markup' => $vendorDir . '/twig/twig/lib/Twig/Markup.php', + 'Twig_Node' => $vendorDir . '/twig/twig/lib/Twig/Node.php', + 'Twig_NodeCaptureInterface' => $vendorDir . '/twig/twig/lib/Twig/NodeCaptureInterface.php', + 'Twig_NodeInterface' => $vendorDir . '/twig/twig/lib/Twig/NodeInterface.php', + 'Twig_NodeOutputInterface' => $vendorDir . '/twig/twig/lib/Twig/NodeOutputInterface.php', + 'Twig_NodeTraverser' => $vendorDir . '/twig/twig/lib/Twig/NodeTraverser.php', + 'Twig_NodeVisitorInterface' => $vendorDir . '/twig/twig/lib/Twig/NodeVisitorInterface.php', + 'Twig_NodeVisitor_Escaper' => $vendorDir . '/twig/twig/lib/Twig/NodeVisitor/Escaper.php', + 'Twig_NodeVisitor_Optimizer' => $vendorDir . '/twig/twig/lib/Twig/NodeVisitor/Optimizer.php', + 'Twig_NodeVisitor_SafeAnalysis' => $vendorDir . '/twig/twig/lib/Twig/NodeVisitor/SafeAnalysis.php', + 'Twig_NodeVisitor_Sandbox' => $vendorDir . '/twig/twig/lib/Twig/NodeVisitor/Sandbox.php', + 'Twig_Node_AutoEscape' => $vendorDir . '/twig/twig/lib/Twig/Node/AutoEscape.php', + 'Twig_Node_Block' => $vendorDir . '/twig/twig/lib/Twig/Node/Block.php', + 'Twig_Node_BlockReference' => $vendorDir . '/twig/twig/lib/Twig/Node/BlockReference.php', + 'Twig_Node_Body' => $vendorDir . '/twig/twig/lib/Twig/Node/Body.php', + 'Twig_Node_CheckSecurity' => $vendorDir . '/twig/twig/lib/Twig/Node/CheckSecurity.php', + 'Twig_Node_Deprecated' => $vendorDir . '/twig/twig/lib/Twig/Node/Deprecated.php', + 'Twig_Node_Do' => $vendorDir . '/twig/twig/lib/Twig/Node/Do.php', + 'Twig_Node_Embed' => $vendorDir . '/twig/twig/lib/Twig/Node/Embed.php', + 'Twig_Node_Expression' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression.php', + 'Twig_Node_Expression_Array' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Array.php', + 'Twig_Node_Expression_AssignName' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/AssignName.php', + 'Twig_Node_Expression_Binary' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary.php', + 'Twig_Node_Expression_Binary_Add' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Add.php', + 'Twig_Node_Expression_Binary_And' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/And.php', + 'Twig_Node_Expression_Binary_BitwiseAnd' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseAnd.php', + 'Twig_Node_Expression_Binary_BitwiseOr' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseOr.php', + 'Twig_Node_Expression_Binary_BitwiseXor' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseXor.php', + 'Twig_Node_Expression_Binary_Concat' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Concat.php', + 'Twig_Node_Expression_Binary_Div' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Div.php', + 'Twig_Node_Expression_Binary_EndsWith' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/EndsWith.php', + 'Twig_Node_Expression_Binary_Equal' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Equal.php', + 'Twig_Node_Expression_Binary_FloorDiv' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/FloorDiv.php', + 'Twig_Node_Expression_Binary_Greater' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Greater.php', + 'Twig_Node_Expression_Binary_GreaterEqual' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/GreaterEqual.php', + 'Twig_Node_Expression_Binary_In' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/In.php', + 'Twig_Node_Expression_Binary_Less' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Less.php', + 'Twig_Node_Expression_Binary_LessEqual' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/LessEqual.php', + 'Twig_Node_Expression_Binary_Matches' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Matches.php', + 'Twig_Node_Expression_Binary_Mod' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Mod.php', + 'Twig_Node_Expression_Binary_Mul' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Mul.php', + 'Twig_Node_Expression_Binary_NotEqual' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/NotEqual.php', + 'Twig_Node_Expression_Binary_NotIn' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/NotIn.php', + 'Twig_Node_Expression_Binary_Or' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Or.php', + 'Twig_Node_Expression_Binary_Power' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Power.php', + 'Twig_Node_Expression_Binary_Range' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Range.php', + 'Twig_Node_Expression_Binary_StartsWith' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/StartsWith.php', + 'Twig_Node_Expression_Binary_Sub' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Binary/Sub.php', + 'Twig_Node_Expression_BlockReference' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/BlockReference.php', + 'Twig_Node_Expression_Call' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Call.php', + 'Twig_Node_Expression_Conditional' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Conditional.php', + 'Twig_Node_Expression_Constant' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Constant.php', + 'Twig_Node_Expression_ExtensionReference' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/ExtensionReference.php', + 'Twig_Node_Expression_Filter' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Filter.php', + 'Twig_Node_Expression_Filter_Default' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Filter/Default.php', + 'Twig_Node_Expression_Function' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Function.php', + 'Twig_Node_Expression_GetAttr' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/GetAttr.php', + 'Twig_Node_Expression_MethodCall' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/MethodCall.php', + 'Twig_Node_Expression_Name' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Name.php', + 'Twig_Node_Expression_NullCoalesce' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/NullCoalesce.php', + 'Twig_Node_Expression_Parent' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Parent.php', + 'Twig_Node_Expression_TempName' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/TempName.php', + 'Twig_Node_Expression_Test' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test.php', + 'Twig_Node_Expression_Test_Constant' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test/Constant.php', + 'Twig_Node_Expression_Test_Defined' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test/Defined.php', + 'Twig_Node_Expression_Test_Divisibleby' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test/Divisibleby.php', + 'Twig_Node_Expression_Test_Even' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test/Even.php', + 'Twig_Node_Expression_Test_Null' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test/Null.php', + 'Twig_Node_Expression_Test_Odd' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test/Odd.php', + 'Twig_Node_Expression_Test_Sameas' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Test/Sameas.php', + 'Twig_Node_Expression_Unary' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Unary.php', + 'Twig_Node_Expression_Unary_Neg' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Unary/Neg.php', + 'Twig_Node_Expression_Unary_Not' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Unary/Not.php', + 'Twig_Node_Expression_Unary_Pos' => $vendorDir . '/twig/twig/lib/Twig/Node/Expression/Unary/Pos.php', + 'Twig_Node_Flush' => $vendorDir . '/twig/twig/lib/Twig/Node/Flush.php', + 'Twig_Node_For' => $vendorDir . '/twig/twig/lib/Twig/Node/For.php', + 'Twig_Node_ForLoop' => $vendorDir . '/twig/twig/lib/Twig/Node/ForLoop.php', + 'Twig_Node_If' => $vendorDir . '/twig/twig/lib/Twig/Node/If.php', + 'Twig_Node_Import' => $vendorDir . '/twig/twig/lib/Twig/Node/Import.php', + 'Twig_Node_Include' => $vendorDir . '/twig/twig/lib/Twig/Node/Include.php', + 'Twig_Node_Macro' => $vendorDir . '/twig/twig/lib/Twig/Node/Macro.php', + 'Twig_Node_Module' => $vendorDir . '/twig/twig/lib/Twig/Node/Module.php', + 'Twig_Node_Print' => $vendorDir . '/twig/twig/lib/Twig/Node/Print.php', + 'Twig_Node_Sandbox' => $vendorDir . '/twig/twig/lib/Twig/Node/Sandbox.php', + 'Twig_Node_SandboxedPrint' => $vendorDir . '/twig/twig/lib/Twig/Node/SandboxedPrint.php', + 'Twig_Node_Set' => $vendorDir . '/twig/twig/lib/Twig/Node/Set.php', + 'Twig_Node_SetTemp' => $vendorDir . '/twig/twig/lib/Twig/Node/SetTemp.php', + 'Twig_Node_Spaceless' => $vendorDir . '/twig/twig/lib/Twig/Node/Spaceless.php', + 'Twig_Node_Text' => $vendorDir . '/twig/twig/lib/Twig/Node/Text.php', + 'Twig_Node_With' => $vendorDir . '/twig/twig/lib/Twig/Node/With.php', + 'Twig_Parser' => $vendorDir . '/twig/twig/lib/Twig/Parser.php', + 'Twig_ParserInterface' => $vendorDir . '/twig/twig/lib/Twig/ParserInterface.php', + 'Twig_Profiler_Dumper_Base' => $vendorDir . '/twig/twig/lib/Twig/Profiler/Dumper/Base.php', + 'Twig_Profiler_Dumper_Blackfire' => $vendorDir . '/twig/twig/lib/Twig/Profiler/Dumper/Blackfire.php', + 'Twig_Profiler_Dumper_Html' => $vendorDir . '/twig/twig/lib/Twig/Profiler/Dumper/Html.php', + 'Twig_Profiler_Dumper_Text' => $vendorDir . '/twig/twig/lib/Twig/Profiler/Dumper/Text.php', + 'Twig_Profiler_NodeVisitor_Profiler' => $vendorDir . '/twig/twig/lib/Twig/Profiler/NodeVisitor/Profiler.php', + 'Twig_Profiler_Node_EnterProfile' => $vendorDir . '/twig/twig/lib/Twig/Profiler/Node/EnterProfile.php', + 'Twig_Profiler_Node_LeaveProfile' => $vendorDir . '/twig/twig/lib/Twig/Profiler/Node/LeaveProfile.php', + 'Twig_Profiler_Profile' => $vendorDir . '/twig/twig/lib/Twig/Profiler/Profile.php', + 'Twig_RuntimeLoaderInterface' => $vendorDir . '/twig/twig/lib/Twig/RuntimeLoaderInterface.php', + 'Twig_Sandbox_SecurityError' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityError.php', + 'Twig_Sandbox_SecurityNotAllowedFilterError' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFilterError.php', + 'Twig_Sandbox_SecurityNotAllowedFunctionError' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFunctionError.php', + 'Twig_Sandbox_SecurityNotAllowedMethodError' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedMethodError.php', + 'Twig_Sandbox_SecurityNotAllowedPropertyError' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedPropertyError.php', + 'Twig_Sandbox_SecurityNotAllowedTagError' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedTagError.php', + 'Twig_Sandbox_SecurityPolicy' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityPolicy.php', + 'Twig_Sandbox_SecurityPolicyInterface' => $vendorDir . '/twig/twig/lib/Twig/Sandbox/SecurityPolicyInterface.php', + 'Twig_SimpleFilter' => $vendorDir . '/twig/twig/lib/Twig/SimpleFilter.php', + 'Twig_SimpleFunction' => $vendorDir . '/twig/twig/lib/Twig/SimpleFunction.php', + 'Twig_SimpleTest' => $vendorDir . '/twig/twig/lib/Twig/SimpleTest.php', + 'Twig_Source' => $vendorDir . '/twig/twig/lib/Twig/Source.php', + 'Twig_SourceContextLoaderInterface' => $vendorDir . '/twig/twig/lib/Twig/SourceContextLoaderInterface.php', + 'Twig_Template' => $vendorDir . '/twig/twig/lib/Twig/Template.php', + 'Twig_TemplateInterface' => $vendorDir . '/twig/twig/lib/Twig/TemplateInterface.php', + 'Twig_TemplateWrapper' => $vendorDir . '/twig/twig/lib/Twig/TemplateWrapper.php', + 'Twig_Test' => $vendorDir . '/twig/twig/lib/Twig/Test.php', + 'Twig_TestCallableInterface' => $vendorDir . '/twig/twig/lib/Twig/TestCallableInterface.php', + 'Twig_TestInterface' => $vendorDir . '/twig/twig/lib/Twig/TestInterface.php', + 'Twig_Test_Function' => $vendorDir . '/twig/twig/lib/Twig/Test/Function.php', + 'Twig_Test_IntegrationTestCase' => $vendorDir . '/twig/twig/lib/Twig/Test/IntegrationTestCase.php', + 'Twig_Test_Method' => $vendorDir . '/twig/twig/lib/Twig/Test/Method.php', + 'Twig_Test_Node' => $vendorDir . '/twig/twig/lib/Twig/Test/Node.php', + 'Twig_Test_NodeTestCase' => $vendorDir . '/twig/twig/lib/Twig/Test/NodeTestCase.php', + 'Twig_Token' => $vendorDir . '/twig/twig/lib/Twig/Token.php', + 'Twig_TokenParser' => $vendorDir . '/twig/twig/lib/Twig/TokenParser.php', + 'Twig_TokenParserBroker' => $vendorDir . '/twig/twig/lib/Twig/TokenParserBroker.php', + 'Twig_TokenParserBrokerInterface' => $vendorDir . '/twig/twig/lib/Twig/TokenParserBrokerInterface.php', + 'Twig_TokenParserInterface' => $vendorDir . '/twig/twig/lib/Twig/TokenParserInterface.php', + 'Twig_TokenParser_AutoEscape' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/AutoEscape.php', + 'Twig_TokenParser_Block' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Block.php', + 'Twig_TokenParser_Deprecated' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Deprecated.php', + 'Twig_TokenParser_Do' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Do.php', + 'Twig_TokenParser_Embed' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Embed.php', + 'Twig_TokenParser_Extends' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Extends.php', + 'Twig_TokenParser_Filter' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Filter.php', + 'Twig_TokenParser_Flush' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Flush.php', + 'Twig_TokenParser_For' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/For.php', + 'Twig_TokenParser_From' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/From.php', + 'Twig_TokenParser_If' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/If.php', + 'Twig_TokenParser_Import' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Import.php', + 'Twig_TokenParser_Include' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Include.php', + 'Twig_TokenParser_Macro' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Macro.php', + 'Twig_TokenParser_Sandbox' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Sandbox.php', + 'Twig_TokenParser_Set' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Set.php', + 'Twig_TokenParser_Spaceless' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Spaceless.php', + 'Twig_TokenParser_Use' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/Use.php', + 'Twig_TokenParser_With' => $vendorDir . '/twig/twig/lib/Twig/TokenParser/With.php', + 'Twig_TokenStream' => $vendorDir . '/twig/twig/lib/Twig/TokenStream.php', + 'Twig_Util_DeprecationCollector' => $vendorDir . '/twig/twig/lib/Twig/Util/DeprecationCollector.php', + 'Twig_Util_TemplateDirIterator' => $vendorDir . '/twig/twig/lib/Twig/Util/TemplateDirIterator.php', +); diff --git a/vendor/composer/autoload_files.php b/vendor/composer/autoload_files.php new file mode 100644 index 0000000..9cfb30a --- /dev/null +++ b/vendor/composer/autoload_files.php @@ -0,0 +1,10 @@ + $vendorDir . '/symfony/polyfill-ctype/bootstrap.php', +); diff --git a/vendor/composer/autoload_namespaces.php b/vendor/composer/autoload_namespaces.php new file mode 100644 index 0000000..f632572 --- /dev/null +++ b/vendor/composer/autoload_namespaces.php @@ -0,0 +1,15 @@ + array($vendorDir . '/twig/twig/lib'), + 'PicoPluginInterface' => array($vendorDir . '/picocms/pico/lib'), + 'Pico' => array($vendorDir . '/picocms/pico/lib'), + 'ParsedownExtra' => array($vendorDir . '/erusev/parsedown-extra'), + 'Parsedown' => array($vendorDir . '/erusev/parsedown'), + 'AbstractPicoPlugin' => array($vendorDir . '/picocms/pico/lib'), +); diff --git a/vendor/composer/autoload_psr4.php b/vendor/composer/autoload_psr4.php new file mode 100644 index 0000000..33eb95a --- /dev/null +++ b/vendor/composer/autoload_psr4.php @@ -0,0 +1,13 @@ + array($vendorDir . '/twig/twig/src'), + 'Symfony\\Polyfill\\Ctype\\' => array($vendorDir . '/symfony/polyfill-ctype'), + 'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'), + 'Pico\\Composer\\' => array($vendorDir . '/picocms/composer-installer/src'), +); diff --git a/vendor/composer/autoload_real.php b/vendor/composer/autoload_real.php new file mode 100644 index 0000000..c90d009 --- /dev/null +++ b/vendor/composer/autoload_real.php @@ -0,0 +1,73 @@ += 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded()); + if ($useStaticLoader) { + require_once __DIR__ . '/autoload_static.php'; + + call_user_func(\Composer\Autoload\ComposerStaticInit37bcf3c1669669b4e374fd17d45b1c62::getInitializer($loader)); + } else { + $map = require __DIR__ . '/autoload_namespaces.php'; + foreach ($map as $namespace => $path) { + $loader->set($namespace, $path); + } + + $map = require __DIR__ . '/autoload_psr4.php'; + foreach ($map as $namespace => $path) { + $loader->setPsr4($namespace, $path); + } + + $classMap = require __DIR__ . '/autoload_classmap.php'; + if ($classMap) { + $loader->addClassMap($classMap); + } + } + + $loader->register(true); + + if ($useStaticLoader) { + $includeFiles = Composer\Autoload\ComposerStaticInit37bcf3c1669669b4e374fd17d45b1c62::$files; + } else { + $includeFiles = require __DIR__ . '/autoload_files.php'; + } + foreach ($includeFiles as $fileIdentifier => $file) { + composerRequire37bcf3c1669669b4e374fd17d45b1c62($fileIdentifier, $file); + } + + return $loader; + } +} + +function composerRequire37bcf3c1669669b4e374fd17d45b1c62($fileIdentifier, $file) +{ + if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) { + require $file; + + $GLOBALS['__composer_autoload_files'][$fileIdentifier] = true; + } +} diff --git a/vendor/composer/autoload_static.php b/vendor/composer/autoload_static.php new file mode 100644 index 0000000..92bdca7 --- /dev/null +++ b/vendor/composer/autoload_static.php @@ -0,0 +1,500 @@ + __DIR__ . '/..' . '/symfony/polyfill-ctype/bootstrap.php', + ); + + public static $prefixLengthsPsr4 = array ( + 'T' => + array ( + 'Twig\\' => 5, + ), + 'S' => + array ( + 'Symfony\\Polyfill\\Ctype\\' => 23, + 'Symfony\\Component\\Yaml\\' => 23, + ), + 'P' => + array ( + 'Pico\\Composer\\' => 14, + ), + ); + + public static $prefixDirsPsr4 = array ( + 'Twig\\' => + array ( + 0 => __DIR__ . '/..' . '/twig/twig/src', + ), + 'Symfony\\Polyfill\\Ctype\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/polyfill-ctype', + ), + 'Symfony\\Component\\Yaml\\' => + array ( + 0 => __DIR__ . '/..' . '/symfony/yaml', + ), + 'Pico\\Composer\\' => + array ( + 0 => __DIR__ . '/..' . '/picocms/composer-installer/src', + ), + ); + + public static $prefixesPsr0 = array ( + 'T' => + array ( + 'Twig_' => + array ( + 0 => __DIR__ . '/..' . '/twig/twig/lib', + ), + ), + 'P' => + array ( + 'PicoPluginInterface' => + array ( + 0 => __DIR__ . '/..' . '/picocms/pico/lib', + ), + 'Pico' => + array ( + 0 => __DIR__ . '/..' . '/picocms/pico/lib', + ), + 'ParsedownExtra' => + array ( + 0 => __DIR__ . '/..' . '/erusev/parsedown-extra', + ), + 'Parsedown' => + array ( + 0 => __DIR__ . '/..' . '/erusev/parsedown', + ), + ), + 'A' => + array ( + 'AbstractPicoPlugin' => + array ( + 0 => __DIR__ . '/..' . '/picocms/pico/lib', + ), + ), + ); + + public static $classMap = array ( + 'AbstractPicoCompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/lib/AbstractPicoCompatPlugin.php', + 'AbstractPicoPlugin' => __DIR__ . '/..' . '/picocms/pico/lib/AbstractPicoPlugin.php', + 'AbstractPicoPluginApiCompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/lib/AbstractPicoPluginApiCompatPlugin.php', + 'Parsedown' => __DIR__ . '/..' . '/erusev/parsedown/Parsedown.php', + 'ParsedownExtra' => __DIR__ . '/..' . '/erusev/parsedown-extra/ParsedownExtra.php', + 'Pico' => __DIR__ . '/..' . '/picocms/pico/lib/Pico.php', + 'PicoCompatPluginInterface' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/lib/PicoCompatPluginInterface.php', + 'PicoDeprecated' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/PicoDeprecated.php', + 'PicoMainCompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/plugins/PicoMainCompatPlugin.php', + 'PicoPluginApi0CompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/plugins/PicoPluginApi0CompatPlugin.php', + 'PicoPluginApi1CompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/plugins/PicoPluginApi1CompatPlugin.php', + 'PicoPluginApi2CompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/plugins/PicoPluginApi2CompatPlugin.php', + 'PicoPluginApiCompatPluginInterface' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/lib/PicoPluginApiCompatPluginInterface.php', + 'PicoPluginInterface' => __DIR__ . '/..' . '/picocms/pico/lib/PicoPluginInterface.php', + 'PicoThemeApi0CompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/plugins/PicoThemeApi0CompatPlugin.php', + 'PicoThemeApi1CompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/plugins/PicoThemeApi1CompatPlugin.php', + 'PicoThemeApi2CompatPlugin' => __DIR__ . '/../..' . '/plugins/PicoDeprecated/plugins/PicoThemeApi2CompatPlugin.php', + 'PicoTwigExtension' => __DIR__ . '/..' . '/picocms/pico/lib/PicoTwigExtension.php', + 'Pico\\Composer\\Installer\\PluginInstaller' => __DIR__ . '/..' . '/picocms/composer-installer/src/Installer/PluginInstaller.php', + 'Symfony\\Component\\Yaml\\Dumper' => __DIR__ . '/..' . '/symfony/yaml/Dumper.php', + 'Symfony\\Component\\Yaml\\Escaper' => __DIR__ . '/..' . '/symfony/yaml/Escaper.php', + 'Symfony\\Component\\Yaml\\Exception\\DumpException' => __DIR__ . '/..' . '/symfony/yaml/Exception/DumpException.php', + 'Symfony\\Component\\Yaml\\Exception\\ExceptionInterface' => __DIR__ . '/..' . '/symfony/yaml/Exception/ExceptionInterface.php', + 'Symfony\\Component\\Yaml\\Exception\\ParseException' => __DIR__ . '/..' . '/symfony/yaml/Exception/ParseException.php', + 'Symfony\\Component\\Yaml\\Exception\\RuntimeException' => __DIR__ . '/..' . '/symfony/yaml/Exception/RuntimeException.php', + 'Symfony\\Component\\Yaml\\Inline' => __DIR__ . '/..' . '/symfony/yaml/Inline.php', + 'Symfony\\Component\\Yaml\\Parser' => __DIR__ . '/..' . '/symfony/yaml/Parser.php', + 'Symfony\\Component\\Yaml\\Unescaper' => __DIR__ . '/..' . '/symfony/yaml/Unescaper.php', + 'Symfony\\Component\\Yaml\\Yaml' => __DIR__ . '/..' . '/symfony/yaml/Yaml.php', + 'Symfony\\Polyfill\\Ctype\\Ctype' => __DIR__ . '/..' . '/symfony/polyfill-ctype/Ctype.php', + 'Twig\\Cache\\CacheInterface' => __DIR__ . '/..' . '/twig/twig/src/Cache/CacheInterface.php', + 'Twig\\Cache\\FilesystemCache' => __DIR__ . '/..' . '/twig/twig/src/Cache/FilesystemCache.php', + 'Twig\\Cache\\NullCache' => __DIR__ . '/..' . '/twig/twig/src/Cache/NullCache.php', + 'Twig\\Compiler' => __DIR__ . '/..' . '/twig/twig/src/Compiler.php', + 'Twig\\Environment' => __DIR__ . '/..' . '/twig/twig/src/Environment.php', + 'Twig\\Error\\Error' => __DIR__ . '/..' . '/twig/twig/src/Error/Error.php', + 'Twig\\Error\\LoaderError' => __DIR__ . '/..' . '/twig/twig/src/Error/LoaderError.php', + 'Twig\\Error\\RuntimeError' => __DIR__ . '/..' . '/twig/twig/src/Error/RuntimeError.php', + 'Twig\\Error\\SyntaxError' => __DIR__ . '/..' . '/twig/twig/src/Error/SyntaxError.php', + 'Twig\\ExpressionParser' => __DIR__ . '/..' . '/twig/twig/src/ExpressionParser.php', + 'Twig\\Extension\\AbstractExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/AbstractExtension.php', + 'Twig\\Extension\\CoreExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/CoreExtension.php', + 'Twig\\Extension\\DebugExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/DebugExtension.php', + 'Twig\\Extension\\EscaperExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/EscaperExtension.php', + 'Twig\\Extension\\ExtensionInterface' => __DIR__ . '/..' . '/twig/twig/src/Extension/ExtensionInterface.php', + 'Twig\\Extension\\GlobalsInterface' => __DIR__ . '/..' . '/twig/twig/src/Extension/GlobalsInterface.php', + 'Twig\\Extension\\InitRuntimeInterface' => __DIR__ . '/..' . '/twig/twig/src/Extension/InitRuntimeInterface.php', + 'Twig\\Extension\\OptimizerExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/OptimizerExtension.php', + 'Twig\\Extension\\ProfilerExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/ProfilerExtension.php', + 'Twig\\Extension\\RuntimeExtensionInterface' => __DIR__ . '/..' . '/twig/twig/src/Extension/RuntimeExtensionInterface.php', + 'Twig\\Extension\\SandboxExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/SandboxExtension.php', + 'Twig\\Extension\\StagingExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/StagingExtension.php', + 'Twig\\Extension\\StringLoaderExtension' => __DIR__ . '/..' . '/twig/twig/src/Extension/StringLoaderExtension.php', + 'Twig\\FileExtensionEscapingStrategy' => __DIR__ . '/..' . '/twig/twig/src/FileExtensionEscapingStrategy.php', + 'Twig\\Lexer' => __DIR__ . '/..' . '/twig/twig/src/Lexer.php', + 'Twig\\Loader\\ArrayLoader' => __DIR__ . '/..' . '/twig/twig/src/Loader/ArrayLoader.php', + 'Twig\\Loader\\ChainLoader' => __DIR__ . '/..' . '/twig/twig/src/Loader/ChainLoader.php', + 'Twig\\Loader\\ExistsLoaderInterface' => __DIR__ . '/..' . '/twig/twig/src/Loader/ExistsLoaderInterface.php', + 'Twig\\Loader\\FilesystemLoader' => __DIR__ . '/..' . '/twig/twig/src/Loader/FilesystemLoader.php', + 'Twig\\Loader\\LoaderInterface' => __DIR__ . '/..' . '/twig/twig/src/Loader/LoaderInterface.php', + 'Twig\\Loader\\SourceContextLoaderInterface' => __DIR__ . '/..' . '/twig/twig/src/Loader/SourceContextLoaderInterface.php', + 'Twig\\Markup' => __DIR__ . '/..' . '/twig/twig/src/Markup.php', + 'Twig\\NodeTraverser' => __DIR__ . '/..' . '/twig/twig/src/NodeTraverser.php', + 'Twig\\NodeVisitor\\AbstractNodeVisitor' => __DIR__ . '/..' . '/twig/twig/src/NodeVisitor/AbstractNodeVisitor.php', + 'Twig\\NodeVisitor\\EscaperNodeVisitor' => __DIR__ . '/..' . '/twig/twig/src/NodeVisitor/EscaperNodeVisitor.php', + 'Twig\\NodeVisitor\\NodeVisitorInterface' => __DIR__ . '/..' . '/twig/twig/src/NodeVisitor/NodeVisitorInterface.php', + 'Twig\\NodeVisitor\\OptimizerNodeVisitor' => __DIR__ . '/..' . '/twig/twig/src/NodeVisitor/OptimizerNodeVisitor.php', + 'Twig\\NodeVisitor\\SafeAnalysisNodeVisitor' => __DIR__ . '/..' . '/twig/twig/src/NodeVisitor/SafeAnalysisNodeVisitor.php', + 'Twig\\NodeVisitor\\SandboxNodeVisitor' => __DIR__ . '/..' . '/twig/twig/src/NodeVisitor/SandboxNodeVisitor.php', + 'Twig\\Node\\AutoEscapeNode' => __DIR__ . '/..' . '/twig/twig/src/Node/AutoEscapeNode.php', + 'Twig\\Node\\BlockNode' => __DIR__ . '/..' . '/twig/twig/src/Node/BlockNode.php', + 'Twig\\Node\\BlockReferenceNode' => __DIR__ . '/..' . '/twig/twig/src/Node/BlockReferenceNode.php', + 'Twig\\Node\\BodyNode' => __DIR__ . '/..' . '/twig/twig/src/Node/BodyNode.php', + 'Twig\\Node\\CheckSecurityNode' => __DIR__ . '/..' . '/twig/twig/src/Node/CheckSecurityNode.php', + 'Twig\\Node\\DeprecatedNode' => __DIR__ . '/..' . '/twig/twig/src/Node/DeprecatedNode.php', + 'Twig\\Node\\DoNode' => __DIR__ . '/..' . '/twig/twig/src/Node/DoNode.php', + 'Twig\\Node\\EmbedNode' => __DIR__ . '/..' . '/twig/twig/src/Node/EmbedNode.php', + 'Twig\\Node\\Expression\\AbstractExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/AbstractExpression.php', + 'Twig\\Node\\Expression\\ArrayExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/ArrayExpression.php', + 'Twig\\Node\\Expression\\AssignNameExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/AssignNameExpression.php', + 'Twig\\Node\\Expression\\Binary\\AbstractBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/AbstractBinary.php', + 'Twig\\Node\\Expression\\Binary\\AddBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/AddBinary.php', + 'Twig\\Node\\Expression\\Binary\\AndBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/AndBinary.php', + 'Twig\\Node\\Expression\\Binary\\BitwiseAndBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/BitwiseAndBinary.php', + 'Twig\\Node\\Expression\\Binary\\BitwiseOrBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/BitwiseOrBinary.php', + 'Twig\\Node\\Expression\\Binary\\BitwiseXorBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/BitwiseXorBinary.php', + 'Twig\\Node\\Expression\\Binary\\ConcatBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/ConcatBinary.php', + 'Twig\\Node\\Expression\\Binary\\DivBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/DivBinary.php', + 'Twig\\Node\\Expression\\Binary\\EndsWithBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/EndsWithBinary.php', + 'Twig\\Node\\Expression\\Binary\\EqualBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/EqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\FloorDivBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/FloorDivBinary.php', + 'Twig\\Node\\Expression\\Binary\\GreaterBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/GreaterBinary.php', + 'Twig\\Node\\Expression\\Binary\\GreaterEqualBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/GreaterEqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\InBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/InBinary.php', + 'Twig\\Node\\Expression\\Binary\\LessBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/LessBinary.php', + 'Twig\\Node\\Expression\\Binary\\LessEqualBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/LessEqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\MatchesBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/MatchesBinary.php', + 'Twig\\Node\\Expression\\Binary\\ModBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/ModBinary.php', + 'Twig\\Node\\Expression\\Binary\\MulBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/MulBinary.php', + 'Twig\\Node\\Expression\\Binary\\NotEqualBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/NotEqualBinary.php', + 'Twig\\Node\\Expression\\Binary\\NotInBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/NotInBinary.php', + 'Twig\\Node\\Expression\\Binary\\OrBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/OrBinary.php', + 'Twig\\Node\\Expression\\Binary\\PowerBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/PowerBinary.php', + 'Twig\\Node\\Expression\\Binary\\RangeBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/RangeBinary.php', + 'Twig\\Node\\Expression\\Binary\\StartsWithBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/StartsWithBinary.php', + 'Twig\\Node\\Expression\\Binary\\SubBinary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Binary/SubBinary.php', + 'Twig\\Node\\Expression\\BlockReferenceExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/BlockReferenceExpression.php', + 'Twig\\Node\\Expression\\CallExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/CallExpression.php', + 'Twig\\Node\\Expression\\ConditionalExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/ConditionalExpression.php', + 'Twig\\Node\\Expression\\ConstantExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/ConstantExpression.php', + 'Twig\\Node\\Expression\\FilterExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/FilterExpression.php', + 'Twig\\Node\\Expression\\Filter\\DefaultFilter' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Filter/DefaultFilter.php', + 'Twig\\Node\\Expression\\FunctionExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/FunctionExpression.php', + 'Twig\\Node\\Expression\\GetAttrExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/GetAttrExpression.php', + 'Twig\\Node\\Expression\\MethodCallExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/MethodCallExpression.php', + 'Twig\\Node\\Expression\\NameExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/NameExpression.php', + 'Twig\\Node\\Expression\\NullCoalesceExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/NullCoalesceExpression.php', + 'Twig\\Node\\Expression\\ParentExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/ParentExpression.php', + 'Twig\\Node\\Expression\\TempNameExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/TempNameExpression.php', + 'Twig\\Node\\Expression\\TestExpression' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/TestExpression.php', + 'Twig\\Node\\Expression\\Test\\ConstantTest' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Test/ConstantTest.php', + 'Twig\\Node\\Expression\\Test\\DefinedTest' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Test/DefinedTest.php', + 'Twig\\Node\\Expression\\Test\\DivisiblebyTest' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Test/DivisiblebyTest.php', + 'Twig\\Node\\Expression\\Test\\EvenTest' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Test/EvenTest.php', + 'Twig\\Node\\Expression\\Test\\NullTest' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Test/NullTest.php', + 'Twig\\Node\\Expression\\Test\\OddTest' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Test/OddTest.php', + 'Twig\\Node\\Expression\\Test\\SameasTest' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Test/SameasTest.php', + 'Twig\\Node\\Expression\\Unary\\AbstractUnary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Unary/AbstractUnary.php', + 'Twig\\Node\\Expression\\Unary\\NegUnary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Unary/NegUnary.php', + 'Twig\\Node\\Expression\\Unary\\NotUnary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Unary/NotUnary.php', + 'Twig\\Node\\Expression\\Unary\\PosUnary' => __DIR__ . '/..' . '/twig/twig/src/Node/Expression/Unary/PosUnary.php', + 'Twig\\Node\\FlushNode' => __DIR__ . '/..' . '/twig/twig/src/Node/FlushNode.php', + 'Twig\\Node\\ForLoopNode' => __DIR__ . '/..' . '/twig/twig/src/Node/ForLoopNode.php', + 'Twig\\Node\\ForNode' => __DIR__ . '/..' . '/twig/twig/src/Node/ForNode.php', + 'Twig\\Node\\IfNode' => __DIR__ . '/..' . '/twig/twig/src/Node/IfNode.php', + 'Twig\\Node\\ImportNode' => __DIR__ . '/..' . '/twig/twig/src/Node/ImportNode.php', + 'Twig\\Node\\IncludeNode' => __DIR__ . '/..' . '/twig/twig/src/Node/IncludeNode.php', + 'Twig\\Node\\MacroNode' => __DIR__ . '/..' . '/twig/twig/src/Node/MacroNode.php', + 'Twig\\Node\\ModuleNode' => __DIR__ . '/..' . '/twig/twig/src/Node/ModuleNode.php', + 'Twig\\Node\\Node' => __DIR__ . '/..' . '/twig/twig/src/Node/Node.php', + 'Twig\\Node\\NodeCaptureInterface' => __DIR__ . '/..' . '/twig/twig/src/Node/NodeCaptureInterface.php', + 'Twig\\Node\\NodeOutputInterface' => __DIR__ . '/..' . '/twig/twig/src/Node/NodeOutputInterface.php', + 'Twig\\Node\\PrintNode' => __DIR__ . '/..' . '/twig/twig/src/Node/PrintNode.php', + 'Twig\\Node\\SandboxNode' => __DIR__ . '/..' . '/twig/twig/src/Node/SandboxNode.php', + 'Twig\\Node\\SandboxedPrintNode' => __DIR__ . '/..' . '/twig/twig/src/Node/SandboxedPrintNode.php', + 'Twig\\Node\\SetNode' => __DIR__ . '/..' . '/twig/twig/src/Node/SetNode.php', + 'Twig\\Node\\SetTempNode' => __DIR__ . '/..' . '/twig/twig/src/Node/SetTempNode.php', + 'Twig\\Node\\SpacelessNode' => __DIR__ . '/..' . '/twig/twig/src/Node/SpacelessNode.php', + 'Twig\\Node\\TextNode' => __DIR__ . '/..' . '/twig/twig/src/Node/TextNode.php', + 'Twig\\Node\\WithNode' => __DIR__ . '/..' . '/twig/twig/src/Node/WithNode.php', + 'Twig\\Parser' => __DIR__ . '/..' . '/twig/twig/src/Parser.php', + 'Twig\\Profiler\\Dumper\\BaseDumper' => __DIR__ . '/..' . '/twig/twig/src/Profiler/Dumper/BaseDumper.php', + 'Twig\\Profiler\\Dumper\\BlackfireDumper' => __DIR__ . '/..' . '/twig/twig/src/Profiler/Dumper/BlackfireDumper.php', + 'Twig\\Profiler\\Dumper\\HtmlDumper' => __DIR__ . '/..' . '/twig/twig/src/Profiler/Dumper/HtmlDumper.php', + 'Twig\\Profiler\\Dumper\\TextDumper' => __DIR__ . '/..' . '/twig/twig/src/Profiler/Dumper/TextDumper.php', + 'Twig\\Profiler\\NodeVisitor\\ProfilerNodeVisitor' => __DIR__ . '/..' . '/twig/twig/src/Profiler/NodeVisitor/ProfilerNodeVisitor.php', + 'Twig\\Profiler\\Node\\EnterProfileNode' => __DIR__ . '/..' . '/twig/twig/src/Profiler/Node/EnterProfileNode.php', + 'Twig\\Profiler\\Node\\LeaveProfileNode' => __DIR__ . '/..' . '/twig/twig/src/Profiler/Node/LeaveProfileNode.php', + 'Twig\\Profiler\\Profile' => __DIR__ . '/..' . '/twig/twig/src/Profiler/Profile.php', + 'Twig\\RuntimeLoader\\ContainerRuntimeLoader' => __DIR__ . '/..' . '/twig/twig/src/RuntimeLoader/ContainerRuntimeLoader.php', + 'Twig\\RuntimeLoader\\FactoryRuntimeLoader' => __DIR__ . '/..' . '/twig/twig/src/RuntimeLoader/FactoryRuntimeLoader.php', + 'Twig\\RuntimeLoader\\RuntimeLoaderInterface' => __DIR__ . '/..' . '/twig/twig/src/RuntimeLoader/RuntimeLoaderInterface.php', + 'Twig\\Sandbox\\SecurityError' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityError.php', + 'Twig\\Sandbox\\SecurityNotAllowedFilterError' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityNotAllowedFilterError.php', + 'Twig\\Sandbox\\SecurityNotAllowedFunctionError' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityNotAllowedFunctionError.php', + 'Twig\\Sandbox\\SecurityNotAllowedMethodError' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityNotAllowedMethodError.php', + 'Twig\\Sandbox\\SecurityNotAllowedPropertyError' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityNotAllowedPropertyError.php', + 'Twig\\Sandbox\\SecurityNotAllowedTagError' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityNotAllowedTagError.php', + 'Twig\\Sandbox\\SecurityPolicy' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityPolicy.php', + 'Twig\\Sandbox\\SecurityPolicyInterface' => __DIR__ . '/..' . '/twig/twig/src/Sandbox/SecurityPolicyInterface.php', + 'Twig\\Source' => __DIR__ . '/..' . '/twig/twig/src/Source.php', + 'Twig\\Template' => __DIR__ . '/..' . '/twig/twig/src/Template.php', + 'Twig\\TemplateWrapper' => __DIR__ . '/..' . '/twig/twig/src/TemplateWrapper.php', + 'Twig\\Test\\IntegrationTestCase' => __DIR__ . '/..' . '/twig/twig/src/Test/IntegrationTestCase.php', + 'Twig\\Test\\NodeTestCase' => __DIR__ . '/..' . '/twig/twig/src/Test/NodeTestCase.php', + 'Twig\\Token' => __DIR__ . '/..' . '/twig/twig/src/Token.php', + 'Twig\\TokenParser\\AbstractTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/AbstractTokenParser.php', + 'Twig\\TokenParser\\AutoEscapeTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/AutoEscapeTokenParser.php', + 'Twig\\TokenParser\\BlockTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/BlockTokenParser.php', + 'Twig\\TokenParser\\DeprecatedTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/DeprecatedTokenParser.php', + 'Twig\\TokenParser\\DoTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/DoTokenParser.php', + 'Twig\\TokenParser\\EmbedTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/EmbedTokenParser.php', + 'Twig\\TokenParser\\ExtendsTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/ExtendsTokenParser.php', + 'Twig\\TokenParser\\FilterTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/FilterTokenParser.php', + 'Twig\\TokenParser\\FlushTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/FlushTokenParser.php', + 'Twig\\TokenParser\\ForTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/ForTokenParser.php', + 'Twig\\TokenParser\\FromTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/FromTokenParser.php', + 'Twig\\TokenParser\\IfTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/IfTokenParser.php', + 'Twig\\TokenParser\\ImportTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/ImportTokenParser.php', + 'Twig\\TokenParser\\IncludeTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/IncludeTokenParser.php', + 'Twig\\TokenParser\\MacroTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/MacroTokenParser.php', + 'Twig\\TokenParser\\SandboxTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/SandboxTokenParser.php', + 'Twig\\TokenParser\\SetTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/SetTokenParser.php', + 'Twig\\TokenParser\\SpacelessTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/SpacelessTokenParser.php', + 'Twig\\TokenParser\\TokenParserInterface' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/TokenParserInterface.php', + 'Twig\\TokenParser\\UseTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/UseTokenParser.php', + 'Twig\\TokenParser\\WithTokenParser' => __DIR__ . '/..' . '/twig/twig/src/TokenParser/WithTokenParser.php', + 'Twig\\TokenStream' => __DIR__ . '/..' . '/twig/twig/src/TokenStream.php', + 'Twig\\TwigFilter' => __DIR__ . '/..' . '/twig/twig/src/TwigFilter.php', + 'Twig\\TwigFunction' => __DIR__ . '/..' . '/twig/twig/src/TwigFunction.php', + 'Twig\\TwigTest' => __DIR__ . '/..' . '/twig/twig/src/TwigTest.php', + 'Twig\\Util\\DeprecationCollector' => __DIR__ . '/..' . '/twig/twig/src/Util/DeprecationCollector.php', + 'Twig\\Util\\TemplateDirIterator' => __DIR__ . '/..' . '/twig/twig/src/Util/TemplateDirIterator.php', + 'Twig_Autoloader' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Autoloader.php', + 'Twig_BaseNodeVisitor' => __DIR__ . '/..' . '/twig/twig/lib/Twig/BaseNodeVisitor.php', + 'Twig_CacheInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/CacheInterface.php', + 'Twig_Cache_Filesystem' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Cache/Filesystem.php', + 'Twig_Cache_Null' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Cache/Null.php', + 'Twig_Compiler' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Compiler.php', + 'Twig_CompilerInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/CompilerInterface.php', + 'Twig_ContainerRuntimeLoader' => __DIR__ . '/..' . '/twig/twig/lib/Twig/ContainerRuntimeLoader.php', + 'Twig_Environment' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Environment.php', + 'Twig_Error' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Error.php', + 'Twig_Error_Loader' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Error/Loader.php', + 'Twig_Error_Runtime' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Error/Runtime.php', + 'Twig_Error_Syntax' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Error/Syntax.php', + 'Twig_ExistsLoaderInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/ExistsLoaderInterface.php', + 'Twig_ExpressionParser' => __DIR__ . '/..' . '/twig/twig/lib/Twig/ExpressionParser.php', + 'Twig_Extension' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension.php', + 'Twig_ExtensionInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/ExtensionInterface.php', + 'Twig_Extension_Core' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/Core.php', + 'Twig_Extension_Debug' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/Debug.php', + 'Twig_Extension_Escaper' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/Escaper.php', + 'Twig_Extension_GlobalsInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/GlobalsInterface.php', + 'Twig_Extension_InitRuntimeInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/InitRuntimeInterface.php', + 'Twig_Extension_Optimizer' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/Optimizer.php', + 'Twig_Extension_Profiler' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/Profiler.php', + 'Twig_Extension_Sandbox' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/Sandbox.php', + 'Twig_Extension_Staging' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/Staging.php', + 'Twig_Extension_StringLoader' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Extension/StringLoader.php', + 'Twig_FactoryRuntimeLoader' => __DIR__ . '/..' . '/twig/twig/lib/Twig/FactoryRuntimeLoader.php', + 'Twig_FileExtensionEscapingStrategy' => __DIR__ . '/..' . '/twig/twig/lib/Twig/FileExtensionEscapingStrategy.php', + 'Twig_Filter' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Filter.php', + 'Twig_FilterCallableInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/FilterCallableInterface.php', + 'Twig_FilterInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/FilterInterface.php', + 'Twig_Filter_Function' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Filter/Function.php', + 'Twig_Filter_Method' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Filter/Method.php', + 'Twig_Filter_Node' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Filter/Node.php', + 'Twig_Function' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Function.php', + 'Twig_FunctionCallableInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/FunctionCallableInterface.php', + 'Twig_FunctionInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/FunctionInterface.php', + 'Twig_Function_Function' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Function/Function.php', + 'Twig_Function_Method' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Function/Method.php', + 'Twig_Function_Node' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Function/Node.php', + 'Twig_Lexer' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Lexer.php', + 'Twig_LexerInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/LexerInterface.php', + 'Twig_LoaderInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/LoaderInterface.php', + 'Twig_Loader_Array' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Loader/Array.php', + 'Twig_Loader_Chain' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Loader/Chain.php', + 'Twig_Loader_Filesystem' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Loader/Filesystem.php', + 'Twig_Loader_String' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Loader/String.php', + 'Twig_Markup' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Markup.php', + 'Twig_Node' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node.php', + 'Twig_NodeCaptureInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeCaptureInterface.php', + 'Twig_NodeInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeInterface.php', + 'Twig_NodeOutputInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeOutputInterface.php', + 'Twig_NodeTraverser' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeTraverser.php', + 'Twig_NodeVisitorInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeVisitorInterface.php', + 'Twig_NodeVisitor_Escaper' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeVisitor/Escaper.php', + 'Twig_NodeVisitor_Optimizer' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeVisitor/Optimizer.php', + 'Twig_NodeVisitor_SafeAnalysis' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeVisitor/SafeAnalysis.php', + 'Twig_NodeVisitor_Sandbox' => __DIR__ . '/..' . '/twig/twig/lib/Twig/NodeVisitor/Sandbox.php', + 'Twig_Node_AutoEscape' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/AutoEscape.php', + 'Twig_Node_Block' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Block.php', + 'Twig_Node_BlockReference' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/BlockReference.php', + 'Twig_Node_Body' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Body.php', + 'Twig_Node_CheckSecurity' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/CheckSecurity.php', + 'Twig_Node_Deprecated' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Deprecated.php', + 'Twig_Node_Do' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Do.php', + 'Twig_Node_Embed' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Embed.php', + 'Twig_Node_Expression' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression.php', + 'Twig_Node_Expression_Array' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Array.php', + 'Twig_Node_Expression_AssignName' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/AssignName.php', + 'Twig_Node_Expression_Binary' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary.php', + 'Twig_Node_Expression_Binary_Add' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Add.php', + 'Twig_Node_Expression_Binary_And' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/And.php', + 'Twig_Node_Expression_Binary_BitwiseAnd' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseAnd.php', + 'Twig_Node_Expression_Binary_BitwiseOr' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseOr.php', + 'Twig_Node_Expression_Binary_BitwiseXor' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseXor.php', + 'Twig_Node_Expression_Binary_Concat' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Concat.php', + 'Twig_Node_Expression_Binary_Div' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Div.php', + 'Twig_Node_Expression_Binary_EndsWith' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/EndsWith.php', + 'Twig_Node_Expression_Binary_Equal' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Equal.php', + 'Twig_Node_Expression_Binary_FloorDiv' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/FloorDiv.php', + 'Twig_Node_Expression_Binary_Greater' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Greater.php', + 'Twig_Node_Expression_Binary_GreaterEqual' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/GreaterEqual.php', + 'Twig_Node_Expression_Binary_In' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/In.php', + 'Twig_Node_Expression_Binary_Less' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Less.php', + 'Twig_Node_Expression_Binary_LessEqual' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/LessEqual.php', + 'Twig_Node_Expression_Binary_Matches' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Matches.php', + 'Twig_Node_Expression_Binary_Mod' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Mod.php', + 'Twig_Node_Expression_Binary_Mul' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Mul.php', + 'Twig_Node_Expression_Binary_NotEqual' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/NotEqual.php', + 'Twig_Node_Expression_Binary_NotIn' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/NotIn.php', + 'Twig_Node_Expression_Binary_Or' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Or.php', + 'Twig_Node_Expression_Binary_Power' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Power.php', + 'Twig_Node_Expression_Binary_Range' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Range.php', + 'Twig_Node_Expression_Binary_StartsWith' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/StartsWith.php', + 'Twig_Node_Expression_Binary_Sub' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Binary/Sub.php', + 'Twig_Node_Expression_BlockReference' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/BlockReference.php', + 'Twig_Node_Expression_Call' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Call.php', + 'Twig_Node_Expression_Conditional' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Conditional.php', + 'Twig_Node_Expression_Constant' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Constant.php', + 'Twig_Node_Expression_ExtensionReference' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/ExtensionReference.php', + 'Twig_Node_Expression_Filter' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Filter.php', + 'Twig_Node_Expression_Filter_Default' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Filter/Default.php', + 'Twig_Node_Expression_Function' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Function.php', + 'Twig_Node_Expression_GetAttr' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/GetAttr.php', + 'Twig_Node_Expression_MethodCall' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/MethodCall.php', + 'Twig_Node_Expression_Name' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Name.php', + 'Twig_Node_Expression_NullCoalesce' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/NullCoalesce.php', + 'Twig_Node_Expression_Parent' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Parent.php', + 'Twig_Node_Expression_TempName' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/TempName.php', + 'Twig_Node_Expression_Test' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test.php', + 'Twig_Node_Expression_Test_Constant' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test/Constant.php', + 'Twig_Node_Expression_Test_Defined' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test/Defined.php', + 'Twig_Node_Expression_Test_Divisibleby' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test/Divisibleby.php', + 'Twig_Node_Expression_Test_Even' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test/Even.php', + 'Twig_Node_Expression_Test_Null' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test/Null.php', + 'Twig_Node_Expression_Test_Odd' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test/Odd.php', + 'Twig_Node_Expression_Test_Sameas' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Test/Sameas.php', + 'Twig_Node_Expression_Unary' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Unary.php', + 'Twig_Node_Expression_Unary_Neg' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Unary/Neg.php', + 'Twig_Node_Expression_Unary_Not' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Unary/Not.php', + 'Twig_Node_Expression_Unary_Pos' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Expression/Unary/Pos.php', + 'Twig_Node_Flush' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Flush.php', + 'Twig_Node_For' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/For.php', + 'Twig_Node_ForLoop' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/ForLoop.php', + 'Twig_Node_If' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/If.php', + 'Twig_Node_Import' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Import.php', + 'Twig_Node_Include' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Include.php', + 'Twig_Node_Macro' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Macro.php', + 'Twig_Node_Module' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Module.php', + 'Twig_Node_Print' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Print.php', + 'Twig_Node_Sandbox' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Sandbox.php', + 'Twig_Node_SandboxedPrint' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/SandboxedPrint.php', + 'Twig_Node_Set' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Set.php', + 'Twig_Node_SetTemp' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/SetTemp.php', + 'Twig_Node_Spaceless' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Spaceless.php', + 'Twig_Node_Text' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/Text.php', + 'Twig_Node_With' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Node/With.php', + 'Twig_Parser' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Parser.php', + 'Twig_ParserInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/ParserInterface.php', + 'Twig_Profiler_Dumper_Base' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/Dumper/Base.php', + 'Twig_Profiler_Dumper_Blackfire' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/Dumper/Blackfire.php', + 'Twig_Profiler_Dumper_Html' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/Dumper/Html.php', + 'Twig_Profiler_Dumper_Text' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/Dumper/Text.php', + 'Twig_Profiler_NodeVisitor_Profiler' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/NodeVisitor/Profiler.php', + 'Twig_Profiler_Node_EnterProfile' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/Node/EnterProfile.php', + 'Twig_Profiler_Node_LeaveProfile' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/Node/LeaveProfile.php', + 'Twig_Profiler_Profile' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Profiler/Profile.php', + 'Twig_RuntimeLoaderInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/RuntimeLoaderInterface.php', + 'Twig_Sandbox_SecurityError' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityError.php', + 'Twig_Sandbox_SecurityNotAllowedFilterError' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFilterError.php', + 'Twig_Sandbox_SecurityNotAllowedFunctionError' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFunctionError.php', + 'Twig_Sandbox_SecurityNotAllowedMethodError' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedMethodError.php', + 'Twig_Sandbox_SecurityNotAllowedPropertyError' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedPropertyError.php', + 'Twig_Sandbox_SecurityNotAllowedTagError' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedTagError.php', + 'Twig_Sandbox_SecurityPolicy' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityPolicy.php', + 'Twig_Sandbox_SecurityPolicyInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Sandbox/SecurityPolicyInterface.php', + 'Twig_SimpleFilter' => __DIR__ . '/..' . '/twig/twig/lib/Twig/SimpleFilter.php', + 'Twig_SimpleFunction' => __DIR__ . '/..' . '/twig/twig/lib/Twig/SimpleFunction.php', + 'Twig_SimpleTest' => __DIR__ . '/..' . '/twig/twig/lib/Twig/SimpleTest.php', + 'Twig_Source' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Source.php', + 'Twig_SourceContextLoaderInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/SourceContextLoaderInterface.php', + 'Twig_Template' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Template.php', + 'Twig_TemplateInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TemplateInterface.php', + 'Twig_TemplateWrapper' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TemplateWrapper.php', + 'Twig_Test' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Test.php', + 'Twig_TestCallableInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TestCallableInterface.php', + 'Twig_TestInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TestInterface.php', + 'Twig_Test_Function' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Test/Function.php', + 'Twig_Test_IntegrationTestCase' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Test/IntegrationTestCase.php', + 'Twig_Test_Method' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Test/Method.php', + 'Twig_Test_Node' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Test/Node.php', + 'Twig_Test_NodeTestCase' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Test/NodeTestCase.php', + 'Twig_Token' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Token.php', + 'Twig_TokenParser' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser.php', + 'Twig_TokenParserBroker' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParserBroker.php', + 'Twig_TokenParserBrokerInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParserBrokerInterface.php', + 'Twig_TokenParserInterface' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParserInterface.php', + 'Twig_TokenParser_AutoEscape' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/AutoEscape.php', + 'Twig_TokenParser_Block' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Block.php', + 'Twig_TokenParser_Deprecated' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Deprecated.php', + 'Twig_TokenParser_Do' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Do.php', + 'Twig_TokenParser_Embed' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Embed.php', + 'Twig_TokenParser_Extends' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Extends.php', + 'Twig_TokenParser_Filter' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Filter.php', + 'Twig_TokenParser_Flush' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Flush.php', + 'Twig_TokenParser_For' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/For.php', + 'Twig_TokenParser_From' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/From.php', + 'Twig_TokenParser_If' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/If.php', + 'Twig_TokenParser_Import' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Import.php', + 'Twig_TokenParser_Include' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Include.php', + 'Twig_TokenParser_Macro' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Macro.php', + 'Twig_TokenParser_Sandbox' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Sandbox.php', + 'Twig_TokenParser_Set' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Set.php', + 'Twig_TokenParser_Spaceless' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Spaceless.php', + 'Twig_TokenParser_Use' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/Use.php', + 'Twig_TokenParser_With' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenParser/With.php', + 'Twig_TokenStream' => __DIR__ . '/..' . '/twig/twig/lib/Twig/TokenStream.php', + 'Twig_Util_DeprecationCollector' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Util/DeprecationCollector.php', + 'Twig_Util_TemplateDirIterator' => __DIR__ . '/..' . '/twig/twig/lib/Twig/Util/TemplateDirIterator.php', + ); + + public static function getInitializer(ClassLoader $loader) + { + return \Closure::bind(function () use ($loader) { + $loader->prefixLengthsPsr4 = ComposerStaticInit37bcf3c1669669b4e374fd17d45b1c62::$prefixLengthsPsr4; + $loader->prefixDirsPsr4 = ComposerStaticInit37bcf3c1669669b4e374fd17d45b1c62::$prefixDirsPsr4; + $loader->prefixesPsr0 = ComposerStaticInit37bcf3c1669669b4e374fd17d45b1c62::$prefixesPsr0; + $loader->classMap = ComposerStaticInit37bcf3c1669669b4e374fd17d45b1c62::$classMap; + + }, null, ClassLoader::class); + } +} diff --git a/vendor/composer/installed.json b/vendor/composer/installed.json new file mode 100644 index 0000000..4232b01 --- /dev/null +++ b/vendor/composer/installed.json @@ -0,0 +1,573 @@ +[ + { + "name": "erusev/parsedown", + "version": "1.8.0-beta-7", + "version_normalized": "1.8.0.0-beta7", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown.git", + "reference": "fe7a50eceb4a3c867cc9fa9c0aa906b1067d1955" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown/zipball/fe7a50eceb4a3c867cc9fa9c0aa906b1067d1955", + "reference": "fe7a50eceb4a3c867cc9fa9c0aa906b1067d1955", + "shasum": "" + }, + "require": { + "ext-mbstring": "*", + "php": ">=5.3.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35" + }, + "time": "2019-03-17T18:47:21+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "Parsedown": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "Parser for Markdown.", + "homepage": "http://parsedown.org", + "keywords": [ + "markdown", + "parser" + ] + }, + { + "name": "erusev/parsedown-extra", + "version": "0.8.0-beta-1", + "version_normalized": "0.8.0.0-beta1", + "source": { + "type": "git", + "url": "https://github.com/erusev/parsedown-extra.git", + "reference": "e756b1bf8642ab1091403e902b0503f1cec7527d" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/erusev/parsedown-extra/zipball/e756b1bf8642ab1091403e902b0503f1cec7527d", + "reference": "e756b1bf8642ab1091403e902b0503f1cec7527d", + "shasum": "" + }, + "require": { + "erusev/parsedown": "^1.8.0|^1.8.0-beta-4", + "ext-dom": "*", + "ext-mbstring": "*", + "php": ">=5.3.6" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35" + }, + "time": "2018-05-08T21:54:32+00:00", + "type": "library", + "installation-source": "dist", + "autoload": { + "psr-0": { + "ParsedownExtra": "" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "description": "An extension of Parsedown that adds support for Markdown Extra.", + "homepage": "https://github.com/erusev/parsedown-extra", + "keywords": [ + "markdown", + "markdown extra", + "parsedown", + "parser" + ] + }, + { + "name": "picocms/composer-installer", + "version": "v1.0.1", + "version_normalized": "1.0.1.0", + "source": { + "type": "git", + "url": "https://github.com/picocms/composer-installer.git", + "reference": "6b5036c83aa091ed76e2a76ed9335885f95a7db7" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/picocms/composer-installer/zipball/6b5036c83aa091ed76e2a76ed9335885f95a7db7", + "reference": "6b5036c83aa091ed76e2a76ed9335885f95a7db7", + "shasum": "" + }, + "time": "2019-11-24T22:50:47+00:00", + "type": "composer-installer", + "extra": { + "class": "Pico\\Composer\\Installer\\PluginInstaller" + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Pico\\Composer\\": "src" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Daniel Rudolf", + "email": "picocms.org@daniel-rudolf.de", + "role": "Lead Developer" + }, + { + "name": "The Pico Community", + "homepage": "http://picocms.org/" + }, + { + "name": "Contributors", + "homepage": "https://github.com/picocms/composer-installer/graphs/contributors" + } + ], + "description": "A composer plugin responsible for installing plugins and themes for Pico, a stupidly simple, blazing fast, flat file CMS.", + "homepage": "http://picocms.org/", + "keywords": [ + "composer", + "composer-installer", + "composer-plugin", + "pico", + "pico-cms", + "picocms", + "picocms-installer", + "picocms-plugin", + "picocms-theme" + ] + }, + { + "name": "picocms/pico", + "version": "v2.1.4", + "version_normalized": "2.1.4.0", + "source": { + "type": "git", + "url": "https://github.com/picocms/Pico.git", + "reference": "7228129cade3f812f22904b503c939b04a75c9dd" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/picocms/Pico/zipball/7228129cade3f812f22904b503c939b04a75c9dd", + "reference": "7228129cade3f812f22904b503c939b04a75c9dd", + "shasum": "" + }, + "require": { + "erusev/parsedown": "1.8.0-beta-7", + "erusev/parsedown-extra": "0.8.0-beta-1", + "ext-mbstring": "*", + "php": ">=5.3.6", + "symfony/yaml": "^2.8", + "twig/twig": "^1.36" + }, + "suggest": { + "picocms/composer-installer": "This Composer plugin is responsible for installing Pico plugins and themes using the Composer package manager.", + "picocms/pico-deprecated": "PicoDeprecated's purpose is to maintain backward compatibility to older versions of Pico.", + "picocms/pico-theme": "Pico requires a theme to actually display the contents of your website. This is Pico's official default theme." + }, + "time": "2020-08-29T14:15:52+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev", + "dev-pico-3.0": "3.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Pico": "lib/", + "PicoPluginInterface": "lib/", + "AbstractPicoPlugin": "lib/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gilbert Pellegrom", + "email": "gilbert@pellegrom.me", + "role": "Project Founder" + }, + { + "name": "Daniel Rudolf", + "email": "picocms.org@daniel-rudolf.de", + "role": "Lead Developer" + }, + { + "name": "The Pico Community", + "homepage": "http://picocms.org/" + }, + { + "name": "Contributors", + "homepage": "https://github.com/picocms/Pico/graphs/contributors" + } + ], + "description": "Pico is a flat file CMS, this means there is no administration backend and database to deal with. You simply create .md files in the \"content\" folder and that becomes a page.", + "homepage": "http://picocms.org/", + "keywords": [ + "Simple", + "cms", + "content-management", + "flat-file", + "markdown", + "markdown-to-html", + "php", + "pico", + "pico-cms", + "picocms", + "twig", + "website", + "yaml" + ], + "funding": [ + { + "url": "https://www.bountysource.com/teams/picocms", + "type": "custom" + } + ] + }, + { + "name": "picocms/pico-deprecated", + "version": "v2.1.4", + "version_normalized": "2.1.4.0", + "source": { + "type": "git", + "url": "https://github.com/picocms/pico-deprecated.git", + "reference": "8d1a4056ecc71cc2857e91d50bcb38db91d424e0" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/picocms/pico-deprecated/zipball/8d1a4056ecc71cc2857e91d50bcb38db91d424e0", + "reference": "8d1a4056ecc71cc2857e91d50bcb38db91d424e0", + "shasum": "" + }, + "require": { + "php": ">=5.3.0", + "picocms/pico": "self.version" + }, + "time": "2020-08-29T15:11:07+00:00", + "type": "pico-plugin", + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev", + "dev-pico-3.0": "3.0.x-dev" + } + }, + "installation-source": "dist", + "autoload": { + "classmap": [ + "PicoDeprecated.php", + "lib/", + "plugins/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Daniel Rudolf", + "email": "picocms.org@daniel-rudolf.de", + "role": "Lead Developer" + }, + { + "name": "The Pico Community", + "homepage": "http://picocms.org/" + }, + { + "name": "Contributors", + "homepage": "https://github.com/picocms/pico-deprecated/graphs/contributors" + } + ], + "description": "This is Pico's official PicoDeprecated plugin. Pico is a stupidly simple, blazing fast, flat file CMS.", + "homepage": "http://picocms.org/", + "keywords": [ + "compatibility", + "deprecation", + "pico", + "pico-deprecated", + "picocms", + "picocms-plugin" + ] + }, + { + "name": "picocms/pico-theme", + "version": "v2.1.4", + "version_normalized": "2.1.4.0", + "source": { + "type": "git", + "url": "https://github.com/picocms/pico-theme.git", + "reference": "d4ec8df28356f1e034a97d37327b9aecb3129eed" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/picocms/pico-theme/zipball/d4ec8df28356f1e034a97d37327b9aecb3129eed", + "reference": "d4ec8df28356f1e034a97d37327b9aecb3129eed", + "shasum": "" + }, + "require": { + "picocms/pico": "self.version" + }, + "time": "2020-08-29T15:11:43+00:00", + "type": "pico-theme", + "extra": { + "installer-name": "default", + "branch-alias": { + "dev-master": "2.1.x-dev", + "dev-pico-3.0": "3.0.x-dev" + } + }, + "installation-source": "dist", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Daniel Rudolf", + "email": "picocms.org@daniel-rudolf.de", + "role": "Lead Developer" + }, + { + "name": "The Pico Community", + "homepage": "http://picocms.org/" + }, + { + "name": "Contributors", + "homepage": "https://github.com/picocms/pico-theme/graphs/contributors" + } + ], + "description": "This is Pico's official default theme. Pico is a stupidly simple, blazing fast, flat file CMS.", + "homepage": "http://picocms.org/", + "keywords": [ + "default-theme", + "pico", + "pico-theme", + "picocms", + "picocms-theme" + ] + }, + { + "name": "symfony/polyfill-ctype", + "version": "v1.18.1", + "version_normalized": "1.18.1.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/polyfill-ctype.git", + "reference": "1c302646f6efc070cd46856e600e5e0684d6b454" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/polyfill-ctype/zipball/1c302646f6efc070cd46856e600e5e0684d6b454", + "reference": "1c302646f6efc070cd46856e600e5e0684d6b454", + "shasum": "" + }, + "require": { + "php": ">=5.3.3" + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "time": "2020-07-14T12:35:20+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Polyfill\\Ctype\\": "" + }, + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony polyfill for ctype functions", + "homepage": "https://symfony.com", + "keywords": [ + "compatibility", + "ctype", + "polyfill", + "portable" + ], + "funding": [ + { + "url": "https://symfony.com/sponsor", + "type": "custom" + }, + { + "url": "https://github.com/fabpot", + "type": "github" + }, + { + "url": "https://tidelift.com/funding/github/packagist/symfony/symfony", + "type": "tidelift" + } + ] + }, + { + "name": "symfony/yaml", + "version": "v2.8.52", + "version_normalized": "2.8.52.0", + "source": { + "type": "git", + "url": "https://github.com/symfony/yaml.git", + "reference": "02c1859112aa779d9ab394ae4f3381911d84052b" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/symfony/yaml/zipball/02c1859112aa779d9ab394ae4f3381911d84052b", + "reference": "02c1859112aa779d9ab394ae4f3381911d84052b", + "shasum": "" + }, + "require": { + "php": ">=5.3.9", + "symfony/polyfill-ctype": "~1.8" + }, + "time": "2018-11-11T11:18:13+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-4": { + "Symfony\\Component\\Yaml\\": "" + }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "description": "Symfony Yaml Component", + "homepage": "https://symfony.com" + }, + { + "name": "twig/twig", + "version": "v1.36.0", + "version_normalized": "1.36.0.0", + "source": { + "type": "git", + "url": "https://github.com/twigphp/Twig.git", + "reference": "730c9c4471b5152d23061feb02b03382264c8a15" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/twigphp/Twig/zipball/730c9c4471b5152d23061feb02b03382264c8a15", + "reference": "730c9c4471b5152d23061feb02b03382264c8a15", + "shasum": "" + }, + "require": { + "php": ">=5.3.3", + "symfony/polyfill-ctype": "^1.8" + }, + "require-dev": { + "psr/container": "^1.0", + "symfony/debug": "^2.7", + "symfony/phpunit-bridge": "^3.4.19|^4.1.8" + }, + "time": "2018-12-16T10:34:11+00:00", + "type": "library", + "extra": { + "branch-alias": { + "dev-master": "1.36-dev" + } + }, + "installation-source": "dist", + "autoload": { + "psr-0": { + "Twig_": "lib/" + }, + "psr-4": { + "Twig\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Armin Ronacher", + "email": "armin.ronacher@active-4.com", + "role": "Project Founder" + }, + { + "name": "Twig Team", + "homepage": "https://twig.symfony.com/contributors", + "role": "Contributors" + } + ], + "description": "Twig, the flexible, fast, and secure template language for PHP", + "homepage": "https://twig.symfony.com", + "keywords": [ + "templating" + ] + } +] diff --git a/vendor/erusev/parsedown-extra/.gitignore b/vendor/erusev/parsedown-extra/.gitignore new file mode 100644 index 0000000..d1502b0 --- /dev/null +++ b/vendor/erusev/parsedown-extra/.gitignore @@ -0,0 +1,2 @@ +vendor/ +composer.lock diff --git a/vendor/erusev/parsedown-extra/LICENSE.txt b/vendor/erusev/parsedown-extra/LICENSE.txt new file mode 100644 index 0000000..baca86f --- /dev/null +++ b/vendor/erusev/parsedown-extra/LICENSE.txt @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Emanuil Rusev, erusev.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/erusev/parsedown-extra/ParsedownExtra.php b/vendor/erusev/parsedown-extra/ParsedownExtra.php new file mode 100644 index 0000000..6a6e4e3 --- /dev/null +++ b/vendor/erusev/parsedown-extra/ParsedownExtra.php @@ -0,0 +1,686 @@ +BlockTypes[':'] []= 'DefinitionList'; + $this->BlockTypes['*'] []= 'Abbreviation'; + + # identify footnote definitions before reference definitions + array_unshift($this->BlockTypes['['], 'Footnote'); + + # identify footnote markers before before links + array_unshift($this->InlineTypes['['], 'FootnoteMarker'); + } + + # + # ~ + + function text($text) + { + $Elements = $this->textElements($text); + + # convert to markup + $markup = $this->elements($Elements); + + # trim line breaks + $markup = trim($markup, "\n"); + + # merge consecutive dl elements + + $markup = preg_replace('/<\/dl>\s+
\s+/', '', $markup); + + # add footnotes + + if (isset($this->DefinitionData['Footnote'])) + { + $Element = $this->buildFootnoteElement(); + + $markup .= "\n" . $this->element($Element); + } + + return $markup; + } + + # + # Blocks + # + + # + # Abbreviation + + protected function blockAbbreviation($Line) + { + if (preg_match('/^\*\[(.+?)\]:[ ]*(.+?)[ ]*$/', $Line['text'], $matches)) + { + $this->DefinitionData['Abbreviation'][$matches[1]] = $matches[2]; + + $Block = array( + 'hidden' => true, + ); + + return $Block; + } + } + + # + # Footnote + + protected function blockFootnote($Line) + { + if (preg_match('/^\[\^(.+?)\]:[ ]?(.*)$/', $Line['text'], $matches)) + { + $Block = array( + 'label' => $matches[1], + 'text' => $matches[2], + 'hidden' => true, + ); + + return $Block; + } + } + + protected function blockFootnoteContinue($Line, $Block) + { + if ($Line['text'][0] === '[' and preg_match('/^\[\^(.+?)\]:/', $Line['text'])) + { + return; + } + + if (isset($Block['interrupted'])) + { + if ($Line['indent'] >= 4) + { + $Block['text'] .= "\n\n" . $Line['text']; + + return $Block; + } + } + else + { + $Block['text'] .= "\n" . $Line['text']; + + return $Block; + } + } + + protected function blockFootnoteComplete($Block) + { + $this->DefinitionData['Footnote'][$Block['label']] = array( + 'text' => $Block['text'], + 'count' => null, + 'number' => null, + ); + + return $Block; + } + + # + # Definition List + + protected function blockDefinitionList($Line, $Block) + { + if ( ! isset($Block) or $Block['type'] !== 'Paragraph') + { + return; + } + + $Element = array( + 'name' => 'dl', + 'elements' => array(), + ); + + $terms = explode("\n", $Block['element']['handler']['argument']); + + foreach ($terms as $term) + { + $Element['elements'] []= array( + 'name' => 'dt', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $term, + 'destination' => 'elements' + ), + ); + } + + $Block['element'] = $Element; + + $Block = $this->addDdElement($Line, $Block); + + return $Block; + } + + protected function blockDefinitionListContinue($Line, array $Block) + { + if ($Line['text'][0] === ':') + { + $Block = $this->addDdElement($Line, $Block); + + return $Block; + } + else + { + if (isset($Block['interrupted']) and $Line['indent'] === 0) + { + return; + } + + if (isset($Block['interrupted'])) + { + $Block['dd']['handler']['function'] = 'textElements'; + $Block['dd']['handler']['argument'] .= "\n\n"; + + $Block['dd']['handler']['destination'] = 'elements'; + + unset($Block['interrupted']); + } + + $text = substr($Line['body'], min($Line['indent'], 4)); + + $Block['dd']['handler']['argument'] .= "\n" . $text; + + return $Block; + } + } + + # + # Header + + protected function blockHeader($Line) + { + $Block = parent::blockHeader($Line); + + if (preg_match('/[ #]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) + { + $attributeString = $matches[1][0]; + + $Block['element']['attributes'] = $this->parseAttributeData($attributeString); + + $Block['element']['handler']['argument'] = substr($Block['element']['handler']['argument'], 0, $matches[0][1]); + } + + return $Block; + } + + # + # Markup + + protected function blockMarkup($Line) + { + if ($this->markupEscaped or $this->safeMode) + { + return; + } + + if (preg_match('/^<(\w[\w-]*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches)) + { + $element = strtolower($matches[1]); + + if (in_array($element, $this->textLevelElements)) + { + return; + } + + $Block = array( + 'name' => $matches[1], + 'depth' => 0, + 'element' => array( + 'rawHtml' => $Line['text'], + 'autobreak' => true, + ), + ); + + $length = strlen($matches[0]); + $remainder = substr($Line['text'], $length); + + if (trim($remainder) === '') + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + $Block['closed'] = true; + $Block['void'] = true; + } + } + else + { + if (isset($matches[2]) or in_array($matches[1], $this->voidElements)) + { + return; + } + if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder)) + { + $Block['closed'] = true; + } + } + + return $Block; + } + } + + protected function blockMarkupContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open + { + $Block['depth'] ++; + } + + if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close + { + if ($Block['depth'] > 0) + { + $Block['depth'] --; + } + else + { + $Block['closed'] = true; + } + } + + if (isset($Block['interrupted'])) + { + $Block['element']['rawHtml'] .= "\n"; + unset($Block['interrupted']); + } + + $Block['element']['rawHtml'] .= "\n".$Line['body']; + + return $Block; + } + + protected function blockMarkupComplete($Block) + { + if ( ! isset($Block['void'])) + { + $Block['element']['rawHtml'] = $this->processTag($Block['element']['rawHtml']); + } + + return $Block; + } + + # + # Setext + + protected function blockSetextHeader($Line, array $Block = null) + { + $Block = parent::blockSetextHeader($Line, $Block); + + if (preg_match('/[ ]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['handler']['argument'], $matches, PREG_OFFSET_CAPTURE)) + { + $attributeString = $matches[1][0]; + + $Block['element']['attributes'] = $this->parseAttributeData($attributeString); + + $Block['element']['handler']['argument'] = substr($Block['element']['handler']['argument'], 0, $matches[0][1]); + } + + return $Block; + } + + # + # Inline Elements + # + + # + # Footnote Marker + + protected function inlineFootnoteMarker($Excerpt) + { + if (preg_match('/^\[\^(.+?)\]/', $Excerpt['text'], $matches)) + { + $name = $matches[1]; + + if ( ! isset($this->DefinitionData['Footnote'][$name])) + { + return; + } + + $this->DefinitionData['Footnote'][$name]['count'] ++; + + if ( ! isset($this->DefinitionData['Footnote'][$name]['number'])) + { + $this->DefinitionData['Footnote'][$name]['number'] = ++ $this->footnoteCount; # » & + } + + $Element = array( + 'name' => 'sup', + 'attributes' => array('id' => 'fnref'.$this->DefinitionData['Footnote'][$name]['count'].':'.$name), + 'element' => array( + 'name' => 'a', + 'attributes' => array('href' => '#fn:'.$name, 'class' => 'footnote-ref'), + 'text' => $this->DefinitionData['Footnote'][$name]['number'], + ), + ); + + return array( + 'extent' => strlen($matches[0]), + 'element' => $Element, + ); + } + } + + private $footnoteCount = 0; + + # + # Link + + protected function inlineLink($Excerpt) + { + $Link = parent::inlineLink($Excerpt); + + $remainder = substr($Excerpt['text'], $Link['extent']); + + if (preg_match('/^[ ]*{('.$this->regexAttribute.'+)}/', $remainder, $matches)) + { + $Link['element']['attributes'] += $this->parseAttributeData($matches[1]); + + $Link['extent'] += strlen($matches[0]); + } + + return $Link; + } + + # + # ~ + # + + private $currentAbreviation; + private $currentMeaning; + + protected function insertAbreviation(array $Element) + { + if (isset($Element['text'])) + { + $Element['elements'] = self::pregReplaceElements( + '/\b'.preg_quote($this->currentAbreviation, '/').'\b/', + array( + array( + 'name' => 'abbr', + 'attributes' => array( + 'title' => $this->currentMeaning, + ), + 'text' => $this->currentAbreviation, + ) + ), + $Element['text'] + ); + + unset($Element['text']); + } + + return $Element; + } + + protected function inlineText($text) + { + $Inline = parent::inlineText($text); + + if (isset($this->DefinitionData['Abbreviation'])) + { + foreach ($this->DefinitionData['Abbreviation'] as $abbreviation => $meaning) + { + $this->currentAbreviation = $abbreviation; + $this->currentMeaning = $meaning; + + $Inline['element'] = $this->elementApplyRecursiveDepthFirst( + array($this, 'insertAbreviation'), + $Inline['element'] + ); + } + } + + return $Inline; + } + + # + # Util Methods + # + + protected function addDdElement(array $Line, array $Block) + { + $text = substr($Line['text'], 1); + $text = trim($text); + + unset($Block['dd']); + + $Block['dd'] = array( + 'name' => 'dd', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $text, + 'destination' => 'elements' + ), + ); + + if (isset($Block['interrupted'])) + { + $Block['dd']['handler']['function'] = 'textElements'; + + unset($Block['interrupted']); + } + + $Block['element']['elements'] []= & $Block['dd']; + + return $Block; + } + + protected function buildFootnoteElement() + { + $Element = array( + 'name' => 'div', + 'attributes' => array('class' => 'footnotes'), + 'elements' => array( + array('name' => 'hr'), + array( + 'name' => 'ol', + 'elements' => array(), + ), + ), + ); + + uasort($this->DefinitionData['Footnote'], 'self::sortFootnotes'); + + foreach ($this->DefinitionData['Footnote'] as $definitionId => $DefinitionData) + { + if ( ! isset($DefinitionData['number'])) + { + continue; + } + + $text = $DefinitionData['text']; + + $textElements = parent::textElements($text); + + $numbers = range(1, $DefinitionData['count']); + + $backLinkElements = array(); + + foreach ($numbers as $number) + { + $backLinkElements[] = array('text' => ' '); + $backLinkElements[] = array( + 'name' => 'a', + 'attributes' => array( + 'href' => "#fnref$number:$definitionId", + 'rev' => 'footnote', + 'class' => 'footnote-backref', + ), + 'rawHtml' => '↩', + 'allowRawHtmlInSafeMode' => true, + 'autobreak' => false, + ); + } + + unset($backLinkElements[0]); + + $n = count($textElements) -1; + + if ($textElements[$n]['name'] === 'p') + { + $backLinkElements = array_merge( + array( + array( + 'rawHtml' => ' ', + 'allowRawHtmlInSafeMode' => true, + ), + ), + $backLinkElements + ); + + unset($textElements[$n]['name']); + + $textElements[$n] = array( + 'name' => 'p', + 'elements' => array_merge( + array($textElements[$n]), + $backLinkElements + ), + ); + } + else + { + $textElements[] = array( + 'name' => 'p', + 'elements' => $backLinkElements + ); + } + + $Element['elements'][1]['elements'] []= array( + 'name' => 'li', + 'attributes' => array('id' => 'fn:'.$definitionId), + 'elements' => array_merge( + $textElements + ), + ); + } + + return $Element; + } + + # ~ + + protected function parseAttributeData($attributeString) + { + $Data = array(); + + $attributes = preg_split('/[ ]+/', $attributeString, - 1, PREG_SPLIT_NO_EMPTY); + + foreach ($attributes as $attribute) + { + if ($attribute[0] === '#') + { + $Data['id'] = substr($attribute, 1); + } + else # "." + { + $classes []= substr($attribute, 1); + } + } + + if (isset($classes)) + { + $Data['class'] = implode(' ', $classes); + } + + return $Data; + } + + # ~ + + protected function processTag($elementMarkup) # recursive + { + # http://stackoverflow.com/q/1148928/200145 + libxml_use_internal_errors(true); + + $DOMDocument = new DOMDocument; + + # http://stackoverflow.com/q/11309194/200145 + $elementMarkup = mb_convert_encoding($elementMarkup, 'HTML-ENTITIES', 'UTF-8'); + + # http://stackoverflow.com/q/4879946/200145 + $DOMDocument->loadHTML($elementMarkup); + $DOMDocument->removeChild($DOMDocument->doctype); + $DOMDocument->replaceChild($DOMDocument->firstChild->firstChild->firstChild, $DOMDocument->firstChild); + + $elementText = ''; + + if ($DOMDocument->documentElement->getAttribute('markdown') === '1') + { + foreach ($DOMDocument->documentElement->childNodes as $Node) + { + $elementText .= $DOMDocument->saveHTML($Node); + } + + $DOMDocument->documentElement->removeAttribute('markdown'); + + $elementText = "\n".$this->text($elementText)."\n"; + } + else + { + foreach ($DOMDocument->documentElement->childNodes as $Node) + { + $nodeMarkup = $DOMDocument->saveHTML($Node); + + if ($Node instanceof DOMElement and ! in_array($Node->nodeName, $this->textLevelElements)) + { + $elementText .= $this->processTag($nodeMarkup); + } + else + { + $elementText .= $nodeMarkup; + } + } + } + + # because we don't want for markup to get encoded + $DOMDocument->documentElement->nodeValue = 'placeholder\x1A'; + + $markup = $DOMDocument->saveHTML($DOMDocument->documentElement); + $markup = str_replace('placeholder\x1A', $elementText, $markup); + + return $markup; + } + + # ~ + + protected function sortFootnotes($A, $B) # callback + { + return $A['number'] - $B['number']; + } + + # + # Fields + # + + protected $regexAttribute = '(?:[#.][-\w]+[ ]*)'; +} diff --git a/vendor/erusev/parsedown-extra/README.md b/vendor/erusev/parsedown-extra/README.md new file mode 100644 index 0000000..cee4b54 --- /dev/null +++ b/vendor/erusev/parsedown-extra/README.md @@ -0,0 +1,31 @@ +> You might also like [Caret](http://caret.io?ref=parsedown) - our Markdown editor for the Desktop. + +## Parsedown Extra + +[![Build Status](https://img.shields.io/travis/erusev/parsedown-extra/master.svg?style=flat-square)](https://travis-ci.org/erusev/parsedown-extra) + +An extension of [Parsedown](http://parsedown.org) that adds support for [Markdown Extra](https://michelf.ca/projects/php-markdown/extra/). + +[See Demo](http://parsedown.org/extra/) + +### Installation + +Include both `Parsedown.php` and `ParsedownExtra.php` or install [the composer package](https://packagist.org/packages/erusev/parsedown-extra). + +### Example + +``` php +$Extra = new ParsedownExtra(); + +echo $Extra->text('# Header {.sth}'); # prints:

Header

+``` + +### Questions + +**Who uses Parsedown Extra?** + +[October CMS](http://octobercms.com/), [Bolt CMS](http://bolt.cm/), [Kirby CMS](http://getkirby.com/), [Grav CMS](http://getgrav.org/), [Statamic CMS](http://www.statamic.com/) and [more](https://www.versioneye.com/php/erusev:parsedown-extra/references). + +**How can I help?** + +Use it, star it, share it and in case you feel generous, [donate some money](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=528P3NZQMP8N2). diff --git a/vendor/erusev/parsedown-extra/composer.json b/vendor/erusev/parsedown-extra/composer.json new file mode 100644 index 0000000..263ab73 --- /dev/null +++ b/vendor/erusev/parsedown-extra/composer.json @@ -0,0 +1,36 @@ +{ + "name": "erusev/parsedown-extra", + "description": "An extension of Parsedown that adds support for Markdown Extra.", + "keywords": ["markdown", "markdown extra", "parser", "parsedown"], + "homepage": "https://github.com/erusev/parsedown-extra", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "require": { + "erusev/parsedown": "^1.8.0|^1.8.0-beta-4", + "php": ">=5.3.6", + "ext-dom": "*", + "ext-mbstring": "*" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35" + }, + "autoload": { + "psr-0": {"ParsedownExtra": ""} + }, + "autoload-dev": { + "psr-0": { + "TestParsedown": "test/", + "ParsedownExtraTest": "test/", + "ParsedownTest": "vendor/erusev/parsedown/test/", + "CommonMarkTest": "vendor/erusev/parsedown/test/", + "CommonMarkTestWeak": "vendor/erusev/parsedown/test/" + } + } +} diff --git a/vendor/erusev/parsedown/LICENSE.txt b/vendor/erusev/parsedown/LICENSE.txt new file mode 100644 index 0000000..8e7c764 --- /dev/null +++ b/vendor/erusev/parsedown/LICENSE.txt @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013-2018 Emanuil Rusev, erusev.com + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/erusev/parsedown/Parsedown.php b/vendor/erusev/parsedown/Parsedown.php new file mode 100644 index 0000000..46974ff --- /dev/null +++ b/vendor/erusev/parsedown/Parsedown.php @@ -0,0 +1,1990 @@ +textElements($text); + + # convert to markup + $markup = $this->elements($Elements); + + # trim line breaks + $markup = trim($markup, "\n"); + + return $markup; + } + + protected function textElements($text) + { + # make sure no definitions are set + $this->DefinitionData = array(); + + # standardize line breaks + $text = str_replace(array("\r\n", "\r"), "\n", $text); + + # remove surrounding line breaks + $text = trim($text, "\n"); + + # split text into lines + $lines = explode("\n", $text); + + # iterate through lines to identify blocks + return $this->linesElements($lines); + } + + # + # Setters + # + + function setBreaksEnabled($breaksEnabled) + { + $this->breaksEnabled = $breaksEnabled; + + return $this; + } + + protected $breaksEnabled; + + function setMarkupEscaped($markupEscaped) + { + $this->markupEscaped = $markupEscaped; + + return $this; + } + + protected $markupEscaped; + + function setUrlsLinked($urlsLinked) + { + $this->urlsLinked = $urlsLinked; + + return $this; + } + + protected $urlsLinked = true; + + function setSafeMode($safeMode) + { + $this->safeMode = (bool) $safeMode; + + return $this; + } + + protected $safeMode; + + function setStrictMode($strictMode) + { + $this->strictMode = (bool) $strictMode; + + return $this; + } + + protected $strictMode; + + protected $safeLinksWhitelist = array( + 'http://', + 'https://', + 'ftp://', + 'ftps://', + 'mailto:', + 'data:image/png;base64,', + 'data:image/gif;base64,', + 'data:image/jpeg;base64,', + 'irc:', + 'ircs:', + 'git:', + 'ssh:', + 'news:', + 'steam:', + ); + + # + # Lines + # + + protected $BlockTypes = array( + '#' => array('Header'), + '*' => array('Rule', 'List'), + '+' => array('List'), + '-' => array('SetextHeader', 'Table', 'Rule', 'List'), + '0' => array('List'), + '1' => array('List'), + '2' => array('List'), + '3' => array('List'), + '4' => array('List'), + '5' => array('List'), + '6' => array('List'), + '7' => array('List'), + '8' => array('List'), + '9' => array('List'), + ':' => array('Table'), + '<' => array('Comment', 'Markup'), + '=' => array('SetextHeader'), + '>' => array('Quote'), + '[' => array('Reference'), + '_' => array('Rule'), + '`' => array('FencedCode'), + '|' => array('Table'), + '~' => array('FencedCode'), + ); + + # ~ + + protected $unmarkedBlockTypes = array( + 'Code', + ); + + # + # Blocks + # + + protected function lines(array $lines) + { + return $this->elements($this->linesElements($lines)); + } + + protected function linesElements(array $lines) + { + $Elements = array(); + $CurrentBlock = null; + + foreach ($lines as $line) + { + if (chop($line) === '') + { + if (isset($CurrentBlock)) + { + $CurrentBlock['interrupted'] = (isset($CurrentBlock['interrupted']) + ? $CurrentBlock['interrupted'] + 1 : 1 + ); + } + + continue; + } + + while (($beforeTab = strstr($line, "\t", true)) !== false) + { + $shortage = 4 - mb_strlen($beforeTab, 'utf-8') % 4; + + $line = $beforeTab + . str_repeat(' ', $shortage) + . substr($line, strlen($beforeTab) + 1) + ; + } + + $indent = strspn($line, ' '); + + $text = $indent > 0 ? substr($line, $indent) : $line; + + # ~ + + $Line = array('body' => $line, 'indent' => $indent, 'text' => $text); + + # ~ + + if (isset($CurrentBlock['continuable'])) + { + $methodName = 'block' . $CurrentBlock['type'] . 'Continue'; + $Block = $this->$methodName($Line, $CurrentBlock); + + if (isset($Block)) + { + $CurrentBlock = $Block; + + continue; + } + else + { + if ($this->isBlockCompletable($CurrentBlock['type'])) + { + $methodName = 'block' . $CurrentBlock['type'] . 'Complete'; + $CurrentBlock = $this->$methodName($CurrentBlock); + } + } + } + + # ~ + + $marker = $text[0]; + + # ~ + + $blockTypes = $this->unmarkedBlockTypes; + + if (isset($this->BlockTypes[$marker])) + { + foreach ($this->BlockTypes[$marker] as $blockType) + { + $blockTypes []= $blockType; + } + } + + # + # ~ + + foreach ($blockTypes as $blockType) + { + $Block = $this->{"block$blockType"}($Line, $CurrentBlock); + + if (isset($Block)) + { + $Block['type'] = $blockType; + + if ( ! isset($Block['identified'])) + { + if (isset($CurrentBlock)) + { + $Elements[] = $this->extractElement($CurrentBlock); + } + + $Block['identified'] = true; + } + + if ($this->isBlockContinuable($blockType)) + { + $Block['continuable'] = true; + } + + $CurrentBlock = $Block; + + continue 2; + } + } + + # ~ + + if (isset($CurrentBlock) and $CurrentBlock['type'] === 'Paragraph') + { + $Block = $this->paragraphContinue($Line, $CurrentBlock); + } + + if (isset($Block)) + { + $CurrentBlock = $Block; + } + else + { + if (isset($CurrentBlock)) + { + $Elements[] = $this->extractElement($CurrentBlock); + } + + $CurrentBlock = $this->paragraph($Line); + + $CurrentBlock['identified'] = true; + } + } + + # ~ + + if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type'])) + { + $methodName = 'block' . $CurrentBlock['type'] . 'Complete'; + $CurrentBlock = $this->$methodName($CurrentBlock); + } + + # ~ + + if (isset($CurrentBlock)) + { + $Elements[] = $this->extractElement($CurrentBlock); + } + + # ~ + + return $Elements; + } + + protected function extractElement(array $Component) + { + if ( ! isset($Component['element'])) + { + if (isset($Component['markup'])) + { + $Component['element'] = array('rawHtml' => $Component['markup']); + } + elseif (isset($Component['hidden'])) + { + $Component['element'] = array(); + } + } + + return $Component['element']; + } + + protected function isBlockContinuable($Type) + { + return method_exists($this, 'block' . $Type . 'Continue'); + } + + protected function isBlockCompletable($Type) + { + return method_exists($this, 'block' . $Type . 'Complete'); + } + + # + # Code + + protected function blockCode($Line, $Block = null) + { + if (isset($Block) and $Block['type'] === 'Paragraph' and ! isset($Block['interrupted'])) + { + return; + } + + if ($Line['indent'] >= 4) + { + $text = substr($Line['body'], 4); + + $Block = array( + 'element' => array( + 'name' => 'pre', + 'element' => array( + 'name' => 'code', + 'text' => $text, + ), + ), + ); + + return $Block; + } + } + + protected function blockCodeContinue($Line, $Block) + { + if ($Line['indent'] >= 4) + { + if (isset($Block['interrupted'])) + { + $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); + + unset($Block['interrupted']); + } + + $Block['element']['element']['text'] .= "\n"; + + $text = substr($Line['body'], 4); + + $Block['element']['element']['text'] .= $text; + + return $Block; + } + } + + protected function blockCodeComplete($Block) + { + return $Block; + } + + # + # Comment + + protected function blockComment($Line) + { + if ($this->markupEscaped or $this->safeMode) + { + return; + } + + if (strpos($Line['text'], '') !== false) + { + $Block['closed'] = true; + } + + return $Block; + } + } + + protected function blockCommentContinue($Line, array $Block) + { + if (isset($Block['closed'])) + { + return; + } + + $Block['element']['rawHtml'] .= "\n" . $Line['body']; + + if (strpos($Line['text'], '-->') !== false) + { + $Block['closed'] = true; + } + + return $Block; + } + + # + # Fenced Code + + protected function blockFencedCode($Line) + { + $marker = $Line['text'][0]; + + $openerLength = strspn($Line['text'], $marker); + + if ($openerLength < 3) + { + return; + } + + $infostring = trim(substr($Line['text'], $openerLength), "\t "); + + if (strpos($infostring, '`') !== false) + { + return; + } + + $Element = array( + 'name' => 'code', + 'text' => '', + ); + + if ($infostring !== '') + { + /** + * https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes + * Every HTML element may have a class attribute specified. + * The attribute, if specified, must have a value that is a set + * of space-separated tokens representing the various classes + * that the element belongs to. + * [...] + * The space characters, for the purposes of this specification, + * are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab), + * U+000A LINE FEED (LF), U+000C FORM FEED (FF), and + * U+000D CARRIAGE RETURN (CR). + */ + $language = substr($infostring, 0, strcspn($infostring, " \t\n\f\r")); + + $Element['attributes'] = array('class' => "language-$language"); + } + + $Block = array( + 'char' => $marker, + 'openerLength' => $openerLength, + 'element' => array( + 'name' => 'pre', + 'element' => $Element, + ), + ); + + return $Block; + } + + protected function blockFencedCodeContinue($Line, $Block) + { + if (isset($Block['complete'])) + { + return; + } + + if (isset($Block['interrupted'])) + { + $Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']); + + unset($Block['interrupted']); + } + + if (($len = strspn($Line['text'], $Block['char'])) >= $Block['openerLength'] + and chop(substr($Line['text'], $len), ' ') === '' + ) { + $Block['element']['element']['text'] = substr($Block['element']['element']['text'], 1); + + $Block['complete'] = true; + + return $Block; + } + + $Block['element']['element']['text'] .= "\n" . $Line['body']; + + return $Block; + } + + protected function blockFencedCodeComplete($Block) + { + return $Block; + } + + # + # Header + + protected function blockHeader($Line) + { + $level = strspn($Line['text'], '#'); + + if ($level > 6) + { + return; + } + + $text = trim($Line['text'], '#'); + + if ($this->strictMode and isset($text[0]) and $text[0] !== ' ') + { + return; + } + + $text = trim($text, ' '); + + $Block = array( + 'element' => array( + 'name' => 'h' . min(6, $level), + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $text, + 'destination' => 'elements', + ) + ), + ); + + return $Block; + } + + # + # List + + protected function blockList($Line, array $CurrentBlock = null) + { + list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]{1,9}+[.\)]'); + + if (preg_match('/^('.$pattern.'([ ]++|$))(.*+)/', $Line['text'], $matches)) + { + $contentIndent = strlen($matches[2]); + + if ($contentIndent >= 5) + { + $contentIndent -= 1; + $matches[1] = substr($matches[1], 0, -$contentIndent); + $matches[3] = str_repeat(' ', $contentIndent) . $matches[3]; + } + elseif ($contentIndent === 0) + { + $matches[1] .= ' '; + } + + $markerWithoutWhitespace = strstr($matches[1], ' ', true); + + $Block = array( + 'indent' => $Line['indent'], + 'pattern' => $pattern, + 'data' => array( + 'type' => $name, + 'marker' => $matches[1], + 'markerType' => ($name === 'ul' ? $markerWithoutWhitespace : substr($markerWithoutWhitespace, -1)), + ), + 'element' => array( + 'name' => $name, + 'elements' => array(), + ), + ); + $Block['data']['markerTypeRegex'] = preg_quote($Block['data']['markerType'], '/'); + + if ($name === 'ol') + { + $listStart = ltrim(strstr($matches[1], $Block['data']['markerType'], true), '0') ?: '0'; + + if ($listStart !== '1') + { + if ( + isset($CurrentBlock) + and $CurrentBlock['type'] === 'Paragraph' + and ! isset($CurrentBlock['interrupted']) + ) { + return; + } + + $Block['element']['attributes'] = array('start' => $listStart); + } + } + + $Block['li'] = array( + 'name' => 'li', + 'handler' => array( + 'function' => 'li', + 'argument' => !empty($matches[3]) ? array($matches[3]) : array(), + 'destination' => 'elements' + ) + ); + + $Block['element']['elements'] []= & $Block['li']; + + return $Block; + } + } + + protected function blockListContinue($Line, array $Block) + { + if (isset($Block['interrupted']) and empty($Block['li']['handler']['argument'])) + { + return null; + } + + $requiredIndent = ($Block['indent'] + strlen($Block['data']['marker'])); + + if ($Line['indent'] < $requiredIndent + and ( + ( + $Block['data']['type'] === 'ol' + and preg_match('/^[0-9]++'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches) + ) or ( + $Block['data']['type'] === 'ul' + and preg_match('/^'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches) + ) + ) + ) { + if (isset($Block['interrupted'])) + { + $Block['li']['handler']['argument'] []= ''; + + $Block['loose'] = true; + + unset($Block['interrupted']); + } + + unset($Block['li']); + + $text = isset($matches[1]) ? $matches[1] : ''; + + $Block['indent'] = $Line['indent']; + + $Block['li'] = array( + 'name' => 'li', + 'handler' => array( + 'function' => 'li', + 'argument' => array($text), + 'destination' => 'elements' + ) + ); + + $Block['element']['elements'] []= & $Block['li']; + + return $Block; + } + elseif ($Line['indent'] < $requiredIndent and $this->blockList($Line)) + { + return null; + } + + if ($Line['text'][0] === '[' and $this->blockReference($Line)) + { + return $Block; + } + + if ($Line['indent'] >= $requiredIndent) + { + if (isset($Block['interrupted'])) + { + $Block['li']['handler']['argument'] []= ''; + + $Block['loose'] = true; + + unset($Block['interrupted']); + } + + $text = substr($Line['body'], $requiredIndent); + + $Block['li']['handler']['argument'] []= $text; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $text = preg_replace('/^[ ]{0,'.$requiredIndent.'}+/', '', $Line['body']); + + $Block['li']['handler']['argument'] []= $text; + + return $Block; + } + } + + protected function blockListComplete(array $Block) + { + if (isset($Block['loose'])) + { + foreach ($Block['element']['elements'] as &$li) + { + if (end($li['handler']['argument']) !== '') + { + $li['handler']['argument'] []= ''; + } + } + } + + return $Block; + } + + # + # Quote + + protected function blockQuote($Line) + { + if (preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches)) + { + $Block = array( + 'element' => array( + 'name' => 'blockquote', + 'handler' => array( + 'function' => 'linesElements', + 'argument' => (array) $matches[1], + 'destination' => 'elements', + ) + ), + ); + + return $Block; + } + } + + protected function blockQuoteContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + if ($Line['text'][0] === '>' and preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches)) + { + $Block['element']['handler']['argument'] []= $matches[1]; + + return $Block; + } + + if ( ! isset($Block['interrupted'])) + { + $Block['element']['handler']['argument'] []= $Line['text']; + + return $Block; + } + } + + # + # Rule + + protected function blockRule($Line) + { + $marker = $Line['text'][0]; + + if (substr_count($Line['text'], $marker) >= 3 and chop($Line['text'], " $marker") === '') + { + $Block = array( + 'element' => array( + 'name' => 'hr', + ), + ); + + return $Block; + } + } + + # + # Setext + + protected function blockSetextHeader($Line, array $Block = null) + { + if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) + { + return; + } + + if ($Line['indent'] < 4 and chop(chop($Line['text'], ' '), $Line['text'][0]) === '') + { + $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2'; + + return $Block; + } + } + + # + # Markup + + protected function blockMarkup($Line) + { + if ($this->markupEscaped or $this->safeMode) + { + return; + } + + if (preg_match('/^<[\/]?+(\w*)(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+(\/)?>/', $Line['text'], $matches)) + { + $element = strtolower($matches[1]); + + if (in_array($element, $this->textLevelElements)) + { + return; + } + + $Block = array( + 'name' => $matches[1], + 'element' => array( + 'rawHtml' => $Line['text'], + 'autobreak' => true, + ), + ); + + return $Block; + } + } + + protected function blockMarkupContinue($Line, array $Block) + { + if (isset($Block['closed']) or isset($Block['interrupted'])) + { + return; + } + + $Block['element']['rawHtml'] .= "\n" . $Line['body']; + + return $Block; + } + + # + # Reference + + protected function blockReference($Line) + { + if (strpos($Line['text'], ']') !== false + and preg_match('/^\[(.+?)\]:[ ]*+?(?:[ ]+["\'(](.+)["\')])?[ ]*+$/', $Line['text'], $matches) + ) { + $id = strtolower($matches[1]); + + $Data = array( + 'url' => $matches[2], + 'title' => isset($matches[3]) ? $matches[3] : null, + ); + + $this->DefinitionData['Reference'][$id] = $Data; + + $Block = array( + 'element' => array(), + ); + + return $Block; + } + } + + # + # Table + + protected function blockTable($Line, array $Block = null) + { + if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted'])) + { + return; + } + + if ( + strpos($Block['element']['handler']['argument'], '|') === false + and strpos($Line['text'], '|') === false + and strpos($Line['text'], ':') === false + or strpos($Block['element']['handler']['argument'], "\n") !== false + ) { + return; + } + + if (chop($Line['text'], ' -:|') !== '') + { + return; + } + + $alignments = array(); + + $divider = $Line['text']; + + $divider = trim($divider); + $divider = trim($divider, '|'); + + $dividerCells = explode('|', $divider); + + foreach ($dividerCells as $dividerCell) + { + $dividerCell = trim($dividerCell); + + if ($dividerCell === '') + { + return; + } + + $alignment = null; + + if ($dividerCell[0] === ':') + { + $alignment = 'left'; + } + + if (substr($dividerCell, - 1) === ':') + { + $alignment = $alignment === 'left' ? 'center' : 'right'; + } + + $alignments []= $alignment; + } + + # ~ + + $HeaderElements = array(); + + $header = $Block['element']['handler']['argument']; + + $header = trim($header); + $header = trim($header, '|'); + + $headerCells = explode('|', $header); + + if (count($headerCells) !== count($alignments)) + { + return; + } + + foreach ($headerCells as $index => $headerCell) + { + $headerCell = trim($headerCell); + + $HeaderElement = array( + 'name' => 'th', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $headerCell, + 'destination' => 'elements', + ) + ); + + if (isset($alignments[$index])) + { + $alignment = $alignments[$index]; + + $HeaderElement['attributes'] = array( + 'style' => "text-align: $alignment;", + ); + } + + $HeaderElements []= $HeaderElement; + } + + # ~ + + $Block = array( + 'alignments' => $alignments, + 'identified' => true, + 'element' => array( + 'name' => 'table', + 'elements' => array(), + ), + ); + + $Block['element']['elements'] []= array( + 'name' => 'thead', + ); + + $Block['element']['elements'] []= array( + 'name' => 'tbody', + 'elements' => array(), + ); + + $Block['element']['elements'][0]['elements'] []= array( + 'name' => 'tr', + 'elements' => $HeaderElements, + ); + + return $Block; + } + + protected function blockTableContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + if (count($Block['alignments']) === 1 or $Line['text'][0] === '|' or strpos($Line['text'], '|')) + { + $Elements = array(); + + $row = $Line['text']; + + $row = trim($row); + $row = trim($row, '|'); + + preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]++`|`)++/', $row, $matches); + + $cells = array_slice($matches[0], 0, count($Block['alignments'])); + + foreach ($cells as $index => $cell) + { + $cell = trim($cell); + + $Element = array( + 'name' => 'td', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $cell, + 'destination' => 'elements', + ) + ); + + if (isset($Block['alignments'][$index])) + { + $Element['attributes'] = array( + 'style' => 'text-align: ' . $Block['alignments'][$index] . ';', + ); + } + + $Elements []= $Element; + } + + $Element = array( + 'name' => 'tr', + 'elements' => $Elements, + ); + + $Block['element']['elements'][1]['elements'] []= $Element; + + return $Block; + } + } + + # + # ~ + # + + protected function paragraph($Line) + { + return array( + 'type' => 'Paragraph', + 'element' => array( + 'name' => 'p', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $Line['text'], + 'destination' => 'elements', + ), + ), + ); + } + + protected function paragraphContinue($Line, array $Block) + { + if (isset($Block['interrupted'])) + { + return; + } + + $Block['element']['handler']['argument'] .= "\n".$Line['text']; + + return $Block; + } + + # + # Inline Elements + # + + protected $InlineTypes = array( + '!' => array('Image'), + '&' => array('SpecialCharacter'), + '*' => array('Emphasis'), + ':' => array('Url'), + '<' => array('UrlTag', 'EmailTag', 'Markup'), + '[' => array('Link'), + '_' => array('Emphasis'), + '`' => array('Code'), + '~' => array('Strikethrough'), + '\\' => array('EscapeSequence'), + ); + + # ~ + + protected $inlineMarkerList = '!*_&[:<`~\\'; + + # + # ~ + # + + public function line($text, $nonNestables = array()) + { + return $this->elements($this->lineElements($text, $nonNestables)); + } + + protected function lineElements($text, $nonNestables = array()) + { + $Elements = array(); + + $nonNestables = (empty($nonNestables) + ? array() + : array_combine($nonNestables, $nonNestables) + ); + + # $excerpt is based on the first occurrence of a marker + + while ($excerpt = strpbrk($text, $this->inlineMarkerList)) + { + $marker = $excerpt[0]; + + $markerPosition = strlen($text) - strlen($excerpt); + + $Excerpt = array('text' => $excerpt, 'context' => $text); + + foreach ($this->InlineTypes[$marker] as $inlineType) + { + # check to see if the current inline type is nestable in the current context + + if (isset($nonNestables[$inlineType])) + { + continue; + } + + $Inline = $this->{"inline$inlineType"}($Excerpt); + + if ( ! isset($Inline)) + { + continue; + } + + # makes sure that the inline belongs to "our" marker + + if (isset($Inline['position']) and $Inline['position'] > $markerPosition) + { + continue; + } + + # sets a default inline position + + if ( ! isset($Inline['position'])) + { + $Inline['position'] = $markerPosition; + } + + # cause the new element to 'inherit' our non nestables + + + $Inline['element']['nonNestables'] = isset($Inline['element']['nonNestables']) + ? array_merge($Inline['element']['nonNestables'], $nonNestables) + : $nonNestables + ; + + # the text that comes before the inline + $unmarkedText = substr($text, 0, $Inline['position']); + + # compile the unmarked text + $InlineText = $this->inlineText($unmarkedText); + $Elements[] = $InlineText['element']; + + # compile the inline + $Elements[] = $this->extractElement($Inline); + + # remove the examined text + $text = substr($text, $Inline['position'] + $Inline['extent']); + + continue 2; + } + + # the marker does not belong to an inline + + $unmarkedText = substr($text, 0, $markerPosition + 1); + + $InlineText = $this->inlineText($unmarkedText); + $Elements[] = $InlineText['element']; + + $text = substr($text, $markerPosition + 1); + } + + $InlineText = $this->inlineText($text); + $Elements[] = $InlineText['element']; + + foreach ($Elements as &$Element) + { + if ( ! isset($Element['autobreak'])) + { + $Element['autobreak'] = false; + } + } + + return $Elements; + } + + # + # ~ + # + + protected function inlineText($text) + { + $Inline = array( + 'extent' => strlen($text), + 'element' => array(), + ); + + $Inline['element']['elements'] = self::pregReplaceElements( + $this->breaksEnabled ? '/[ ]*+\n/' : '/(?:[ ]*+\\\\|[ ]{2,}+)\n/', + array( + array('name' => 'br'), + array('text' => "\n"), + ), + $text + ); + + return $Inline; + } + + protected function inlineCode($Excerpt) + { + $marker = $Excerpt['text'][0]; + + if (preg_match('/^(['.$marker.']++)[ ]*+(.+?)[ ]*+(? strlen($matches[0]), + 'element' => array( + 'name' => 'code', + 'text' => $text, + ), + ); + } + } + + protected function inlineEmailTag($Excerpt) + { + $hostnameLabel = '[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?'; + + $commonMarkEmail = '[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]++@' + . $hostnameLabel . '(?:\.' . $hostnameLabel . ')*'; + + if (strpos($Excerpt['text'], '>') !== false + and preg_match("/^<((mailto:)?$commonMarkEmail)>/i", $Excerpt['text'], $matches) + ){ + $url = $matches[1]; + + if ( ! isset($matches[2])) + { + $url = "mailto:$url"; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $matches[1], + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + protected function inlineEmphasis($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + $marker = $Excerpt['text'][0]; + + if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'strong'; + } + elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches)) + { + $emphasis = 'em'; + } + else + { + return; + } + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => $emphasis, + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $matches[1], + 'destination' => 'elements', + ) + ), + ); + } + + protected function inlineEscapeSequence($Excerpt) + { + if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters)) + { + return array( + 'element' => array('rawHtml' => $Excerpt['text'][1]), + 'extent' => 2, + ); + } + } + + protected function inlineImage($Excerpt) + { + if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[') + { + return; + } + + $Excerpt['text']= substr($Excerpt['text'], 1); + + $Link = $this->inlineLink($Excerpt); + + if ($Link === null) + { + return; + } + + $Inline = array( + 'extent' => $Link['extent'] + 1, + 'element' => array( + 'name' => 'img', + 'attributes' => array( + 'src' => $Link['element']['attributes']['href'], + 'alt' => $Link['element']['handler']['argument'], + ), + 'autobreak' => true, + ), + ); + + $Inline['element']['attributes'] += $Link['element']['attributes']; + + unset($Inline['element']['attributes']['href']); + + return $Inline; + } + + protected function inlineLink($Excerpt) + { + $Element = array( + 'name' => 'a', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => null, + 'destination' => 'elements', + ), + 'nonNestables' => array('Url', 'Link'), + 'attributes' => array( + 'href' => null, + 'title' => null, + ), + ); + + $extent = 0; + + $remainder = $Excerpt['text']; + + if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches)) + { + $Element['handler']['argument'] = $matches[1]; + + $extent += strlen($matches[0]); + + $remainder = substr($remainder, $extent); + } + else + { + return; + } + + if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*+"|\'[^\']*+\'))?\s*+[)]/', $remainder, $matches)) + { + $Element['attributes']['href'] = $matches[1]; + + if (isset($matches[2])) + { + $Element['attributes']['title'] = substr($matches[2], 1, - 1); + } + + $extent += strlen($matches[0]); + } + else + { + if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches)) + { + $definition = strlen($matches[1]) ? $matches[1] : $Element['handler']['argument']; + $definition = strtolower($definition); + + $extent += strlen($matches[0]); + } + else + { + $definition = strtolower($Element['handler']['argument']); + } + + if ( ! isset($this->DefinitionData['Reference'][$definition])) + { + return; + } + + $Definition = $this->DefinitionData['Reference'][$definition]; + + $Element['attributes']['href'] = $Definition['url']; + $Element['attributes']['title'] = $Definition['title']; + } + + return array( + 'extent' => $extent, + 'element' => $Element, + ); + } + + protected function inlineMarkup($Excerpt) + { + if ($this->markupEscaped or $this->safeMode or strpos($Excerpt['text'], '>') === false) + { + return; + } + + if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w[\w-]*+[ ]*+>/s', $Excerpt['text'], $matches)) + { + return array( + 'element' => array('rawHtml' => $matches[0]), + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] === '!' and preg_match('/^/s', $Excerpt['text'], $matches)) + { + return array( + 'element' => array('rawHtml' => $matches[0]), + 'extent' => strlen($matches[0]), + ); + } + + if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w[\w-]*+(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+\/?>/s', $Excerpt['text'], $matches)) + { + return array( + 'element' => array('rawHtml' => $matches[0]), + 'extent' => strlen($matches[0]), + ); + } + } + + protected function inlineSpecialCharacter($Excerpt) + { + if ($Excerpt['text'][1] !== ' ' and strpos($Excerpt['text'], ';') !== false + and preg_match('/^&(#?+[0-9a-zA-Z]++);/', $Excerpt['text'], $matches) + ) { + return array( + 'element' => array('rawHtml' => '&' . $matches[1] . ';'), + 'extent' => strlen($matches[0]), + ); + } + + return; + } + + protected function inlineStrikethrough($Excerpt) + { + if ( ! isset($Excerpt['text'][1])) + { + return; + } + + if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches)) + { + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'del', + 'handler' => array( + 'function' => 'lineElements', + 'argument' => $matches[1], + 'destination' => 'elements', + ) + ), + ); + } + } + + protected function inlineUrl($Excerpt) + { + if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/') + { + return; + } + + if (strpos($Excerpt['context'], 'http') !== false + and preg_match('/\bhttps?+:[\/]{2}[^\s<]+\b\/*+/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE) + ) { + $url = $matches[0][0]; + + $Inline = array( + 'extent' => strlen($matches[0][0]), + 'position' => $matches[0][1], + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + + return $Inline; + } + } + + protected function inlineUrlTag($Excerpt) + { + if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w++:\/{2}[^ >]++)>/i', $Excerpt['text'], $matches)) + { + $url = $matches[1]; + + return array( + 'extent' => strlen($matches[0]), + 'element' => array( + 'name' => 'a', + 'text' => $url, + 'attributes' => array( + 'href' => $url, + ), + ), + ); + } + } + + # ~ + + protected function unmarkedText($text) + { + $Inline = $this->inlineText($text); + return $this->element($Inline['element']); + } + + # + # Handlers + # + + protected function handle(array $Element) + { + if (isset($Element['handler'])) + { + if (!isset($Element['nonNestables'])) + { + $Element['nonNestables'] = array(); + } + + if (is_string($Element['handler'])) + { + $function = $Element['handler']; + $argument = $Element['text']; + unset($Element['text']); + $destination = 'rawHtml'; + } + else + { + $function = $Element['handler']['function']; + $argument = $Element['handler']['argument']; + $destination = $Element['handler']['destination']; + } + + $Element[$destination] = $this->{$function}($argument, $Element['nonNestables']); + + if ($destination === 'handler') + { + $Element = $this->handle($Element); + } + + unset($Element['handler']); + } + + return $Element; + } + + protected function handleElementRecursive(array $Element) + { + return $this->elementApplyRecursive(array($this, 'handle'), $Element); + } + + protected function handleElementsRecursive(array $Elements) + { + return $this->elementsApplyRecursive(array($this, 'handle'), $Elements); + } + + protected function elementApplyRecursive($closure, array $Element) + { + $Element = call_user_func($closure, $Element); + + if (isset($Element['elements'])) + { + $Element['elements'] = $this->elementsApplyRecursive($closure, $Element['elements']); + } + elseif (isset($Element['element'])) + { + $Element['element'] = $this->elementApplyRecursive($closure, $Element['element']); + } + + return $Element; + } + + protected function elementApplyRecursiveDepthFirst($closure, array $Element) + { + if (isset($Element['elements'])) + { + $Element['elements'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['elements']); + } + elseif (isset($Element['element'])) + { + $Element['element'] = $this->elementsApplyRecursiveDepthFirst($closure, $Element['element']); + } + + $Element = call_user_func($closure, $Element); + + return $Element; + } + + protected function elementsApplyRecursive($closure, array $Elements) + { + foreach ($Elements as &$Element) + { + $Element = $this->elementApplyRecursive($closure, $Element); + } + + return $Elements; + } + + protected function elementsApplyRecursiveDepthFirst($closure, array $Elements) + { + foreach ($Elements as &$Element) + { + $Element = $this->elementApplyRecursiveDepthFirst($closure, $Element); + } + + return $Elements; + } + + protected function element(array $Element) + { + if ($this->safeMode) + { + $Element = $this->sanitiseElement($Element); + } + + # identity map if element has no handler + $Element = $this->handle($Element); + + $hasName = isset($Element['name']); + + $markup = ''; + + if ($hasName) + { + $markup .= '<' . $Element['name']; + + if (isset($Element['attributes'])) + { + foreach ($Element['attributes'] as $name => $value) + { + if ($value === null) + { + continue; + } + + $markup .= " $name=\"".self::escape($value).'"'; + } + } + } + + $permitRawHtml = false; + + if (isset($Element['text'])) + { + $text = $Element['text']; + } + // very strongly consider an alternative if you're writing an + // extension + elseif (isset($Element['rawHtml'])) + { + $text = $Element['rawHtml']; + + $allowRawHtmlInSafeMode = isset($Element['allowRawHtmlInSafeMode']) && $Element['allowRawHtmlInSafeMode']; + $permitRawHtml = !$this->safeMode || $allowRawHtmlInSafeMode; + } + + $hasContent = isset($text) || isset($Element['element']) || isset($Element['elements']); + + if ($hasContent) + { + $markup .= $hasName ? '>' : ''; + + if (isset($Element['elements'])) + { + $markup .= $this->elements($Element['elements']); + } + elseif (isset($Element['element'])) + { + $markup .= $this->element($Element['element']); + } + else + { + if (!$permitRawHtml) + { + $markup .= self::escape($text, true); + } + else + { + $markup .= $text; + } + } + + $markup .= $hasName ? '' : ''; + } + elseif ($hasName) + { + $markup .= ' />'; + } + + return $markup; + } + + protected function elements(array $Elements) + { + $markup = ''; + + $autoBreak = true; + + foreach ($Elements as $Element) + { + if (empty($Element)) + { + continue; + } + + $autoBreakNext = (isset($Element['autobreak']) + ? $Element['autobreak'] : isset($Element['name']) + ); + // (autobreak === false) covers both sides of an element + $autoBreak = !$autoBreak ? $autoBreak : $autoBreakNext; + + $markup .= ($autoBreak ? "\n" : '') . $this->element($Element); + $autoBreak = $autoBreakNext; + } + + $markup .= $autoBreak ? "\n" : ''; + + return $markup; + } + + # ~ + + protected function li($lines) + { + $Elements = $this->linesElements($lines); + + if ( ! in_array('', $lines) + and isset($Elements[0]) and isset($Elements[0]['name']) + and $Elements[0]['name'] === 'p' + ) { + unset($Elements[0]['name']); + } + + return $Elements; + } + + # + # AST Convenience + # + + /** + * Replace occurrences $regexp with $Elements in $text. Return an array of + * elements representing the replacement. + */ + protected static function pregReplaceElements($regexp, $Elements, $text) + { + $newElements = array(); + + while (preg_match($regexp, $text, $matches, PREG_OFFSET_CAPTURE)) + { + $offset = $matches[0][1]; + $before = substr($text, 0, $offset); + $after = substr($text, $offset + strlen($matches[0][0])); + + $newElements[] = array('text' => $before); + + foreach ($Elements as $Element) + { + $newElements[] = $Element; + } + + $text = $after; + } + + $newElements[] = array('text' => $text); + + return $newElements; + } + + # + # Deprecated Methods + # + + function parse($text) + { + $markup = $this->text($text); + + return $markup; + } + + protected function sanitiseElement(array $Element) + { + static $goodAttribute = '/^[a-zA-Z0-9][a-zA-Z0-9-_]*+$/'; + static $safeUrlNameToAtt = array( + 'a' => 'href', + 'img' => 'src', + ); + + if ( ! isset($Element['name'])) + { + unset($Element['attributes']); + return $Element; + } + + if (isset($safeUrlNameToAtt[$Element['name']])) + { + $Element = $this->filterUnsafeUrlInAttribute($Element, $safeUrlNameToAtt[$Element['name']]); + } + + if ( ! empty($Element['attributes'])) + { + foreach ($Element['attributes'] as $att => $val) + { + # filter out badly parsed attribute + if ( ! preg_match($goodAttribute, $att)) + { + unset($Element['attributes'][$att]); + } + # dump onevent attribute + elseif (self::striAtStart($att, 'on')) + { + unset($Element['attributes'][$att]); + } + } + } + + return $Element; + } + + protected function filterUnsafeUrlInAttribute(array $Element, $attribute) + { + foreach ($this->safeLinksWhitelist as $scheme) + { + if (self::striAtStart($Element['attributes'][$attribute], $scheme)) + { + return $Element; + } + } + + $Element['attributes'][$attribute] = str_replace(':', '%3A', $Element['attributes'][$attribute]); + + return $Element; + } + + # + # Static Methods + # + + protected static function escape($text, $allowQuotes = false) + { + return htmlspecialchars($text, $allowQuotes ? ENT_NOQUOTES : ENT_QUOTES, 'UTF-8'); + } + + protected static function striAtStart($string, $needle) + { + $len = strlen($needle); + + if ($len > strlen($string)) + { + return false; + } + else + { + return strtolower(substr($string, 0, $len)) === strtolower($needle); + } + } + + static function instance($name = 'default') + { + if (isset(self::$instances[$name])) + { + return self::$instances[$name]; + } + + $instance = new static(); + + self::$instances[$name] = $instance; + + return $instance; + } + + private static $instances = array(); + + # + # Fields + # + + protected $DefinitionData; + + # + # Read-Only + + protected $specialCharacters = array( + '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|', '~' + ); + + protected $StrongRegex = array( + '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*+[*])+?)[*]{2}(?![*])/s', + '_' => '/^__((?:\\\\_|[^_]|_[^_]*+_)+?)__(?!_)/us', + ); + + protected $EmRegex = array( + '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s', + '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us', + ); + + protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*+(?:\s*+=\s*+(?:[^"\'=<>`\s]+|"[^"]*+"|\'[^\']*+\'))?+'; + + protected $voidElements = array( + 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', + ); + + protected $textLevelElements = array( + 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont', + 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing', + 'i', 'rp', 'del', 'code', 'strike', 'marquee', + 'q', 'rt', 'ins', 'font', 'strong', + 's', 'tt', 'kbd', 'mark', + 'u', 'xm', 'sub', 'nobr', + 'sup', 'ruby', + 'var', 'span', + 'wbr', 'time', + ); +} diff --git a/vendor/erusev/parsedown/README.md b/vendor/erusev/parsedown/README.md new file mode 100644 index 0000000..cdf0167 --- /dev/null +++ b/vendor/erusev/parsedown/README.md @@ -0,0 +1,97 @@ +> I also make [Caret](https://caret.io?ref=parsedown) - a Markdown editor for Mac and PC. + +## Parsedown + +[![Build Status](https://img.shields.io/travis/erusev/parsedown/master.svg?style=flat-square)](https://travis-ci.org/erusev/parsedown) + + +Better Markdown Parser in PHP + +[Demo](http://parsedown.org/demo) | +[Benchmarks](http://parsedown.org/speed) | +[Tests](http://parsedown.org/tests/) | +[Documentation](https://github.com/erusev/parsedown/wiki/) + +### Features + +* One File +* No Dependencies +* Super Fast +* Extensible +* [GitHub flavored](https://help.github.com/articles/github-flavored-markdown) +* Tested in 5.3 to 7.2 and in HHVM +* [Markdown Extra extension](https://github.com/erusev/parsedown-extra) + +### Installation +#### Composer +Install the [composer package] by running the following command: + + composer require erusev/parsedown + +#### Manual +1. Download the "Source code" from the [latest release] +2. Include `Parsedown.php` + +[composer package]: https://packagist.org/packages/erusev/parsedown "The Parsedown package on packagist.org" +[latest release]: https://github.com/erusev/parsedown/releases/latest "The latest release of Parsedown" + +### Example + +``` php +$Parsedown = new Parsedown(); + +echo $Parsedown->text('Hello _Parsedown_!'); # prints:

Hello Parsedown!

+// you can also parse inline markdown only +echo $Parsedown->line('Hello _Parsedown_!'); # prints: Hello Parsedown! +``` + +More examples in [the wiki](https://github.com/erusev/parsedown/wiki/) and in [this video tutorial](http://youtu.be/wYZBY8DEikI). + +### Security + +Parsedown is capable of escaping user-input within the HTML that it generates. Additionally Parsedown will apply sanitisation to additional scripting vectors (such as scripting link destinations) that are introduced by the markdown syntax itself. + +To tell Parsedown that it is processing untrusted user-input, use the following: +```php +$parsedown = new Parsedown; +$parsedown->setSafeMode(true); +``` + +If instead, you wish to allow HTML within untrusted user-input, but still want output to be free from XSS it is recommended that you make use of a HTML sanitiser that allows HTML tags to be whitelisted, like [HTML Purifier](http://htmlpurifier.org/). + +In both cases you should strongly consider employing defence-in-depth measures, like [deploying a Content-Security-Policy](https://scotthelme.co.uk/content-security-policy-an-introduction/) (a browser security feature) so that your page is likely to be safe even if an attacker finds a vulnerability in one of the first lines of defence above. + +#### Security of Parsedown Extensions + +Safe mode does not necessarily yield safe results when using extensions to Parsedown. Extensions should be evaluated on their own to determine their specific safety against XSS. + +### Escaping HTML +> ⚠️  **WARNING:** This method isn't safe from XSS! + +If you wish to escape HTML **in trusted input**, you can use the following: +```php +$parsedown = new Parsedown; +$parsedown->setMarkupEscaped(true); +``` + +Beware that this still allows users to insert unsafe scripting vectors, such as links like `[xss](javascript:alert%281%29)`. + +### Questions + +**How does Parsedown work?** + +It tries to read Markdown like a human. First, it looks at the lines. It’s interested in how the lines start. This helps it recognise blocks. It knows, for example, that if a line starts with a `-` then perhaps it belongs to a list. Once it recognises the blocks, it continues to the content. As it reads, it watches out for special characters. This helps it recognise inline elements (or inlines). + +We call this approach "line based". We believe that Parsedown is the first Markdown parser to use it. Since the release of Parsedown, other developers have used the same approach to develop other Markdown parsers in PHP and in other languages. + +**Is it compliant with CommonMark?** + +It passes most of the CommonMark tests. Most of the tests that don't pass deal with cases that are quite uncommon. Still, as CommonMark matures, compliance should improve. + +**Who uses it?** + +[Laravel Framework](https://laravel.com/), [Bolt CMS](http://bolt.cm/), [Grav CMS](http://getgrav.org/), [Herbie CMS](http://www.getherbie.org/), [Kirby CMS](http://getkirby.com/), [October CMS](http://octobercms.com/), [Pico CMS](http://picocms.org), [Statamic CMS](http://www.statamic.com/), [phpDocumentor](http://www.phpdoc.org/), [RaspberryPi.org](http://www.raspberrypi.org/), [Symfony demo](https://github.com/symfony/symfony-demo) and [more](https://packagist.org/packages/erusev/parsedown/dependents). + +**How can I help?** + +Use it, star it, share it and if you feel generous, [donate](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=528P3NZQMP8N2). diff --git a/vendor/erusev/parsedown/composer.json b/vendor/erusev/parsedown/composer.json new file mode 100644 index 0000000..f8b40f8 --- /dev/null +++ b/vendor/erusev/parsedown/composer.json @@ -0,0 +1,33 @@ +{ + "name": "erusev/parsedown", + "description": "Parser for Markdown.", + "keywords": ["markdown", "parser"], + "homepage": "http://parsedown.org", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Emanuil Rusev", + "email": "hello@erusev.com", + "homepage": "http://erusev.com" + } + ], + "require": { + "php": ">=5.3.0", + "ext-mbstring": "*" + }, + "require-dev": { + "phpunit/phpunit": "^4.8.35" + }, + "autoload": { + "psr-0": {"Parsedown": ""} + }, + "autoload-dev": { + "psr-0": { + "TestParsedown": "test/", + "ParsedownTest": "test/", + "CommonMarkTest": "test/", + "CommonMarkTestWeak": "test/" + } + } +} diff --git a/vendor/pico-plugin.php b/vendor/pico-plugin.php new file mode 100644 index 0000000..c98adae --- /dev/null +++ b/vendor/pico-plugin.php @@ -0,0 +1,12 @@ + array( + 'installerName' => 'PicoDeprecated', + 'classNames' => array( + 'PicoDeprecated', + ), + ), +); diff --git a/vendor/picocms/composer-installer/.gitignore b/vendor/picocms/composer-installer/.gitignore new file mode 100644 index 0000000..768fc06 --- /dev/null +++ b/vendor/picocms/composer-installer/.gitignore @@ -0,0 +1,16 @@ +# Linux +*~ +*.swp + +# Windows +Thumbs.db +desktop.ini + +# Mac OS X +.DS_Store +._* + +# Composer +/composer.lock +/composer.phar +/vendor diff --git a/vendor/picocms/composer-installer/CHANGELOG.md b/vendor/picocms/composer-installer/CHANGELOG.md new file mode 100644 index 0000000..b1e2311 --- /dev/null +++ b/vendor/picocms/composer-installer/CHANGELOG.md @@ -0,0 +1,25 @@ +Pico Composer Installer Changelog +================================= + +**Note:** This changelog only provides technical information about the changes + introduced with a particular version, and is meant to supplement the + actual code changes. The information in this changelog are often + insufficient to understand the implications of larger changes. Please + refer to both the UPGRADE and NEWS sections of the docs for more + details. + +### Version 1.0.1 +Released: 2019-11-24 + +``` +* [Changed] Code cleanup +* [Changed] Remove unused code +* [Changed] Improve PHPDoc class docs +``` + +### Version 1.0.0 +Released: 2017-10-13 + +``` +* Initial release +``` diff --git a/vendor/picocms/composer-installer/LICENSE b/vendor/picocms/composer-installer/LICENSE new file mode 100644 index 0000000..91a34cf --- /dev/null +++ b/vendor/picocms/composer-installer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2012 The Pico Community + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/picocms/composer-installer/README.md b/vendor/picocms/composer-installer/README.md new file mode 100644 index 0000000..580a8ae --- /dev/null +++ b/vendor/picocms/composer-installer/README.md @@ -0,0 +1,174 @@ +Pico Composer Installer +======================= + +This is the repository of Pico's official [Composer][] installer. + +Pico is a stupidly simple, blazing fast, flat file CMS. See http://picocms.org/ for more info. + +This Composer plugin is responsible for installing Pico plugins and themes using the Composer package manager (i.e. by running `composer install` on the command line). It assumes responsibility for packages that identify as `{ "type": "pico-plugin" }` and `{ "type": "pico-theme" }` in their `composer.json` and instructs Composer to install these packages to Pico's `plugins/` and `themes/` folder respectively. + +The installer furthermore creates a `vendor/pico-plugin.php` with a list of all installed Pico plugins and the corresponding PHP classes (requires the `post-autoload-dump` event, see "Install" section below). This file is used by Pico 2.0+ to load such plugins at runtime and even allows you to completely disable filesystem-based loading of plugins. Just make sure to add a proper autoload section to your `composer.json` - otherwise Pico won't find your plugin's PHP class. + +The installer's behavior is fully configurable in both the plugin's and themes's `composer.json`, and the root package's `composer.json` (see the "Usage" section below). + +Please refer to [`picocms/Pico`](https://github.com/picocms/Pico) to get info about how to contribute or getting help. + +Install +------- + +If you've used Pico's official composer starter project ([`picocms/pico-composer`][pico-composer]), your website's `composer.json` (the "root package") already depends on `picocms/composer-installer`. If this isn't true, run the following to load it from [Packagist.org][]: + +```shell +$ composer require picocms/composer-installer:^1.0 +``` + +The Composer plugin tries to automatically register itself for the `post-autoload-dump` event. This is a prerequisite for the installer to create a `vendor/pico-plugin.php`. If the installer was successful in doing so, you'll see the following three lines when running `composer install` or `composer update`: + +``` +Generating autoload files +> Pico\Composer\Installer\PluginInstaller::postAutoloadDump +Creating Pico plugins file +``` + +If you see just the first two lines and not the third one, please make sure that your website identifies itself as `{ "type": "project" }` in your root package's `composer.json` and *directly* depends on `picocms/composer-installer`. If you see the first line only, let us know by opening a new Issue on [GitHub][pico-composer]. To solve this issue, add the following to the root package's `composer.json`: + +```json +{ + "scripts": { + "post-autoload-dump": [ + "Pico\\Composer\\Installer\\PluginInstaller::postAutoloadDump" + ] + } +} +``` + +Usage +----- + +Your plugins and themes themselves do **not** need to require `picocms/composer-installer`. They only need to specify the type in their `composer.json`: + +```json +{ + "type": "pico-plugin" +} +``` + +or + +```json +{ + "type": "pico-theme" +} +``` + +#### More about themes + +The Pico theme installer will automatically determine the installation directory by converting the package name to StudlyCase and removing the `-theme` suffix, if present. The result of this step is called "installer name". For example, the package `pico-nyan-cat-theme` is installed to the `themes/PicoNyanCat` directory. You can then use the theme by adding `theme: PicoNyanCat` to Pico's `config/config.yml`. + +You can overrule this behavior by setting the `installer-name` extra in your theme's `composer.json`. For example, Pico's official default theme ([`picocms/pico-theme`][pico-theme]) has the following lines in its `composer.json`, instructing the installer to install it to the `themes/default` directory: + +```json +{ + "extra": { + "installer-name": "default" + } +} +``` + +#### More about plugins + +The Pico plugin installer will automatically determine the installation directory by converting the package name to StudlyCase and removing the `-plugin` suffix, if present. The result of this step is called "installer name". The installer name is later used by Pico to load the plugin's PHP class. For example, the package `pico-nyan-cat-plugin` is installed to the `plugins/PicoNyanCat` directory and Pico later uses the `PicoNyanCat` PHP class to load the plugin. + +For the installer to work properly ensure that your plugin's `composer.json` has a proper autoload section, allowing Pico to later find the `PicoNyanCat` PHP class: + +```json +{ + "autoload": { + "classmap": [ "PicoNyanCat.php" ] + } +} +``` + +You can change the installation directory by setting the `installer-name` extra in your plugin's `composer.json`. By overruling the installer name, you also change the PHP class Pico uses to load the plugin. For example, if your package is called `my-vendor/my-pico-plugin`, the installer would install it to the `plugins/MyPico` directory. If you don't want the `-plugin` suffix to be removed, add the following lines to your plugin's `composer.json`: + +```json +{ + "extra": { + "installer-name": "MyPicoPlugin" + } +} +``` + +The installer will now install your plugin to the `plugins/MyPicoPlugin` directory and Pico loads the plugin using the `MyPicoPlugin` PHP class. + +#### Advanced plugin setups + +**If you're not an absolute Pico expert, don't read further!** Even if it sounds pretty convenient, the following is only relevant in very advanced setups: + +The Pico plugin installer consists of two parts: First, it determines the installer name to decide to which directory the plugin is installed to. Second, it creates a `vendor/pico-plugin.php` with a list of all installed plugins and the corresponding PHP classes. If this file is present, it is used by Pico 2.0+ to load these plugins. Pico naturally also ensures that these plugins aren't loaded as local plugin a second time. However, the `vendor/pico-plugin.php` is only created if the `post-autoload-dump` event is used (what is usually the case). + +If the `post-autoload-dump` event is *not* used, the installer won't create a `vendor/pico-plugin.php` and Pico loads the plugin the filesystem-based way: It looks at the directory name, tries to include a `.php` file of the same name in this directory and uses the same name as PHP class. In other words: If there's a `plugins/PicoNyanCat` directory, Pico includes the `plugins/PicoNyanCat/PicoNyanCat.php` file and loads the plugin using the `PicoNyanCat` PHP class. If this doesn't work, Pico irrecoverably bails out. + +As you've probably noticed already, this might go horribly wrong. *So, be careful!* + +If you want to overwrite the PHP classes Pico uses to load the plugin, or if you want to load multiple plugins at a time, use the `pico-plugin` extra in your plugin's `composer.json`. The `composer.json` of a plugin collection might look like the following: + +```json +{ + "extra": { + "installer-name": "MyPluginCollection", + "pico-plugin": [ + "MyVendor\\MyPluginCollection\\MyFirstPlugin", + "MyVendor\\MyPluginCollection\\MySecondPlugin" + ] + } +} +``` + +Please note that you **must not** use this feature if you want to share your plugin with others! + +#### Using the root package's `composer.json` + +All `composer.json` tweaks explained above can also be used in the root package's `composer.json`. The root package's `composer.json` even takes precedence over the plugin's or theme's `composer.json`, allowing you to overwrite the installer's behavior specifically for your website! + +If you e.g. want to install the Pico theme `some-vendor/nyan-cat-theme` to the `themes/TacNayn` directory instead of `themes/NyanCat`, add the following to the root package's `composer.json`: + +```json +{ + "extra": { + "installer-name": { + "some-vendor/nyan-cat-theme": "TacNayn" + } + } +} +``` + +Besides using the exact package name, you can also use the `vendor:` (e.g. `vendor:some-vendor`) and `name:` (e.g. `name:nyan-cat-theme`) prefixes to match a plugin or theme package's name. + +Naturally this isn't limited to themes, this works for plugins, too. However, *be very careful*, by changing a plugin's installer name, you (usually) also change the PHP class Pico uses to load the plugin. **This will likely break your installation!** See the "Advanced plugin setups" section above for more info. Simply put, don't use this for plugins! + +Sometimes your themes directory isn't called `themes/`, but rather something else, like `public/`. You can change the path to both the `themes/` and `plugins/` directory using the `pico-theme-dir` resp. `pico-plugin-dir` extra. Simply add the following to your root package's `composer.json`: + +```json +{ + "extra": { + "pico-theme-dir": "public/", + "pico-plugin-dir": "/some/absolute/path/" + } +} +``` + +#### What about websites not using Composer? + +Don't worry, Pico neither requires you to use Composer, nor `picocms/composer-installer`. + +If your plugin consists of the `PicoNyanCat` PHP class, create a `PicoNyanCat.php` and write its class definition into this file. If you then want to use that plugin, simply move the `PicoNyanCat.php` to your `plugins/` directory. If your plugin consists of multiple files (what is recommended, like a `README.md` or `LICENSE` file), create a `plugins/PicoNyanCat/` folder and move the `PicoNyanCat.php` into that folder (so that you get `plugins/PicoNyanCat/PicoNyanCat.php`). + +If you want to share your plugin, simply share said `plugins/PicoNyanCat/` folder and instruct your users to copy it to their `plugins/` directory. That's it! + +One might legitimately ask why he should use Composer and `picocms/composer-installer` in the first place. The answer's simple: Because Composer makes it even easier for the user - especially with more than two or three plugins! See Pico's official composer starter project ([`picocms/pico-composer`][pico-composer]) for a more complete reasoning. + +[Composer]: https://getcomposer.org/ +[pico-composer]: https://github.com/picocms/pico-composer +[Packagist.org]: https://packagist.org/packages/picocms/composer-installer +[pico-theme]: https://github.com/picocms/pico-theme diff --git a/vendor/picocms/composer-installer/composer.json b/vendor/picocms/composer-installer/composer.json new file mode 100644 index 0000000..869aa10 --- /dev/null +++ b/vendor/picocms/composer-installer/composer.json @@ -0,0 +1,35 @@ +{ + "name": "picocms/composer-installer", + "type": "composer-installer", + "description": "A composer plugin responsible for installing plugins and themes for Pico, a stupidly simple, blazing fast, flat file CMS.", + "keywords": [ "pico", "picocms", "pico-cms", "picocms-plugin", "picocms-theme", "picocms-installer", "composer", "composer-plugin", "composer-installer" ], + "homepage": "http://picocms.org/", + "license": "MIT", + "authors": [ + { + "name": "Daniel Rudolf", + "email": "picocms.org@daniel-rudolf.de", + "role": "Lead Developer" + }, + { + "name": "The Pico Community", + "homepage": "http://picocms.org/" + }, + { + "name": "Contributors", + "homepage": "https://github.com/picocms/composer-installer/graphs/contributors" + } + ], + "support": { + "issues": "https://github.com/picocms/composer-installer/issues", + "source": "https://github.com/picocms/composer-installer" + }, + "autoload": { + "psr-4": { + "Pico\\Composer\\": "src" + } + }, + "extra": { + "class": "Pico\\Composer\\Installer\\PluginInstaller" + } +} diff --git a/vendor/picocms/composer-installer/src/Installer/PluginInstaller.php b/vendor/picocms/composer-installer/src/Installer/PluginInstaller.php new file mode 100644 index 0000000..7bc9aad --- /dev/null +++ b/vendor/picocms/composer-installer/src/Installer/PluginInstaller.php @@ -0,0 +1,558 @@ + + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +namespace Pico\Composer\Installer; + +use Composer\Composer; +use Composer\Installer\BinaryInstaller; +use Composer\Installer\LibraryInstaller; +use Composer\IO\IOInterface; +use Composer\Package\AliasPackage; +use Composer\Package\PackageInterface; +use Composer\Script\Event; +use Composer\Util\Filesystem; + +/** + * Pico plugin and theme installer + * + * The Pico plugin and theme installer is responsible for installing plugins + * and themes for Pico using Composer. Pico is a stupidly simple, blazing fast, + * flat file CMS. + * + * See for more info. + * + * @author Daniel Rudolf + * @link http://picocms.org + * @license http://opensource.org/licenses/MIT The MIT License + * @version 1.0 + */ +class PluginInstaller extends LibraryInstaller +{ + /** + * Package name of this composer installer + * + * @var string + */ + const PACKAGE_NAME = 'picocms/composer-installer'; + + /** + * Package type of Pico plugins + * + * @var string + */ + const PACKAGE_TYPE_PLUGIN = 'pico-plugin'; + + /** + * Package type of Pico themes + * + * @var string + */ + const PACKAGE_TYPE_THEME = 'pico-theme'; + + /** + * Composer root package + * + * @var PackageInterface|null + */ + protected $rootPackage; + + /** + * Default package installation locations + * + * @var string[] + */ + protected $installDirs = array( + self::PACKAGE_TYPE_PLUGIN => 'plugins', + self::PACKAGE_TYPE_THEME => 'themes' + ); + + /** + * A flag to check usage of the postAutoloadDump event + * + * @var bool|null + */ + protected static $useAutoloadDump; + + /** + * Initializes Pico plugin and theme installer + * + * This method tries to register the `post-autoload-dump` script + * ({@see PluginInstaller::postAutoloadDump()}), if it wasn't explicitly + * set already. If this isn't possible, the autoload dump event can't be + * used ({@see PluginInstaller::checkAutoloadDump()}). + * + * @param IOInterface $io + * @param Composer $composer + * @param string $type + * @param Filesystem $filesystem + * @param BinaryInstaller $binaryInstaller + */ + public function __construct( + IOInterface $io, + Composer $composer, + $type = 'library', + Filesystem $filesystem = null, + BinaryInstaller $binaryInstaller = null + ) { + parent::__construct($io, $composer, $type, $filesystem, $binaryInstaller); + $this->rootPackage = static::getRootPackage($this->composer); + + // try to register the `post-autoload-dump` script + $scripts = $this->rootPackage->getScripts(); + $callback = get_called_class() . '::postAutoloadDump'; + if (isset($scripts['post-autoload-dump']) && in_array($callback, $scripts['post-autoload-dump'])) { + // the user explicitly added the `post-autoload-dump` script, + // force the autoload dump event to be used + static::$useAutoloadDump = true; + } else { + if (is_callable(array($this->rootPackage, 'setScripts'))) { + $scripts['post-autoload-dump'][] = $callback; + $this->rootPackage->setScripts($scripts); + } + + // check whether the autoload dump event is used + static::checkAutoloadDump($this->composer); + } + } + + /** + * Checks whether the autoload dump event is used + * + * Using the autoload dump event will always create `pico-plugin.php` in + * Composer's vendor dir. Plugins are nevertheless installed to Pico's + * `plugins/` dir ({@see PluginInstaller::getInstallPath()}). + * + * The autoload dump event is used when the root package is a project and + * explicitly requires this composer installer. + * + * @param Composer $composer + * + * @return bool + */ + public static function checkAutoloadDump(Composer $composer) + { + if (static::$useAutoloadDump === null) { + static::$useAutoloadDump = false; + + $rootPackage = static::getRootPackage($composer); + if (!$rootPackage || ($rootPackage->getType() !== 'project')) { + return false; + } + + $rootPackageRequires = $rootPackage->getRequires(); + if (!isset($rootPackageRequires[static::PACKAGE_NAME])) { + return false; + } + + $scripts = $rootPackage->getScripts(); + $callback = get_called_class() . '::postAutoloadDump'; + if (!isset($scripts['post-autoload-dump']) || !in_array($callback, $scripts['post-autoload-dump'])) { + return false; + } + + static::$useAutoloadDump = true; + } + + return static::$useAutoloadDump; + } + + /** + * Called whenever Composer (re)generates the autoloader + * + * Recreates the `pico-plugin.php` in Composer's vendor dir, containing + * a mapping of Composer package to Pico plugin class names. + * + * @param Event $event + */ + public static function postAutoloadDump(Event $event) + { + $io = $event->getIO(); + $composer = $event->getComposer(); + + $vendorDir = $composer->getConfig()->get('vendor-dir'); + $pluginConfig = static::getPluginConfig($vendorDir); + + if (!static::checkAutoloadDump($composer)) { + if (file_exists($pluginConfig) || is_link($pluginConfig)) { + $io->write('Deleting Pico plugins file'); + + $filesystem = new Filesystem(); + $filesystem->unlink($pluginConfig); + } + + return; + } + + if (!file_exists($pluginConfig) && !is_link($pluginConfig)) { + $io->write('Creating Pico plugins file'); + } else { + $io->write('Updating Pico plugins file'); + } + + $rootPackage = static::getRootPackage($composer); + $packages = $composer->getRepositoryManager()->getLocalRepository()->getPackages(); + + $plugins = $pluginClassNames = array(); + foreach ($packages as $package) { + if ($package->getType() !== static::PACKAGE_TYPE_PLUGIN) { + continue; + } + + $packageName = $package->getName(); + $plugins[$packageName] = static::getInstallName($package, $rootPackage); + $pluginClassNames[$packageName] = static::getPluginClassNames($package, $rootPackage); + } + + static::writePluginConfig($pluginConfig, $plugins, $pluginClassNames); + } + + /** + * Determines the plugin class names of a package + * + * Plugin class names are either specified explicitly in either the root + * package's or the plugin package's `composer.json`, or are derived + * implicitly from the plugin's installer name. The installer name is, for + * its part, either specified explicitly, or derived implicitly from the + * plugin package's name ({@see PluginInstaller::getInstallName()}). + * + * 1. Using the "pico-plugin" extra in the root package's `composer.json`: + * ```yaml + * { + * "extra": { + * "pico-plugin": { + * "": [ "", "", ... ] + * } + * } + * } + * ``` + * + * Besides matching exact package names, you can also use the prefixes + * `vendor:` or `name:` ({@see PluginInstaller::mapRootExtra()}). + * + * 2. Using the "pico-plugin" extra in the package's `composer.json`: + * ```yaml + * { + * "extra": { + * "pico-plugin": [ "", "", ... ] + * } + * } + * ``` + * + * 3. Using the installer name ({@see PluginInstaller::getInstallName()}). + * + * @param PackageInterface $package + * @param PackageInterface|null $rootPackage + * + * @return string[] + */ + public static function getPluginClassNames(PackageInterface $package, PackageInterface $rootPackage = null) + { + $packageType = $package->getType(); + $packagePrettyName = $package->getPrettyName(); + + $classNames = array(); + + // 1. root package + $rootPackageExtra = $rootPackage ? $rootPackage->getExtra() : null; + if (!empty($rootPackageExtra[$packageType])) { + $classNames = (array) static::mapRootExtra($rootPackageExtra[$packageType], $packagePrettyName); + } + + // 2. package + if (!$classNames) { + $packageExtra = $package->getExtra(); + if (!empty($packageExtra[$packageType])) { + $classNames = (array) $packageExtra[$packageType]; + } + } + + // 3. guess by installer name + if (!$classNames) { + $installName = static::getInstallName($package, $rootPackage); + $classNames = array($installName); + } + + return $classNames; + } + + /** + * Returns the install name of a package + * + * The install name of packages are either explicitly specified in either + * the root package's or the plugin package's `composer.json` using the + * "installer-name" extra, or implicitly derived from the plugin package's + * name. + * + * Install names are determined the same way as plugin class names. See + * {@see PluginInstaller::getPluginClassNames()} for details. + * + * @param PackageInterface $package + * @param PackageInterface|null $rootPackage + * + * @return string + */ + public static function getInstallName(PackageInterface $package, PackageInterface $rootPackage = null) + { + $packagePrettyName = $package->getPrettyName(); + $packageName = $package->getName(); + $installName = null; + + $rootPackageExtra = $rootPackage ? $rootPackage->getExtra() : null; + if (!empty($rootPackageExtra['installer-name'])) { + $installName = static::mapRootExtra($rootPackageExtra['installer-name'], $packagePrettyName); + } + + if (!$installName) { + $packageExtra = $package->getExtra(); + if (!empty($packageExtra['installer-name'])) { + $installName = $packageExtra['installer-name']; + } + } + + return $installName ?: static::guessInstallName($packageName); + } + + /** + * Guesses the install name of a package + * + * The install name of a Pico plugin or theme is guessed by converting the + * package name to StudlyCase and removing "-plugin" or "-theme" suffixes, + * if present. + * + * @param string $packageName + * + * @return string + */ + protected static function guessInstallName($packageName) + { + $name = $packageName; + if (strpos($packageName, '/') !== false) { + list(, $name) = explode('/', $packageName); + } + + $name = preg_replace('/[\.\-_]+(?>plugin|theme)$/u', '', $name); + $name = preg_replace_callback( + '/(?>^[\.\-_]*|[\.\-_]+)(.)/u', + function ($matches) { + return strtoupper($matches[1]); + }, + $name + ); + + return $name; + } + + /** + * Maps the root package's extra data to a package + * + * Besides matching the exact package name, you can also use the `vendor:` + * or `name:` prefixes to match all packages of a specific vendor resp. + * all packages with a specific name, no matter the vendor. + * + * @param mixed[] $packageExtra + * @param string $packagePrettyName + * + * @return mixed + */ + protected static function mapRootExtra(array $packageExtra, $packagePrettyName) + { + if (isset($packageExtra[$packagePrettyName])) { + return $packageExtra[$packagePrettyName]; + } + + if (strpos($packagePrettyName, '/') !== false) { + list($vendor, $name) = explode('/', $packagePrettyName); + } else { + $vendor = ''; + $name = $packagePrettyName; + } + + foreach ($packageExtra as $key => $value) { + if ((substr($key, 0, 5) === 'name:') && (substr($key, 5) === $name)) { + return $value; + } elseif ((substr($key, 0, 7) === 'vendor:') && (substr($key, 7) === $vendor)) { + return $value; + } + } + + return null; + } + + /** + * Returns the path to the pico-plugin.php in Composer's vendor dir + * + * @param string $vendorDir + * + * @return string + */ + protected static function getPluginConfig($vendorDir) + { + return $vendorDir . '/' . static::PACKAGE_TYPE_PLUGIN . '.php'; + } + + /** + * Rewrites the pico-plugin.php in Composer's vendor dir + * + * @param string $pluginConfig + * @param array $plugins + * @param array $pluginClassNames + */ + public static function writePluginConfig($pluginConfig, array $plugins, array $pluginClassNames) + { + $data = array(); + foreach ($plugins as $pluginName => $installerName) { + // see https://github.com/composer/composer/blob/1.0.0/src/Composer/Command/InitCommand.php#L206-L210 + if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $pluginName)) { + throw new \InvalidArgumentException( + "The package name '" . $pluginName . "' is invalid, it must be lowercase and have a vendor name, " + . "a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+" + ); + } + $data[] = sprintf(" '%s' => array(", $pluginName); + + if (!preg_match('{^[a-zA-Z0-9_.-]+$}', $installerName)) { + throw new \InvalidArgumentException( + "The installer name '" . $installerName . "' is invalid, " + . "it must be alphanumeric, matching: [a-zA-Z0-9_.-]+" + ); + } + $data[] = sprintf(" 'installerName' => '%s',", $installerName); + + if (isset($pluginClassNames[$pluginName])) { + $data[] = sprintf(" 'classNames' => array("); + + foreach ($pluginClassNames[$pluginName] as $className) { + // see https://secure.php.net/manual/en/language.oop5.basic.php + if (!preg_match('{^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$}', $className)) { + throw new \InvalidArgumentException( + "The plugin class name '" . $className . "' is no valid PHP class name" + ); + } + $data[] = sprintf(" '%s',", $className); + } + + $data[] = " ),"; + } + + $data[] = " ),"; + } + + $contents = <<<'PHP' +getPackage(); + if ($rootPackage) { + while ($rootPackage instanceof AliasPackage) { + $rootPackage = $rootPackage->getAliasOf(); + } + } + + return $rootPackage; + } + + /** + * Decides if the installer supports installing the given package type + * + * @param string $packageType + * + * @return bool + */ + public function supports($packageType) + { + return ( + ($packageType === static::PACKAGE_TYPE_PLUGIN) + || ($packageType === static::PACKAGE_TYPE_THEME) + ); + } + + /** + * Returns the installation path of a package + * + * Plugins are installed to the `plugins/`, themes to the `themes/` dir + * by default respectively. You can overwrite these target dirs using the + * "pico-plugin-dir" resp. "pico-theme-dir" extra in the root package's + * `composer.json`. + * + * @param PackageInterface $package + * + * @return string + */ + public function getInstallPath(PackageInterface $package) + { + $packageType = $package->getType(); + + $installDir = $this->initializeInstallDir($packageType); + $installName = static::getInstallName($package, $this->rootPackage); + return $installDir . '/' . $installName; + } + + /** + * Returns and initializes the installation directory of the given type + * + * @param string $packageType + * + * @return string + */ + protected function initializeInstallDir($packageType) + { + $installDir = ''; + + $rootPackageExtra = $this->rootPackage ? $this->rootPackage->getExtra() : null; + if (!empty($rootPackageExtra[$packageType . '-dir'])) { + $installDir = rtrim($rootPackageExtra[$packageType . '-dir'], '/\\'); + } + + if (!$installDir) { + if (empty($this->installDirs[$packageType])) { + throw new \InvalidArgumentException( + "The package type '" . $packageType . "' is not supported" + ); + } + + $installDir = $this->installDirs[$packageType]; + } + + if (!$this->filesystem->isAbsolutePath($installDir)) { + $installDir = dirname($this->vendorDir) . '/' . $installDir; + } + + $this->filesystem->ensureDirectoryExists($installDir); + return realpath($installDir); + } +} diff --git a/vendor/picocms/pico/.htaccess b/vendor/picocms/pico/.htaccess new file mode 100644 index 0000000..b3e7685 --- /dev/null +++ b/vendor/picocms/pico/.htaccess @@ -0,0 +1,23 @@ + + RewriteEngine On + # May be required to access sub directories + #RewriteBase / + + # Deny access to internal dirs and files by passing the URL to Pico + RewriteRule ^(config|content|content-sample|lib|vendor)(/|$) index.php [L] + RewriteRule ^(CHANGELOG\.md|composer\.(json|lock|phar))(/|$) index.php [L] + RewriteRule (^\.|/\.)(?!well-known(/|$)) index.php [L] + + # Enable URL rewriting + RewriteCond %{REQUEST_FILENAME} !-f + RewriteCond %{REQUEST_FILENAME} !-d + RewriteRule ^ index.php [L] + + + # Let Pico know about available URL rewriting + SetEnv PICO_URL_REWRITING 1 + + + +# Prevent file browsing +Options -Indexes -MultiViews diff --git a/vendor/picocms/pico/CHANGELOG.md b/vendor/picocms/pico/CHANGELOG.md new file mode 100644 index 0000000..bf84f7b --- /dev/null +++ b/vendor/picocms/pico/CHANGELOG.md @@ -0,0 +1,650 @@ +Pico Changelog +============== + +**Note:** This changelog only provides technical information about the changes + introduced with a particular Pico version, and is meant to supplement + the actual code changes. The information in this changelog are often + insufficient to understand the implications of larger changes. Please + refer to both the UPGRADE and NEWS sections of the docs for more + details. + +**Note:** Changes breaking backwards compatibility (BC) are marked with an `!` + (exclamation mark). This doesn't include changes for which BC is + preserved by Pico's official `PicoDeprecated` plugin. If a previously + deprecated feature is later removed in `PicoDeprecated`, this change + is going to be marked as BC-breaking change in both Pico's and + `PicoDeprecated`'s changelog. Please note that BC-breaking changes + are only possible with a new major version. + +### Version 2.1.4 +Released: 2020-08-29 + +``` +* [Changed] Silence PHP errors in Parsedown +* [Fixed] #560: Improve charset guessing for formatted date strings using + `strftime()` (Pico always uses UTF-8, but `strftime()` might not) +``` + +### Version 2.1.3 +Released: 2020-07-10 + +``` +* [New] Add `locale` option to `config/config.yml` +* [Changed] Improve Pico docs +``` + +### Version 2.1.2 +Released: 2020-04-10 + +``` +* [Fixed] Fix DummyPlugin declaring API version 3 +``` + +### Version 2.1.1 +Released: 2019-12-31 + +``` +* [Fixed] Require Parsedown 1.8.0-beta-7 and Parsedown Extra 0.8.0-beta-1 due + to changes in Parsedown and Parsedown Extra breaking BC beyond repair +* [Changed] #523: Check for hidden pages based on page ID instead of full paths +* [Changed] Improve Pico docs +``` + +### Version 2.1.0 +Released: 2019-11-24 + +``` +* [Changed] Add Pico's official logo and tagline to `content-sample/_meta.md` +* [Changed] Improve `content-sample/theme.md` to show Pico's official logo and + the usage of the new image utility classes of Pico's default theme +* [Changed] Improve Pico docs and PHPDoc class docs +``` + +### Version 2.1.0-beta.1 +Released: 2019-11-03 + +``` +* [New] Introduce API version 3 +* [New] Add `assets_dir`, `assets_url` and `plugins_url` config params +* [New] Add `%config.*%` Markdown placeholders for scalar config params and the + `%assets_url%`, `%themes_url%` and `%plugins_url%` placeholders +* [New] Add `content-sample/theme.md` for theme testing purposes +* [New] Introduce API versioning for themes and support theme-specific configs + using the new `pico-theme.yml` in a theme's directory; `pico-theme.yml` + allows a theme to influence Pico's Twig config, to register known meta + headers and to provide defaults for theme config params +* [New] Add `assets_url`, `themes_url` and `plugins_url` Twig variables +* [New] Add `pages` Twig function to deal with Pico's page tree; this function + replaces the raw usage of Pico's `pages` array in themes +* [New] Add `url` Twig filter to replace URL placeholders (e.g. `%base_url%`) + in strings using the new `Pico::substituteUrl()` method +* [New] Add `onThemeLoading` and `onThemeLoaded` events +* [New] Add `debug` config param and the `Pico::isDebugModeEnabled()` method, + checking the `PICO_DEBUG` environment variable, to enable debugging +* [New] Add new `Pico::getNormalizedPath()` method to normalize a path; this + method should be used to prevent content dir breakouts when dealing + with paths provided by user input +* [New] Add new `Pico::getUrlFromPath()` method to guess a URL from a file path +* [New] Add new `Pico::getAbsoluteUrl()` method to make a relative URL absolute +* [New] #505: Create pre-built `.zip` release archives +* [Fixed] #461: Proberly handle content files with a UTF-8 BOM +* [Changed] Rename `theme_url` config param to `themes_url`; the `theme_url` + Twig variable and Markdown placeholder are kept unchanged +* [Changed] Update to Parsedown Extra 0.8 and Parsedown 1.8 (both still beta) +* [Changed] Enable Twig's `autoescape` feature by default; outputting a + variable now causes Twig to escape HTML markup; Pico's `content` + variable is a notable exception, as it is marked as being HTML safe +* [Changed] Rename `prev_page` Twig variable to `previous_page` +* [Changed] Mark `markdown` and `content` Twig filters as well as the `content` + variable as being HTML safe +* [Changed] Add `$singleLine` param to `markdown` Twig filter as well as the + `Pico::parseFileContent()` method to parse just a single line of + Markdown input +* [Changed] Add `AbstractPicoPlugin::configEnabled()` method to check whether + a plugin should be enabled or disabled based on Pico's config +* [Changed] Deprecate the use of `AbstractPicoPlugin::__call()`, use + `PicoPluginInterface::getPico()` instead +* [Changed] Update to Twig 1.36 as last version supporting PHP 5.3, use a + Composer-based installation to use a newer Twig version +* [Changed] Add `$basePath` and `$endSlash` params to `Pico::getAbsolutePath()` +* [Changed] Deprecate `Pico::getBaseThemeUrl()` +* [Changed] Replace various `file_exists` calls with proper `is_file` calls +* [Changed] Refactor release & build system +* [Changed] Improve Pico docs and PHPDoc class docs +* [Changed] Various small improvements +* [Removed] Remove superfluous `base_dir` and `theme_dir` Twig variables +* [Removed] Remove `PicoPluginInterface::__construct()` +``` + +### Version 2.0.5-beta.1 +Released: 2019-01-03 + +``` +* [New] Add PHP 7.3 tests +* [New] Add `2.0.x-dev` alias for master branch to `composer.json` +* [Changed] Update to Parsedown Extra 0.8 and Parsedown 1.8 (both still beta) +* [Changed] Improve release & build process +``` + +### Version 2.0.4 +Released: 2018-12-17 + +``` +* [Fixed] Proberly handle hostnames with ports in `Pico::getBaseUrl()` +* [Changed] Improve documentation +``` + +### Version 2.0.3 +Released: 2018-12-03 + +``` +* [Fixed] Support alternative server ports in `Pico::getBaseUrl()` +* [Changed] Don't require server environment variables to be configured +* [Changed] Improve release & build process +* [Changed] Improve documentation +* [Changed] Improve PHP class docs +* [Changed] Various small improvements +``` + +### Version 2.0.2 +Released: 2018-08-12 + +``` +* [Fixed] Support Windows paths (`\` instead of `/`) in `Pico::evaluateRequestUrl()` +``` + +### Version 2.0.1 +Released: 2018-07-29 + +``` +* [Changed] Improve documentation +* [Changed] Add missing "Formatted Date", "Time" and "Hidden" meta headers; use + the "Hidden" meta header to manually hide a page in the pages list +``` + +### Version 2.0.0 +Released: 2018-07-01 + +``` +* [New] Add Bountysource +* [Changed] Improve documentation +* [Changed] Improve release & build process +* [Changed] Add `Pico::setConfig()` example to `index.php.dist` +* [Fixed] Don't load `config/config.yml` multiple times +``` + +### Version 2.0.0-beta.3 +Released: 2018-04-07 + +``` +* [Changed] Add `README.md`, `CONTRIBUTING.md` and `CHANGELOG.md` of main repo + to pre-bundled releases, keep `.gitignore` +* [Changed] Deny access to a possibly existing `composer.phar` in `.htaccess` +* [Changed] Disallow the use of the `callback` filter for the `url_param` and + `form_param` Twig functions +* [Changed] Improve documentation +* [Fixed] Fix page tree when sorting pages by arbitrary values +* [Fixed] Fix sorting of `Pico::$nativePlugins` +``` + +### Version 2.0.0-beta.2 +Released: 2018-01-21 + +``` +* [New] Improve release & build process and move most build tools to the new + `picocms/ci-tools` repo, allowing them to be used by other projects +* [New] Add page tree; refer to the `Pico::buildPageTree()` method for more + details; also see the `onPageTreeBuilt` event +* [Changed] Update dependencies: Twig 1.35 +* [Changed] ! Improve `.htaccess` and deny access to all dot files by default +* [Changed] ! Throw a `RuntimeException` when non-native plugins are loaded, + but Pico's `PicoDeprecated` plugin is not loaded +* [Changed] ! Change `AbstractPicoPlugin::$enabled`'s behavior: setting it to + TRUE now leads to throwing a `RuntimeException` when the plugin's + dependencies aren't fulfilled; use NULL to maintain old behavior +* [Changed] ! Force themes to use `.twig` as file extension for Twig templates +* [Changed] Improve PHP class docs +* [Changed] Various small improvements +``` + +### Version 2.0.0-beta.1 +Released: 2017-11-05 + +``` +* [New] Pico is on its way to its second major release! +* [New] Improve Pico's release & build process +* [New] Add "Developer Certificate of Origin" to `CONTRIBUTING.md` +* [New] Add license & copyright header to all relevant files +* [New] Add Pico version constants (`Pico::VERSION` and `Pico::VERSION_ID`), + and add a `version` Twig variable and `%version%` Markdown placeholder +* [New] Add Pico API versioning for plugins (see `Pico::API_VERSION` constant); + Pico now triggers events on plugins using the latest API version only + ("native" plugins), `PicoDeprecated` takes care of all other plugins; + as a result, old plugin's always depend on `PicoDeprecated` now +* [New] Add a theme and plugin installer for composer; Pico now additionally + uses the new `vendor/pico-plugin.php` file to discover plugins + installed by composer and loads them using composer's autoloader; + see the `picocms/composer-installer` repo for more details; Pico + loads plugins installed by composer first and ignores conflicting + plugins in Pico's `plugins/` dir +* [New] Add `$enableLocalPlugins` parameter to `Pico::__construct()` to allow + website developers to disable local plugin discovery by scanning the + `plugins/` dir (i.e. load plugins from `vendor/pico-plugin.php` only) +* [New] Add public `AbstractPicoPlugin::getPluginConfig()` method +* [New] Add public `Pico::loadPlugin()` method and the corresponding + `onPluginManuallyLoaded` event +* [New] Add public `Pico::resolveFilePath()` method (replaces the protected + `Pico::discoverRequestFile()` method) +* [New] Add public `Pico::is404Content()` method +* [New] Add public `Pico::getYamlParser()` method and the corresponding + `onYamlParserRegistered` event +* [New] Add public `Pico::substituteFileContent()` method +* [New] Add public `Pico::getPageId()` method +* [New] Add public `Pico::getFilesGlob()` method +* [New] Add public `Pico::getVendorDir()` method, returning Pico's installation + directory (i.e. `/var/www/pico/vendor/picocms/pico`); don't confuse + this with composer's `vendor/` dir! +* [New] Add `$default` parameter to `Pico::getConfig()` method +* [New] Add empty `assets/` and `content/` dirs +* [New] #305: Add `url_param` and `form_param` Twig functions, and the public + `Pico::getUrlParameter()` and `Pico::getFormParameter()` methods, + allowing theme developers to access URL GET and HTTP POST parameters +* [New] Add `$meta` parameter to `markdown` Twig filter +* [New] Add `remove` fallback to `sort_by` Twig filter +* [New] Add `theme_url` config parameter +* [New] Add public `Pico::getBaseThemeUrl()` method +* [New] Add `REQUEST_URI` routing method, allowing one to simply rewrite all + requests to `index.php` (e.g. use `FallbackResource` or `mod_rewrite` + in your `.htaccess` for Apache, or use `try_files` for nginx) +* [New] #299: Add built-in 404 page as fallback when no `404.md` is found +* [New] Allow sorting pages by arbitrary meta values +* [New] Add `onSinglePageLoading` event, allowing one to skip a page +* [New] Add `onSinglePageContent` event +* [New] Add some config parameters to change Parsedown's behavior +* [Changed] ! Disallow running the same Pico instance multiple times by + throwing a `RuntimeException` when calling `Pico::run()` +* [Changed] ! #203: Load plugins from `plugins//.php` + and `plugins/.php` only (directory and file name must + match case-sensitive), and throw a `RuntimeException` when Pico is + unable to load a plugin; also throw a `RuntimeException` when + superfluous files or directories in `plugins/` are found; use a + scope-isolated `require()` to include plugin files +* [Changed] ! Use a plugin dependency topology to sort `Pico::$plugins`, + changing the execution order of plugins so that plugins, on which + other plugins depend, are always executed before their dependants +* [Changed] ! Don't pass `$plugins` parameter to `onPluginsLoaded` event by + reference anymore; use `Pico::loadPlugin()` instead +* [Changed] ! Leave `Pico::$pages` unsorted when a unknown sort method was + configured; this usually means that a plugin wants to sort it +* [Changed] Overhaul page discovery events: add `onPagesDiscovered` event which + is triggered right before `Pico::$pages` is sorted and move the + `$currentPage`, `$previousPage` and `$nextPage` parameters of the + `onPagesLoaded` event to the new `onCurrentPageDiscovered` event +* [Changed] Move the `$twig` parameter of the `onPageRendering` event to the + `onTwigRegistered` event, replacing the `onTwigRegistration` event +* [Changed] Unify the `onParsedownRegistration` event by renaming it to + `onParsedownRegistered` and add the `$parsedown` parameter +* [Changed] #330: Replace `config/config.php` by a modular YAML-based approach; + you can now use a arbitrary number of `config/*.yml` files to + configure Pico +* [Changed] ! When trying to auto-detect Pico's `content` dir, Pico no longer + searches just for a (possibly empty) directory, but rather checks + whether a `index.md` exists in this directory +* [Changed] ! Use the relative path between `index.php` and `Pico::$themesDir` + for Pico's theme URL (also refer to the new `theme_url` config and + the public `Pico::getBaseThemeUrl()` method for more details) +* [Changed] #347: Drop the superfluous trailing "/index" from Pico's URLs +* [Changed] Flip registered meta headers array, so that the array key is used + to search for a meta value and the array value is used to store the + found meta value (previously it was the other way round) +* [Changed] ! Add lazy loading for `Pico::$yamlParser`, `Pico::$parsedown` and + `Pico::$twig`; the corresponding events are no longer part of + Pico's event flow and are triggered on demand +* [Changed] ! Trigger the `onMetaHeaders` event just once; the event is no + longer part of Pico's event flow and is triggered on demand +* [Changed] Don't lower meta headers on the first level of a page's meta data + (i.e. `SomeKey: value` is accessible using `$meta['SomeKey']`) +* [Changed] Don't compare registered meta headers case-insensitive, require + matching case +* [Changed] Allow users to explicitly set values for the `date_formatted` and + `time` meta headers in a page's YAML front matter +* [Changed] Add page siblings for all pages +* [Changed] ! Treat pages or directories that are prefixed by `_` as hidden; + when requesting a hidden page, Pico responds with a 404 page; + hidden pages are still in `Pico::$pages`, but are moved to the end + of the pages array when sorted alphabetically or by date +* [Changed] ! Don't treat explicit requests to a 404 page as successful request +* [Changed] Change method visibility of `Pico::getFiles()` to public +* [Changed] Change method visibility of `Pico::triggerEvent()` to public; + at first glance this method triggers events on native plugins only, + however, `PicoDeprecated` takes care of triggering events for other + plugins, thus you can use this method to trigger (custom) events on + all plugins; never use it to trigger Pico core events! +* [Changed] Move Pico's default theme to the new `picocms/pico-theme` repo; the + theme was completely rewritten from scratch and is a much better + starting point for creating your own theme; refer to the theme's + `CHANGELOG.md` for more details +* [Changed] Move `PicoDeprecated` plugin to the new `picocms/pico-deprecated` + repo; refer to the plugin's `CHANGELOG.md` for more details +* [Changed] Update dependencies: Twig 1.34, Symfony YAML 2.8, Parsedown 1.6 +* [Changed] Improve Pico docs and PHP class docs +* [Changed] A vast number of small improvements and changes... +* [Removed] ! Remove `PicoParsePagesContent` plugin +* [Removed] ! Remove `PicoExcerpt` plugin +* [Removed] Remove `rewrite_url` and `is_front_page` Twig variables +* [Removed] Remove superfluous parameters of various events to reduce Pico's + error-proneness (plugins hopefully interfere with each other less) +``` + +### Version 1.0.6 +Released: 2017-07-25 + +``` +* [Changed] Improve documentation +* [Changed] Improve handling of Pico's Twig config (`$config['twig_config']`) +* [Changed] Improve PHP platform requirement checks +``` + +### Version 1.0.5 +Released: 2017-05-02 + +``` +* [Changed] Improve documentation +* [Fixed] Improve hostname detection with proxies +* [Fixed] Fix detection of Windows-based server environments +* [Removed] Remove Twitter links +``` + +### Version 1.0.4 +Released: 2016-10-04 + +``` +* [New] Add Pico's social icons to default theme +* [Changed] Improve documentation +* [Changed] Add CSS flexbox rules to default theme +* [Fixed] Fix handling of non-YAML 1-line front matters +* [Fixed] Fix responsiveness in default theme +``` + +### Version 1.0.3 +Released: 2016-05-11 + +``` +* [Changed] Improve documentation +* [Changed] Heavily extend nginx configuration docs +* [Changed] Add CSS rules for definition lists to default theme +* [Changed] Always use `on404Content...` execution path when serving a `404.md` +* [Changed] Deny access to `.git` directory, `CHANGELOG.md`, `composer.json` + and `composer.lock` (`.htaccess` file) +* [Changed] Use Pico's `404.md` to deny access to `.git`, `config`, `content`, +* `content-sample`, `lib` and `vendor` dirs (`.htaccess` file) +* [Fixed] #342: Fix responsiveness in default theme +* [Fixed] #344: Improve HTTPS detection with proxies +* [Fixed] #346: Force HTTPS to load Google Fonts in default theme +``` + +### Version 1.0.2 +Released: 2016-03-16 + +``` +* [Changed] Various small improvements and changes... +* [Fixed] Check dependencies when a plugin is enabled by default +* [Fixed] Allow `Pico::$requestFile` to point to somewhere outside `content_dir` +* [Fixed] #336: Fix `Date` meta header parsing with ISO-8601 datetime strings +``` + +### Version 1.0.1 +Released: 2016-02-27 + +``` +* [Changed] Improve documentation +* [Changed] Replace `version_compare()` with `PHP_VERSION_ID` in + `index.php.dist` (available since PHP 5.2.7) +* [Fixed] Suppress PHP warning when using `date_default_timezone_get()` +* [Fixed] #329: Force Apache's `MultiViews` feature to be disabled +``` + +### Version 1.0.0 +Released: 2015-12-24 + +``` +* [New] On Christmas Eve, we are happy to announce Pico's first stable release! + The Pico Community wants to thank all contributors and users who made + this possible. Merry Christmas and a Happy New Year 2016! +* [New] Adding `$queryData` parameter to `Pico::getPageUrl()` method +* [Changed] Improve documentation +* [Changed] Moving `LICENSE` to `LICENSE.md` +* [Changed] Throw `LogicException` instead of `RuntimeException` when calling + `Pico::setConfig()` after processing has started +* [Changed] Default theme now highlights the current page and shows pages with + a title in the navigation only +* [Changed] #292: Ignore YAML parse errors (meta data) in `Pico::readPages()` +* [Changed] Various small improvements and changes... +* [Fixed] Support empty meta header +* [Fixed] #307: Fix path handling on Windows +``` + +### Version 1.0.0-beta.2 +Released: 2015-11-30 + +``` +* [New] Introducing the `PicoTwigExtension` Twig extension +* [New] New `markdown` filter for Twig to parse markdown strings; Note: If you + want to parse the contents of a page, use the `content` filter instead +* [New] New `sort_by` filter to sort an array by a specified key or key path +* [New] New `map` filter to get the values of the given key or key path +* [New] Introducing `index.php.dist` (used for pre-bundled releases) +* [New] Use PHP_CodeSniffer to auto-check source code (see `.phpcs.xml`) +* [New] Use Travis CI to generate phpDocs class docs automatically +* [Changed] Improve documentation +* [Changed] Improve table styling in default theme +* [Changed] Update composer version constraints; almost all dependencies will + have pending updates, run `composer update` +* [Changed] Throw a RuntimeException when the `content` dir isn't accessible +* [Changed] Reuse `ParsedownExtra` object; new `onParsedownRegistration` event +* [Changed] `$config['rewrite_url']` is now always available +* [Changed] `DummyPlugin` class is now final +* [Changed] Remove `.git` dirs from `vendor/` when deploying +* [Changed] Various small improvements and changes... +* [Fixed] `PicoDeprecated`: Sanitize `content_dir` and `base_url` options when + reading `config.php` in Picos root dir +* [Fixed] Replace `urldecode()` (deprecated RFC 1738) with `rawurldecode()` + (RFC 3986) in `Page::evaluateRequestUrl()` +* [Fixed] #272: Encode URLs using `rawurlencode()` in `Pico::getPageUrl()` +* [Fixed] #274: Prevent double slashes in `base_url` +* [Fixed] #285: Make `index.php` work when installed as a composer dependency +* [Fixed] #291: Force `Pico::$requestUrl` to have no leading/trailing slash +``` + +### Version 1.0.0-beta.1 +Released: 2015-11-06 + +``` +* [Security] (9e2604a) Prevent content_dir breakouts using malicious URLs +* [New] Pico is on its way to its first stable release! +* [New] Provide pre-bundled releases +* [New] Heavily expanded documentation (inline code docs, user docs, dev docs) +* [New] New routing system using the QUERY_STRING method; Pico now works + out-of-the-box with any webserver and without URL rewriting; use + `%base_url%?sub/page` in markdown files and `{{ "sub/page"|link }}` + in Twig templates to declare internal links +* [New] Brand new plugin system with dependencies (see `PicoPluginInterface` + and `AbstractPicoPlugin`); if you're plugin dev, you really should + take a look at the UPGRADE section of the docs! +* [New] Introducing the `PicoDeprecated` plugin to maintain full backward + compatibility with Pico 0.9 and Pico 0.8 +* [New] Support YAML-style meta header comments (`---`) +* [New] Various new placeholders to use in content files (e.g. `%site_title%`) +* [New] Provide access to all meta headers in content files (`%meta.*%`) +* [New] Provide access to meta headers in `$page` arrays (`$page['meta']`) +* [New] The file extension of content files is now configurable +* [New] Add `Pico::setConfig()` method to predefine config variables +* [New] Supporting per-directory `404.md` files +* [New] #103: Providing access to `sub.md` even when the `sub` directory + exists, provided that there is no `sub/index.md` +* [New] #249: Support the `.twig` file extension for templates +* [New] #268, 269: Now using Travis CI; performing basic code tests and + implementing an automatic release process +* [Changed] Complete code refactoring +* [Changed] Source code now follows PSR code styling +* [Changed] Replacing constants (e.g. `ROOT_DIR`) with constructor parameters +* [Changed] Paths (e.g. `content_dir`) are now relative to Pico's root dir +* [Changed] Adding `Pico::run()` method that performs Pico's processing and + returns the rendered contents +* [Changed] Renaming all plugin events; adding some new events +* [Changed] `Pico_Plugin` is now the fully documented `DummyPlugin` +* [Changed] Meta data must start on the first line of the file now +* [Changed] Dropping the need to register meta headers for the convenience of + users and pure (!) theme devs; plugin devs are still REQUIRED to + register their meta headers during `onMetaHeaders` +* [Changed] Exclude inaccessible files from pages list +* [Changed] With alphabetical order, index files (e.g. `sub/index.md`) are + now always placed before their sub pages (e.g. `sub/foo.md`) +* [Changed] Pico requires PHP >= 5.3.6 (due to `erusev/parsedown-extra`) +* [Changed] Pico now implicitly uses a existing `content` directory without + the need to configure this in the `config/config.php` explicitly +* [Changed] Composer: Require a v0.7 release of `erusev/parsedown-extra` +* [Changed] Moving `license.txt` to `LICENSE` +* [Changed] Moving and reformatting `changelog.txt` to `CHANGELOG.md` +* [Changed] #116: Parse meta headers using the Symfony YAML component +* [Changed] #244: Replace opendir() with scandir() +* [Changed] #246: Move `config.php` to `config/` directory +* [Changed] #253: Assume HTTPS if page is requested through port 443 +* [Changed] A vast number of small improvements and changes... +* [Fixed] Sorting by date now uses timestamps and works as expected +* [Fixed] Fixing `$currentPage`, `$nextPage` and `$previousPage` +* [Fixed] #99: Support content filenames with spaces +* [Fixed] #140, #241: Use file paths as page identifiers rather than titles +* [Fixed] #248: Always set a timezone; adding `$config['timezone']` option +* [Fixed] A vast number of small bugs... +* [Removed] Removing the default Twig cache dir +* [Removed] Removing various empty `index.html` files +* [Removed] Removing `$pageData['excerpt']`; recoverable with `PicoExcerpt` +* [Removed] #93, #158: Pico doesn't parse all content files anymore; moved to + `PicoParsePagesContent`; i.e. `$pageData['content']` doesn't exist + anymore, use `$pageData['raw_content']` when possible; otherwise + use Twigs new `content` filter (e.g. `{{ "sub/page"|content }}`) +``` + +### Version 0.9 +Released: 2015-04-28 + +``` +* [New] Default theme is now mobile-friendly +* [New] Description meta now available in content areas +* [New] Add description to composer.json +* [Changed] content folder is now content-sample +* [Changed] config.php moved to config.php.template +* [Changed] Updated documentation & wiki +* [Changed] Removed Composer, Twig files in /vendor, you must run composer + install now +* [Changed] Localized date format; strftime() instead of date() +* [Changed] Added ignore for tmp file extensions in the get_files() method +* [Changed] michelf/php-markdown is replaced with erusev/parsedown-extra +* [Changed] $config is no global variable anymore +* [Fixed] Pico now only removes the 1st comment block in .md files +* [Fixed] Issue wherein the alphabetical sorting of pages did not happen +``` + +### Version 0.8 +Released: 2013-10-23 + +``` +* [New] Added ability to set template in content meta +* [New] Added before_parse_content and after_parse_content hooks +* [Changed] content_parsed hook is now deprecated +* [Changed] Moved loading the config to nearer the beginning of the class +* [Changed] Only append ellipsis in limit_words() when word count exceeds max +* [Changed] Made private methods protected for better inheritance +* [Fixed] Fixed get_protocol() method to work in more situations +``` + +### Version 0.7 +Released: 2013-09-04 + +``` +* [New] Added before_read_file_meta and get_page_data plugin hooks to customize + page meta data +* [Changed] Make get_files() ignore dotfiles +* [Changed] Make get_pages() ignore Emacs and temp files +* [Changed] Use composer version of Markdown +* [Changed] Other small tweaks +* [Fixed] Date warnings and other small bugs +``` + +### Version 0.6.2 +Released: 2013-05-07 + +``` +* [Changed] Replaced glob_recursive with get_files +``` + +### Version 0.6.1 +Released: 2013-05-07 + +``` +* [New] Added "content" and "excerpt" fields to pages +* [New] Added excerpt_length config setting +``` + +### Version 0.6 +Released: 2013-05-06 + +``` +* [New] Added plugin functionality +* [Changed] Other small cleanup +``` + +### Version 0.5 +Released: 2013-05-03 + +``` +* [New] Added ability to order pages by "alpha" or "date" (asc or desc) +* [New] Added prev_page, current_page, next_page and is_front_page template vars +* [New] Added "Author" and "Date" title meta fields +* [Changed] Added "twig_config" to settings +* [Changed] Updated documentation +* [Fixed] Query string 404 bug +``` + +### Version 0.4.1 +Released: 2013-05-01 + +``` +* [New] Added CONTENT_EXT global +* [Changed] Use .md files instead of .txt +``` + +### Version 0.4 +Released: 2013-05-01 + +``` +* [New] Add get_pages() function for listing content +* [New] Added changelog.txt +* [Changed] Updated default theme +* [Changed] Updated documentation +``` + +### Version 0.3 +Released: 2013-04-27 + +``` +* [Fixed] get_config() function +``` + +### Version 0.2 +Released: 2013-04-26 + +``` +* [Changed] Updated Twig +* [Changed] Better checking for HTTPS +* [Fixed] Add 404 header to 404 page +* [Fixed] Case sensitive folder bug +``` + +### Version 0.1 +Released: 2012-04-04 + +``` +* Initial release +``` diff --git a/vendor/picocms/pico/CONTRIBUTING.md b/vendor/picocms/pico/CONTRIBUTING.md new file mode 100644 index 0000000..9d37588 --- /dev/null +++ b/vendor/picocms/pico/CONTRIBUTING.md @@ -0,0 +1,209 @@ +Contributing to Pico +==================== + +Pico aims to be a high quality Content Management System (CMS) but at the same time wants to give contributors freedom when submitting fixes or improvements. + +By contributing to Pico, you accept and agree to the *Developer Certificate of Origin* for your present and future contributions submitted to Pico. Please refer to the *Developer Certificate of Origin* section below. + +Aside from this, we want to *encourage*, but not obligate you, the contributor, to follow the following guidelines. The only exception to this are the guidelines elucidated in the *Prevent `merge-hell`* section. Having said that: we really appreciate it when you apply the guidelines in part or wholly as that will save us time which, in turn, we can spend on bugfixes and new features. + +Issues +------ + +If you want to report an *issue* with Pico's core, please create a new [Issue](https://github.com/picocms/Pico/issues) on GitHub. Concerning problems with plugins or themes, please refer to the website of the developer of this plugin or theme. + +Before creating a [new Issue on GitHub](https://github.com/picocms/Pico/issues/new), please make sure the problem wasn't reported yet using [GitHubs search engine](https://github.com/picocms/Pico/search?type=Issues). + +Please describe your issue as clear as possible and always include the *Pico version* you're using. Provided that you're using *plugins*, include a list of them too. We need information about the *actual and expected behavior*, the *steps to reproduce* the problem, and what steps you have taken to resolve the problem by yourself (i.e. *your own troubleshooting*). + +Contributing +------------ + +Once you decide you want to contribute to *Pico's core* (which we really appreciate!) you can fork the project from https://github.com/picocms/Pico. If you're interested in developing a *plugin* or *theme* for Pico, please refer to the [development section](http://picocms.org/development/) of our website. + +### Developer Certificate of Origin + +By contributing to Pico, you accept and agree to the following terms and conditions for your present and future contributions submitted to Pico. Except for the license granted herein to Pico and recipients of software distributed by Pico, you reserve all right, title, and interest in and to your contributions. All contributions are subject to the following DCO + license terms. + +``` +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. +1 Letterman Drive +Suite D4700 +San Francisco, CA, 94129 + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +(b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +(c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +(d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. +``` + +All contributions to this project are licensed under the following MIT License: + +``` +Copyright (c) + +Permission is hereby granted, free of charge, to any person +obtaining a copy of this software and associated documentation +files (the "Software"), to deal in the Software without +restriction, including without limitation the rights to use, +copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES +OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT +HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. +``` + +Please note that developing a *plugin* or *theme* for Pico is *not* assumed to be a contribution to Pico itself. By developing a plugin or theme you rather create a 3rd-party project that just uses Pico. Following the spirit of open source, we want to *encourage* you to release your plugin or theme under the terms of a [OSI-approved open source license](https://opensource.org/licenses). After all, Pico is open source, too! + +### Prevent `merge-hell` + +Please do *not* develop your contribution on the `master` branch of your fork, but create a separate feature branch, that is based off the `master` branch, for each feature that you want to contribute. + +> Not doing so means that if you decide to work on two separate features and place a pull request for one of them, that the changes of the other issue that you are working on is also submitted. Even if it is not completely finished. + +To get more information about the usage of Git, please refer to the [Pro Git book](https://git-scm.com/book) written by Scott Chacon and/or [this help page of GitHub](https://help.github.com/articles/using-pull-requests). + +### Pull Requests + +Please keep in mind that pull requests should be small (i.e. one feature per request), stick to existing coding conventions and documentation should be updated if required. It's encouraged to make commits of logical units and check for unnecessary whitespace before committing (try `git diff --check`). Please reference issue numbers in your commit messages where appropriate. + +### Coding Standards + +Pico uses the [PSR-2 Coding Standard](http://www.php-fig.org/psr/psr-2/) as defined by the [PHP Framework Interoperability Group (PHP-FIG)](http://www.php-fig.org/). + +For historical reasons we don't use formal namespaces. Markdown files in the `content-sample` folder (the inline documentation) must follow a hard limit of 80 characters line length. + +It is recommended to check your code using [PHP_CodeSniffer](https://github.com/squizlabs/PHP_CodeSniffer) using Pico's `.phpcs.xml` standard. Use the following command: + + $ ./vendor/bin/phpcs --standard=.phpcs.xml [file]... + +With this command you can specify a file or folder to limit which files it will check or omit that argument altogether, in which case the current working directory is checked. + +### Keep documentation in sync + +Pico accepts the problems of having redundant documentation on different places (concretely Pico's inline user docs, the `README.md` and the website) for the sake of a better user experience. When updating the docs, please make sure to keep them in sync. + +If you update the [`README.md`](https://github.com/picocms/Pico/blob/master/README.md) or [`content-sample/index.md`](https://github.com/picocms/Pico/blob/master/content-sample/index.md), please make sure to update the corresponding files in the [`_docs`](https://github.com/picocms/picocms.github.io/tree/master/_docs/) folder of the `picocms.github.io` repo (i.e. [Pico's website](http://picocms.org/docs/)) and vice versa. Unfortunately this involves three (!) different markdown parsers. If you're experiencing problems, use Pico's [`erusev/parsedown-extra`](https://github.com/erusev/parsedown-extra) as a reference. You can try to make the contents compatible to [Kramdown](http://kramdown.gettalong.org/) (Pico's website) and [CommonMarker](https://github.com/gjtorikian/commonmarker) (`README.md`) by yourself, otherwise please address the issues in your pull request message and we'll take care of it. + +Versioning +---------- + +Pico follows [Semantic Versioning 2.0](http://semver.org) and uses version numbers like `MAJOR`.`MINOR`.`PATCH`. We will increment the: + +- `MAJOR` version when we make incompatible API changes, +- `MINOR` version when we add functionality in a backwards-compatible manner, and +- `PATCH` version when we make backwards-compatible bug fixes. + +For more information please refer to the http://semver.org website. + +Branching +--------- + +The `master` branch contains the current development version of Pico. It is likely *unstable* and *not ready for production use*. + +However, the `master` branch always consists of a deployable (but not necessarily deployed) version of Pico. As soon as development of a new `MAJOR` or `MINOR` release starts, a separate branch (e.g. `pico-1.1`) is created and a [pull request](https://github.com/picocms/Pico/pulls) is opened to receive the desired feedback. + +Pico's actual development happens in separate development branches. Development branches are prefixed by: + +- `feature/` for bigger features, +- `enhancement/` for smaller improvements, and +- `bugfix/` for non-trivial bug fixes. + +As soon as development reaches a point where feedback is appreciated, a pull request is opened. After some time (very soon for bug fixes, and other improvements should have a reasonable feedback phase) the pull request is merged and the development branch will be deleted. Trivial bug fixes that will be part of the next `PATCH` version will be merged directly into `master`. + +Build & Release process +----------------------- + +We're using [Travis CI](https://travis-ci.com) to automate the build & release process of Pico. It generates and deploys a [PHP class documentation](http://picocms.org/phpDoc/) (powered by [phpDoc](http://phpdoc.org)) for new releases and on every commit to the `master` branch. Travis also prepares new releases by generating Pico's pre-built release packages, a version badge, code statistics (powered by [cloc](https://github.com/AlDanial/cloc)) and updates our website (the [`picocms.github.io` repo](https://github.com/picocms/picocms.github.io)). Please refer to our [`.travis.yml`](https://github.com/picocms/Pico/blob/master/.travis.yml), the [`picocms/ci-tools` repo](https://github.com/picocms/ci-tools) and the [`.build` directory](https://github.com/picocms/Pico/tree/master/.build) for details. + +As insinuated above, it is important that each commit to `master` is deployable. Once development of a new Pico release is finished, trigger Pico's build & release process by pushing a new Git tag. This tag should reference a (usually empty) commit on `master`, which message should adhere to the following template: + +``` +Version 1.0.0 + +* [Security] ... +* [New] ... +* [Changed] ... +* [Fixed] ... +* [Removed] ... +``` + +Before pushing a new Git tag, make sure to update the `Pico::VERSION` and `Pico::VERSION_ID` constants. The versions of Pico's official [default theme](https://github.com/picocms/pico-theme) and the [`PicoDeprecated` plugin](https://github.com/picocms/pico-deprecated) both strictly follow Pico's version. Since Pico's pre-built release package contains them, you must always create a new release of them (even though nothing has changed) before creating a new Pico release. + +If you're pushing a new major or minor release of Pico, you should also update Pico's `composer.json` to require the latest minor releases of Pico's dependencies. Besides, don't forget to update the `@version` tags in the PHP class docs. + +Travis CI will draft the new [release on GitHub](https://github.com/picocms/Pico/releases) automatically, but will require you to manually amend the descriptions formatting. The latest Pico version is always available at https://github.com/picocms/Pico/releases/latest, so please make sure to publish this URL rather than version-specific URLs. [Packagist](http://packagist.org/packages/picocms/pico) will be updated automatically. + +Labeling of Issues & Pull Requests +---------------------------------- + +Pico makes use of GitHub's label and milestone features, to aide developers in quickly identifying and prioritizing which issues need to be worked on. The starting point for labeling issues and pull requests is the `type` label, which is explained in greater detail below. The `type` label might get combined with a `pri` label, describing the issue's priority, and a `status` label, describing the current status of the issue. + +Issues and pull requests labeled with `info: Feedback Needed` indicate that feedback from others is highly appreciated. We always appreciate feedback at any time and from anyone, but when this label is present, we explicitly *ask* you to give feedback. It would be great if you leave a comment! + +- The `type: Bug` label is assigned to issues or pull requests, which have been identified as bugs or security issues in Pico's core. It might get combined with the `pri: High` label, when the problem was identified as security issue, or as a so-called "show stopper" bug. In contrast, uncritical problems might get labeled with `pri: Low`. `type: Bug` issues and pull requests are usually labeled with one of the following `status` labels when being closed: + - `status: Resolved` is used when the issue has been resolved. + - `status: Conflict` indicates a conflict with another issue or behavior of Pico, making it impossible to resolve the problem at the moment. + - `status: Won't Fix` means, that there is indeed a problem, but for some reason we made the decision that resolving it isn't reasonable, making it intended behavior. + - `status: Rejected` is used when the issue was rejected for another reason. + +- The `type: Enhancement` and `type: Feature` labels are used to tag pull requests, which introduce either a comparatively small enhancement, or a "big" new feature. As with the `type: Bug` label, they might get combined with the `pri: High` or `pri: Low` labels to indicate the pull request's priority. If a pull request isn't mergeable at the moment, it is labeled with `status: Work In Progress` until development of the pull request is finished. After merging or closing the pull request, it is labeled with one of the `status` labels as described above for the `type: Bug` label. + +- The `type: Idea` label is similar to the `type: Enhancement` and `type: Feature` labels, but is used for issues or incomplete and abandoned pull requests. It is otherwise used in the exact same way as `type: Enhancement` and `type: Feature`. + +- The `type: Release` label is used in the exact same way as `type: Feature` and indicates the primary pull request of a new Pico release (please refer to the *Branching* and *Build & Release process* sections above). + +- The `type: Notice`, `type: Question` and `type: Discussion` labels are used to indicate "fyi" issues, issues opened by users or developers asking questions, and issues with disucssions about arbitrary topics related to Pico. They are neither combined with `pri` labels, nor with `status` labels. + +- The `type: Duplicate` label is used when there is already another issue or pull request related to this problem or feature request. Issues labeled with `type: Duplicate` are immediately closed. + +- The `type: Invalid` label is used for everything else, e.g. issues or pull requests not related to Pico, or invalid bug reports. This includes supposed bug reports that concern actually intended behavior. + +The `status: Deferred` label might get added to any open issue or pull request to indicate that it is still unresolved and will be resolved later. This is also true for the `info: Pinned` label: It indicates a important issue or pull request that remains open on purpose. + +After resolving a issue, we usually keep it open for about a week to give users some more time for feedback and further questions. This is especially true for issues with the `type: Notice`, `type: Question`, `type: Discussion` and `type: Invalid` labels. After 7 days with no interaction, [Probot](https://probot.github.io/)'s [Stale](https://github.com/apps/stale) bot adds the `info: Stale` label to the issue to ask the participants whether the issue has been resolved. If no more activity occurs, the issue will be automatically closed by Stale bot 2 days later. + +Issues and pull requests labeled with `info: Information Needed` indicate that we have asked one of the participants for further information and didn't receive any feedback yet. It is usually added after Stale bot adds the `info: Stale` label to give the participants some more days to give the necessary information. + +Issues and pull requests, which are rather related to upstream projects (i.e. projects Pico depends on, like Twig), are additionally labeled with `info: Upstream`. + +When a issue or pull request isn't directly related to Pico's core, but the project as a whole, it is labeled with `info: Meta`. Issues labeled with `info: Website` are related to [Pico's website](http://picocms.org), however, in this case it is usually expedient to move the issue to the [`picocms.github.io` repo](https://github.com/picocms/picocms.github.io) instead. The same applies to the `info: Pico CMS for Nextcloud` label; these issues are related to [Pico CMS for Nextcloud](https://apps.nextcloud.com/apps/cms_pico). diff --git a/vendor/picocms/pico/LICENSE.md b/vendor/picocms/pico/LICENSE.md new file mode 100644 index 0000000..dced775 --- /dev/null +++ b/vendor/picocms/pico/LICENSE.md @@ -0,0 +1,22 @@ + Copyright (c) 2012 Dev7studios Ltd + + Permission is hereby granted, free of charge, to any person + obtaining a copy of this software and associated documentation + files (the "Software"), to deal in the Software without + restriction, including without limitation the rights to use, + copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the + Software is furnished to do so, subject to the following + conditions: + + The above copyright notice and this permission notice shall be + included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES + OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT + HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, + WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR + OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/vendor/picocms/pico/README.md b/vendor/picocms/pico/README.md new file mode 100644 index 0000000..bca6f45 --- /dev/null +++ b/vendor/picocms/pico/README.md @@ -0,0 +1,257 @@ +Pico +==== + +[![License](https://picocms.github.io/badges/pico-license.svg)](https://github.com/picocms/Pico/blob/master/LICENSE.md) +[![Version](https://picocms.github.io/badges/pico-version.svg)](https://github.com/picocms/Pico/releases/latest) +[![Build Status](https://api.travis-ci.org/picocms/Pico.svg?branch=master)](https://travis-ci.org/picocms/Pico) +[![Freenode IRC Webchat](https://picocms.github.io/badges/pico-chat.svg)](https://webchat.freenode.net/?channels=%23picocms) +[![Open Bounties on Bountysource](https://www.bountysource.com/badge/team?team_id=198139&style=bounties_received)](https://www.bountysource.com/teams/picocms) + +Pico is a stupidly simple, blazing fast, flat file CMS. + +Visit us at http://picocms.org/ and see http://picocms.org/about/ for more info. + +Screenshot +---------- + +![Pico Screenshot](https://picocms.github.io/screenshots/pico-21.png) + +Install +------- + +Installing Pico is dead simple - and done in seconds! If you have access to a shell on your server (i.e. SSH access), we recommend using [Composer][]. If not, use a pre-bundled release. If you don't know what "SSH access" is, head over to the pre-bundled release. 😇 + +Pico requires PHP 5.3.6+ and the PHP extensions `dom` and `mbstring` to be enabled. + +### I want to use Composer + +Starting with Pico 2.0 we recommend installing Pico using Composer whenever possible. Trust us, you won't regret it when it comes to upgrading Pico! Anyway, if you don't want to use Composer, or if you simply can't use Composer because you don't have access to a shell on your server, don't despair, installing Pico using a pre-bundled release is still easier than everything you know! + +###### Step 1 + +Open a shell and navigate to the `httpdocs` directory (e.g. `/var/www/html`) of your server. Download Composer and run it with the `create-project` option to install it to the desired directory (e.g. `/var/www/html/pico`): + +```shell +$ curl -sSL https://getcomposer.org/installer | php +$ php composer.phar create-project picocms/pico-composer pico +``` + +###### Step 2 + +What second step? There's no second step. That's it! Open your favorite web browser and navigate to your brand new, stupidly simple, blazing fast, flat file CMS! Pico's sample contents will explain how to create your own contents. 😊 + +### I want to use a pre-bundled release + +Do you know the feeling: You want to install a new website, so you upload all files of your favorite CMS and run the setup script - just to find out that you forgot about creating the SQL database first? Later the setup script tells you that the file permissions are wrong. Heck, what does this even mean? Forget about it, Pico is different! + +###### Step 1 + +[Download the latest Pico release][LatestRelease] and upload all files to the desired install directory of Pico within the `httpdocs` directory (e.g. `/var/www/html/pico`) of your server. + +###### Step 2 + +Okay, here's the catch: There's no catch. That's it! Open your favorite web browser and navigate to your brand new, stupidly simple, blazing fast, flat file CMS! Pico's sample contents will explain how to create your own contents. 😊 + +### I want to manage my website using a Git repository + +Git is a very powerful distributed version-control system - and it can be used to establish a nice workflow around your Pico website. Using a Git repository for your website aids content creation and deployment, including collaborative editing and version control. If you want to manage your website in a Git repository, you use a Composer-based installation. + +1. Fork [Pico's Composer starter project][PicoComposerGit] using [GitHub's fork button][HelpFork]. If you don't want to use GitHub you aren't required to, you can choose whatever Git server you want. Forking manually just requires some extra steps: First clone the Git repository locally, add your Git server as a remote and push the repository to this new remote. + +2. Clone your fork locally and add your contents and assets. You can edit Pico's `composer.json` to include 3rd-party plugins and themes, or simply add your own plugins and themes to Pico's `plugins` resp. `themes` directories. Don't forget to commit your changes and push them to your Git server. + +3. Open a shell on your webserver and navigate to the `httpdocs` directory (e.g. `/var/www/html`). Download Composer, clone your Git repository to the desired directory (e.g. `/var/www/html/pico`) and install Pico's dependencies using Composer's `install` option: + + ```shell + $ curl -sSL https://getcomposer.org/installer | php + $ git clone https://github.com// pico + $ php composer.phar --working-dir=pico install + ``` + +4. If you update your website's contents, simply commit your changes and push them to your Git server. Open a shell on your webserver and navigate to Pico's install directory within the `httpdocs` directory (e.g. `/var/www/html/pico`) of your server. Pull all changes from your Git server and update Pico's dependencies using Composer's `update` option: + + ```shell + $ git pull + $ php composer.phar update + ``` + +### I'm a developer + +So, you're one of these amazing people making all of this possible? We love you folks! As a developer we recommend you to clone [Pico's Git repository][PicoGit] as well as the Git repositories of [Pico's default theme][PicoThemeGit] and the [`PicoDeprecated` plugin][PicoDeprecatedGit]. You can set up your workspace using [Pico's Composer starter project][PicoComposerGit] and include all of Pico's components using local packages. + +Using Pico's Git repositories is different from using one of the installation methods elucidated above. It gives you the current development version of Pico, what is likely *unstable* and *not ready for production use*! + +1. Open a shell and navigate to the desired directory of Pico's development workspace within the `httpdocs` directory (e.g. `/var/www/html/pico`) of your server. Download and extract Pico's Composer starter project into the `workspace` directory: + + ```shell + $ curl -sSL https://github.com/picocms/pico-composer/archive/master.tar.gz | tar xz + $ mv pico-composer-master workspace + ``` + +2. Clone the Git repositories of all Pico components (Pico's core, Pico's default theme and the `PicoDeprecated` plugin) into the `components` directory: + + ```shell + $ mkdir components + $ git clone https://github.com/picocms/Pico.git components/pico + $ git clone https://github.com/picocms/pico-theme.git components/pico-theme + $ git clone https://github.com/picocms/pico-deprecated.git components/pico-deprecated + ``` + +3. Instruct Composer to use the local Git repositories as replacement for the `picocms/pico` (Pico's core), `picocms/pico-theme` (Pico's default theme) and `picocms/pico-deprecated` (the `PicoDeprecated` plugin) packages. Update the `composer.json` of your development workspace (i.e. `workspace/composer.json`) accordingly: + + ```json + { + "repositories": [ + { + "type": "path", + "url": "../components/pico", + "options": { "symlink": true } + }, + { + "type": "path", + "url": "../components/pico-theme", + "options": { "symlink": true } + }, + { + "type": "path", + "url": "../components/pico-deprecated", + "options": { "symlink": true } + } + ], + "require": { + "picocms/pico": "dev-master", + "picocms/pico-theme": "dev-master", + "picocms/pico-deprecated": "dev-master", + "picocms/composer-installer": "^1.0" + } + } + ``` + +4. Download Composer and run it with the `install` option: + + ```shell + $ curl -sSL https://getcomposer.org/installer | php + $ php composer.phar --working-dir=workspace install + ``` + +You can now open your web browser and navigate to Pico's development workspace. All changes you make to Pico's components will automatically be reflected in the development workspace. + +By the way, you can also find all of Pico's components on [Packagist.org][Packagist]: [Pico's core][PicoPackagist], [Pico's default theme][PicoThemePackagist], the [`PicoDeprecated` plugin][PicoDeprecatedPackagist] and [Pico's Composer starter project][PicoComposerPackagist]. + +Upgrade +------- + +Do you remember when you installed Pico? It was ingeniously simple, wasn't it? Upgrading Pico is no difference! The upgrade process differs depending on whether you used [Composer][] or a pre-bundled release to install Pico. Please note that you should *always* create a backup of your Pico installation before upgrading! + +Pico follows [Semantic Versioning 2.0][SemVer] and uses version numbers like `MAJOR`.`MINOR`.`PATCH`. When we update the `PATCH` version (e.g. `2.0.0` to `2.0.1`), we made backwards-compatible bug fixes. If we change the `MINOR` version (e.g. `2.0` to `2.1`), we added functionality in a backwards-compatible manner. Upgrading Pico is dead simple in both cases. Simply head over to the appropiate Upgrade sections below. + +But wait, we forgot to mention what happens when we update the `MAJOR` version (e.g. `2.0` to `3.0`). In this case we made incompatible API changes. We will then provide a appropriate upgrade tutorial, so please head over to the ["Upgrade" page on our website][HelpUpgrade]. + +### I've used Composer to install Pico + +Upgrading Pico is dead simple if you've used Composer to install Pico. Simply open a shell and navigate to Pico's install directory within the `httpdocs` directory (e.g. `/var/www/html/pico`) of your server. You can now upgrade Pico using just a single command: + +```shell +$ php composer.phar update +``` + +That's it! Composer will automatically update Pico and all plugins and themes you've installed using Composer. Please make sure to manually update all plugins and themes you've installed manually. + +### I've used a pre-bundled release to install Pico + +Okay, installing Pico was easy, but upgrading Pico is going to be hard, isn't it? I'm afraid I have to disappoint you. It's just as simple as installing Pico! + +First you'll have to delete the `vendor` directory of your Pico installation (e.g. if you've installed Pico to `/var/www/html/pico`, delete `/var/www/html/pico/vendor`). Then [download the latest Pico release][LatestRelease] and upload all files to your existing Pico installation directory. You will be prompted whether you want to overwrite files like `index.php`, `.htaccess`, ... - simply hit "Yes". + +That's it! Now that Pico is up-to-date, you need to update all plugins and themes you've installed. + +### I'm a developer + +As a developer you should know how to stay up-to-date... 😉 For the sake of completeness, if you want to upgrade Pico, simply open a shell and navigate to Pico's development workspace (e.g. `/var/www/html/pico`). Then pull the latest commits from the Git repositories of [Pico's core][PicoGit], [Pico's default theme][PicoThemeGit] and the [`PicoDeprecated` plugin][PicoDeprecatedGit]. Let Composer update your dependencies and you're ready to go. + +```shell +$ git -C components/pico pull +$ git -C components/pico-theme pull +$ git -C components/pico-deprecated pull +$ php composer.phar --working-dir=workspace update +``` + +Getting Help +------------ + +#### Getting Help as a user + +If you want to get started using Pico, please refer to our [user docs][HelpUserDocs]. Please read the [upgrade notes][HelpUpgrade] if you want to upgrade from Pico 1.0 to Pico 2.0. You can find officially supported [plugins][OfficialPlugins] and [themes][OfficialThemes] on our website. A greater choice of third-party plugins and themes can be found in our [Wiki][] on the [plugins][WikiPlugins] or [themes][WikiThemes] pages respectively. If you want to create your own plugin or theme, please refer to the "Getting Help as a developer" section below. + +#### Getting Help as a developer + +If you're a developer, please refer to the "Contributing" section below and our [contribution guidelines][ContributionGuidelines]. To get you started with creating a plugin or theme, please read the [developer docs on our website][HelpDevDocs]. + +#### You still need help or experience a problem with Pico? + +When the docs can't answer your question, you can get help by joining us on [#picocms on Freenode IRC][Freenode] ([logs][FreenodeLogs]). When you're experiencing problems with Pico, please don't hesitate to create a new [Issue][Issues] on GitHub. Concerning problems with plugins or themes, please refer to the website of the developer of this plugin or theme. + +**Before creating a new Issue,** please make sure the problem wasn't reported yet using [GitHubs search engine][IssuesSearch]. Please describe your issue as clear as possible and always include the *Pico version* you're using. Provided that you're using *plugins*, include a list of them too. We need information about the *actual and expected behavior*, the *steps to reproduce* the problem, and what steps you have taken to resolve the problem by yourself (i.e. *your own troubleshooting*). + +Contributing +------------ + +You want to contribute to Pico? We really appreciate that! You can help make Pico better by [contributing code][PullRequests] or [reporting issues][Issues], but please take note of our [contribution guidelines][ContributionGuidelines]. In general you can contribute in three different areas: + +1. Plugins & Themes: You're a plugin developer or theme designer? We love you folks! You can find tons of information about how to develop plugins and themes at http://picocms.org/development/. If you have created a plugin or theme, please add it to our [Wiki][], either on the [plugins][WikiPlugins] or [themes][WikiThemes] page. You may also [Submit][] it to our website, where it'll be displayed on the official [plugin][OfficialPlugins] or [theme][OfficialThemes] pages! + +2. Documentation: We always appreciate people improving our documentation. You can either improve the [inline user docs][EditInlineDocs] or the more extensive [user docs on our website][EditUserDocs]. You can also improve the [docs for plugin and theme developers][EditDevDocs]. Simply fork our website's Git repository from https://github.com/picocms/picocms.github.io, change the Markdown files and open a [pull request][PullRequestsWebsite]. + +3. Pico's Core: The supreme discipline is to work on Pico's Core. Your contribution should help *every* Pico user to have a better experience with Pico. If this is the case, fork Pico from https://github.com/picocms/Pico and open a [pull request][PullRequests]. We look forward to your contribution! + +By contributing to Pico, you accept and agree to the *Developer Certificate of Origin* for your present and future contributions submitted to Pico. Please refer to the ["Developer Certificate of Origin" section in our `CONTRIBUTING.md`][ContributionGuidelinesDCO]. + +You don't have time to contribute code to Pico, but still want to "stand a coffee" for the ones who do? You can contribute monetary to Pico using [Bountysource][], a crowd funding website that focuses on individual issues and feature requests. Just refer to the "Bounties and Fundraisers" section below for more info. + +Bounties and Fundraisers +------------------------ + +Pico uses [Bountysource][] to allow monetary contributions to the project. Bountysource is a crowd funding website that focuses on individual issues and feature requests in Open Source projects using micropayment. Users, or "Backers", can pledge money for fixing a specific issue, implementing new features, or developing a new plugin or theme. Open source software developers, or "Bounty Hunters", can then pick up and solve these tasks to earn the money. + +Obviously this won't allow a developer to replace a full time job, it's rather aiming to "stand a coffee". However, it helps bringing users and developers closer together, and shows developers what users want and how much they care about certain things. Nevertheless you can still donate money to the project itself, as an easy way to say "Thank You" and to support Pico. + +If you want to encourage developers to [fix a specific issue][Issues] or implement a feature, simply [pledge a new bounty][Bountysource] or back an existing one. + +As a developer you can pick up a bounty by simply contributing to Pico (please refer to the "Contributing" section above). You don't have to be a official Pico Contributor! Pico is a Open Source project, anyone can open [pull requests][PullRequests] and claim bounties. + +Official Pico Contributors won't claim bounties on their own behalf, Pico will never take any money out of Bountysource. All money collected by Pico is used to pledge new bounties or to support projects Pico depends on. + +[Composer]: https://getcomposer.org/ +[LatestRelease]: https://github.com/picocms/Pico/releases/latest +[PicoGit]: https://github.com/picocms/Pico +[PicoThemeGit]: https://github.com/picocms/pico-theme +[PicoDeprecatedGit]: https://github.com/picocms/pico-deprecated +[PicoComposerGit]: https://github.com/picocms/pico-composer +[Packagist]: https://packagist.org/ +[PicoPackagist]: https://packagist.org/packages/picocms/pico +[PicoThemePackagist]: https://packagist.org/packages/picocms/pico-theme +[PicoDeprecatedPackagist]: https://packagist.org/packages/picocms/pico-deprecated +[PicoComposerPackagist]: https://packagist.org/packages/picocms/pico-composer +[SemVer]: http://semver.org +[HelpFork]: https://help.github.com/en/github/getting-started-with-github/fork-a-repo +[HelpUpgrade]: http://picocms.org/in-depth/upgrade/ +[HelpUserDocs]: http://picocms.org/docs/ +[HelpDevDocs]: http://picocms.org/development/ +[Submit]: http://picocms.org/in-depth/submission_guidelines +[OfficialPlugins]: http://picocms.org/plugins/ +[OfficialThemes]: http://picocms.org/themes/ +[Wiki]: https://github.com/picocms/Pico/wiki +[WikiPlugins]: https://github.com/picocms/Pico/wiki/Pico-Plugins +[WikiThemes]: https://github.com/picocms/Pico/wiki/Pico-Themes +[Issues]: https://github.com/picocms/Pico/issues +[IssuesSearch]: https://github.com/picocms/Pico/search?type=Issues +[Freenode]: https://webchat.freenode.net/?channels=%23picocms +[FreenodeLogs]: http://picocms.org/irc-logs +[PullRequests]: https://github.com/picocms/Pico/pulls +[PullRequestsWebsite]: https://github.com/picocms/picocms.github.io/pulls +[ContributionGuidelines]: https://github.com/picocms/Pico/blob/master/CONTRIBUTING.md +[ContributionGuidelinesDCO]: https://github.com/picocms/Pico/blob/master/CONTRIBUTING.md#developer-certificate-of-origin +[EditInlineDocs]: https://github.com/picocms/Pico/edit/master/content-sample/index.md +[EditUserDocs]: https://github.com/picocms/picocms.github.io/tree/master/_docs +[EditDevDocs]: https://github.com/picocms/picocms.github.io/tree/master/_development +[Bountysource]: https://www.bountysource.com/teams/picocms diff --git a/vendor/picocms/pico/composer.json b/vendor/picocms/pico/composer.json new file mode 100644 index 0000000..b9ff27c --- /dev/null +++ b/vendor/picocms/pico/composer.json @@ -0,0 +1,59 @@ +{ + "name": "picocms/pico", + "type": "library", + "description": "Pico is a flat file CMS, this means there is no administration backend and database to deal with. You simply create .md files in the \"content\" folder and that becomes a page.", + "keywords": ["pico", "picocms", "pico-cms", "simple", "flat-file", "cms", "content-management", "website", "markdown-to-html", "php", "markdown", "yaml", "twig" ], + "homepage": "http://picocms.org/", + "license": "MIT", + "authors": [ + { + "name": "Gilbert Pellegrom", + "email": "gilbert@pellegrom.me", + "role": "Project Founder" + }, + { + "name": "Daniel Rudolf", + "email": "picocms.org@daniel-rudolf.de", + "role": "Lead Developer" + }, + { + "name": "The Pico Community", + "homepage": "http://picocms.org/" + }, + { + "name": "Contributors", + "homepage": "https://github.com/picocms/Pico/graphs/contributors" + } + ], + "support": { + "docs": "http://picocms.org/docs", + "issues": "https://github.com/picocms/Pico/issues", + "source": "https://github.com/picocms/Pico" + }, + "require": { + "php": ">=5.3.6", + "ext-mbstring": "*", + "twig/twig": "^1.36", + "symfony/yaml" : "^2.8", + "erusev/parsedown": "1.8.0-beta-7", + "erusev/parsedown-extra": "0.8.0-beta-1" + }, + "suggest": { + "picocms/pico-theme": "Pico requires a theme to actually display the contents of your website. This is Pico's official default theme.", + "picocms/pico-deprecated": "PicoDeprecated's purpose is to maintain backward compatibility to older versions of Pico.", + "picocms/composer-installer": "This Composer plugin is responsible for installing Pico plugins and themes using the Composer package manager." + }, + "autoload": { + "psr-0": { + "Pico": "lib/", + "PicoPluginInterface": "lib/", + "AbstractPicoPlugin": "lib/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "2.1.x-dev", + "dev-pico-3.0": "3.0.x-dev" + } + } +} diff --git a/vendor/picocms/pico/config/config.yml.template b/vendor/picocms/pico/config/config.yml.template new file mode 100644 index 0000000..5500ccb --- /dev/null +++ b/vendor/picocms/pico/config/config.yml.template @@ -0,0 +1,60 @@ +## +# Basic +# +site_title: Pico # The title of your website +base_url: ~ # Pico will try to guess its base URL, if this fails, override it here; + # Example: https://example.com/pico/ +rewrite_url: ~ # A boolean (true or false) indicating whether URL rewriting is forced +debug: ~ # Set this to true to enable Pico's debug mode +timezone: ~ # Your PHP installation might require you to manually specify a timezone +locale: ~ # Your PHP installation might require you to manually specify a locale to use + +## +# Theme +# +theme: default # The name of your custom theme +themes_url: ~ # Pico will try to guess the URL to the themes dir of your installation; + # If this fails, override it here. Example: https://example.com/pico/themes/ +theme_config: # Additional theme-specific config + widescreen: false # Default theme: Use more horizontal space (i.e. make the site container wider) +twig_config: # Twig template engine config + autoescape: html # Let Twig escape variables by default + strict_variables: false # If set to true, Twig will bail out when unset variables are being used + charset: utf-8 # The charset used by Twig templates + debug: ~ # Enable Twig's debug mode + cache: false # Enable Twig template caching by specifying a path to a writable directory + auto_reload: ~ # Recompile Twig templates whenever the source code changes + +## +# Content +# +date_format: %D %T # Pico's default date format; + # See https://php.net/manual/en/function.strftime.php for more info +pages_order_by_meta: author # Sort pages by meta value "author" (set "pages_order_by" to "meta") +pages_order_by: alpha # Change how Pico sorts pages ("alpha" for alphabetical order, "date", or "meta") +pages_order: asc # Sort pages in ascending ("asc") or descending ("desc") order +content_dir: ~ # The path to Pico's content directory +content_ext: .md # The file extension of your Markdown files +content_config: # Parsedown Markdown parser config + extra: true # Use the Parsedown Extra parser to support extended markup; + # See https://michelf.ca/projects/php-markdown/extra/ for more info + breaks: false # A boolean indicating whether breaks in the markup should be reflected in the + # parsed contents of the page + escape: false # Escape HTML markup in your content files; don't confuse this with some sort of + # safe mode, enabling this doesn't allow you to process untrusted user input! + auto_urls: true # Automatically link URLs found in your markup +assets_dir: assets/ # The path to Pico's assets directory +assets_url: ~ # Pico will try to guess the URL to the assets dir of your installation; + # If this fails, override it here. Example: https://example.com/pico/assets/ + +## +# Plugins +# +plugins_url: ~ # Pico will try to guess the URL to the plugins dir of your installation; + # If this fails, override it here. Example: https://example.com/pico/plugins/ +DummyPlugin.enabled: false # Force the plugin "DummyPlugin" to be disabled + +## +# Custom +# +my_custom_setting: Hello World! # You can access custom settings in themes using {{ config.my_custom_setting }} diff --git a/vendor/picocms/pico/content-sample/404.md b/vendor/picocms/pico/content-sample/404.md new file mode 100644 index 0000000..e6ddf30 --- /dev/null +++ b/vendor/picocms/pico/content-sample/404.md @@ -0,0 +1,9 @@ +--- +Title: Error 404 +Robots: noindex,nofollow +--- + +Error 404 +========= + +Woops. Looks like this page doesn't exist. diff --git a/vendor/picocms/pico/content-sample/_meta.md b/vendor/picocms/pico/content-sample/_meta.md new file mode 100644 index 0000000..d18f051 --- /dev/null +++ b/vendor/picocms/pico/content-sample/_meta.md @@ -0,0 +1,14 @@ +--- +Logo: %theme_url%/img/pico-white.svg +Tagline: Making the web easy. +Social: + - title: Visit us on GitHub + url: https://github.com/picocms/Pico + icon: octocat + - title: Join us on Freenode IRC Webchat + url: https://webchat.freenode.net/?channels=%23picocms + icon: chat + - title: Help us by creating/collecting bounties and pledging to fundraisers + url: https://www.bountysource.com/teams/picocms + icon: dollar +--- diff --git a/vendor/picocms/pico/content-sample/index.md b/vendor/picocms/pico/content-sample/index.md new file mode 100644 index 0000000..341ebec --- /dev/null +++ b/vendor/picocms/pico/content-sample/index.md @@ -0,0 +1,509 @@ +--- +Title: Welcome +Description: Pico is a stupidly simple, blazing fast, flat file CMS. +--- + +## Welcome to Pico + +Congratulations, you have successfully installed [Pico][] %version%. +%meta.description% + +## Creating Content + +Pico is a flat file CMS. This means there is no administration backend or +database to deal with. You simply create `.md` files in the `content` folder +and those files become your pages. For example, this file is called `index.md` +and is shown as the main landing page. + +When you install Pico, it comes with some sample contents that will display +until you add your own content. Simply add some `.md` files to your `content` +folder in Pico's root directory. No configuration is required, Pico will +automatically use the `content` folder as soon as you create your own +`index.md`. Just check out [Pico's sample contents][SampleContents] for an +example! + +If you create a folder within the content directory (e.g. `content/sub`) and +put an `index.md` inside it, you can access that folder at the URL +`%base_url%?sub`. If you want another page within the sub folder, simply create +a text file with the corresponding name and you will be able to access it +(e.g. `content/sub/page.md` is accessible from the URL `%base_url%?sub/page`). +Below we've shown some examples of locations and their corresponding URLs: + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Physical LocationURL
content/index.md/
content/sub.md?sub (not accessible, see below)
content/sub/index.md?sub (same as above)
content/sub/page.md?sub/page
content/theme.md?theme (hidden in menu)
content/a/very/long/url.md + ?a/very/long/url + (doesn't exist) +
+ +If a file cannot be found, the file `content/404.md` will be shown. You can add +`404.md` files to any directory. So, for example, if you wanted to use a special +error page for your blog, you could simply create `content/blog/404.md`. + +Pico strictly separates contents of your website (the Markdown files in your +`content` directory) and how these contents should be displayed (the Twig +templates in your `themes` directory). However, not every file in your `content` +directory might actually be a distinct page. For example, some themes (including +Pico's default theme) use some special "hidden" file to manage meta data (like +`_meta.md` in Pico's sample contents). Some other themes use a `_footer.md` to +represent the contents of the website's footer. The common point is the `_`: all +files and directories prefixed by a `_` in your `content` directory are hidden. +These pages can't be accessed from a web browser, Pico will show a 404 error +page instead. + +As a common practice, we recommend you to separate your contents and assets +(like images, downloads, etc.). We even deny access to your `content` directory +by default. If you want to use some assets (e.g. a image) in one of your content +files, use Pico's `assets` folder. You can then access them in your Markdown +using the %assets_url% placeholder, for example: +!\[Image Title\](%assets_url%/image.png) + +### Text File Markup + +Text files are marked up using [Markdown][] and [Markdown Extra][MarkdownExtra]. +They can also contain regular HTML. + +At the top of text files you can place a block comment and specify certain meta +attributes of the page using [YAML][] (the "YAML header"). For example: + + --- + Title: Welcome + Description: This description will go in the meta description tag + Author: Joe Bloggs + Date: 2001-04-25 + Robots: noindex,nofollow + Template: index + --- + +These values will be contained in the `{{ meta }}` variable in themes (see +below). Meta headers sometimes have a special meaning: For instance, Pico not +only passes through the `Date` meta header, but rather evaluates it to really +"understand" when this page was created. This comes into play when you want to +sort your pages not just alphabetically, but by date. Another example is the +`Template` meta header: It controls what Twig template Pico uses to display +this page (e.g. if you add `Template: blog`, Pico uses `blog.twig`). + +In an attempt to separate contents and styling, we recommend you to not use +inline CSS in your Markdown files. You should rather add appropriate CSS +classes to your theme. For example, you might want to add some CSS classes to +your theme to rule how much of the available space a image should use (e.g. +`img.small { width: 80%; }`). You can then use these CSS classes in your +Markdown files, for example: +!\[Image Title\](%assets_url%/image.png) {.small} + +There are also certain variables that you can use in your text files: + +* %site_title% - The title of your Pico site +* %base_url% - The URL to your Pico site; internal links + can be specified using %base_url%?sub/page +* %theme_url% - The URL to the currently used theme +* %assets_url% - The URL to Pico's `assets` directory +* %themes_url% - The URL to Pico's `themes` directory; + don't confuse this with %theme_url% +* %plugins_url% - The URL to Pico's `plugins` directory +* %version% - Pico's current version string (e.g. `2.0.0`) +* %meta.*% - Access any meta variable of the current + page, e.g. %meta.author% is replaced with `Joe Bloggs` +* %config.*% - Access any scalar config variable, + e.g. %config.theme% is replaced with `default` + +### Blogging + +Pico is not blogging software - but makes it very easy for you to use it as a +blog. You can find many plugins out there implementing typical blogging +features like authentication, tagging, pagination and social plugins. See the +below Plugins section for details. + +If you want to use Pico as a blogging software, you probably want to do +something like the following: + +1. Put all your blog articles in a separate `blog` folder in your `content` + directory. All these articles should have a `Date` meta header. +2. Create a `blog.md` or `blog/index.md` in your `content` directory. Add + `Template: blog-index` to the YAML header of this page. It will later show a + list of all your blog articles (see step 3). +3. Create the new Twig template `blog-index.twig` (the file name must match the + `Template` meta header from Step 2) in your theme directory. This template + probably isn't very different from your default `index.twig` (i.e. copy + `index.twig`), it will create a list of all your blog articles. Add the + following Twig snippet to `blog-index.twig` near `{{ content }}`: + ``` + {% for page in pages("blog")|sort_by("time")|reverse if not page.hidden %} +
+

{{ page.title }}

+

{{ page.date_formatted }}

+

{{ page.description }}

+
+ {% endfor %} + ``` + +## Customization + +Pico is highly customizable in two different ways: On the one hand you can +change Pico's appearance by using themes, on the other hand you can add new +functionality by using plugins. Doing the former includes changing Pico's HTML, +CSS and JavaScript, the latter mostly consists of PHP programming. + +This is all Greek to you? Don't worry, you don't have to spend time on these +techie talk - it's very easy to use one of the great themes or plugins others +developed and released to the public. Please refer to the next sections for +details. + +### Themes + +You can create themes for your Pico installation in the `themes` folder. Pico +uses [Twig][] for template rendering. You can select your theme by setting the +`theme` option in `config/config.yml` to the name of your theme folder. + +[Pico's default theme][PicoTheme] isn't really intended to be used for a +productive website, it's rather a starting point for creating your own theme. +If the default theme isn't sufficient for you, and you don't want to create +your own theme, you can use one of the great themes third-party developers and +designers created in the past. As with plugins, you can find themes in +[our Wiki][WikiThemes] and on [our website][OfficialThemes]. + +All themes must include an `index.twig` file to define the HTML structure of +the theme, and a `pico-theme.yml` to set the necessary config parameters. Just +refer to Pico's default theme as an example. You can use different templates +for different content files by specifying the `Template` meta header. Simply +add e.g. `Template: blog` to the YAML header of a content file and Pico will +use the `blog.twig` template in your theme folder to display the page. + +Below are the Twig variables that are available to use in themes. Please note +that URLs (e.g. `{{ base_url }}`) never include a trailing slash. + +* `{{ site_title }}` - Shortcut to the site title (see `config/config.yml`) +* `{{ config }}` - Contains the values you set in `config/config.yml` + (e.g. `{{ config.theme }}` becomes `default`) +* `{{ base_url }}` - The URL to your Pico site; use Twig's `link` filter to + specify internal links (e.g. `{{ "sub/page"|link }}`), + this guarantees that your link works whether URL rewriting + is enabled or not +* `{{ theme_url }}` - The URL to the currently active theme +* `{{ assets_url }}` - The URL to Pico's `assets` directory +* `{{ themes_url }}` - The URL to Pico's `themes` directory; don't confuse this + with `{{ theme_url }}` +* `{{ plugins_url }}` - The URL to Pico's `plugins` directory +* `{{ version }}` - Pico's current version string (e.g. `%version%`) +* `{{ meta }}` - Contains the meta values of the current page + * `{{ meta.title }}` - The `Title` YAML header + * `{{ meta.description }}` - The `Description` YAML header + * `{{ meta.author }}` - The `Author` YAML header + * `{{ meta.date }}` - The `Date` YAML header + * `{{ meta.date_formatted }}` - The formatted date of the page as specified + by the `date_format` parameter in your + `config/config.yml` + * `{{ meta.time }}` - The [Unix timestamp][UnixTimestamp] derived from the + `Date` YAML header + * `{{ meta.robots }}` - The `Robots` YAML header + * ... +* `{{ content }}` - The content of the current page after it has been processed + through Markdown +* `{{ previous_page }}` - The data of the previous page, relative to + `current_page` +* `{{ current_page }}` - The data of the current page; refer to the "Pages" + section below for details +* `{{ next_page }}` - The data of the next page, relative to `current_page` + +To call assets from your theme, use `{{ theme_url }}`. For instance, to include +the CSS file `themes/my_theme/example.css`, add +`` +to your `index.twig`. This works for arbitrary files in your theme's folder, +including images and JavaScript files. + +Please note that Twig escapes HTML in all strings before outputting them. So +for example, if you add `headline: My favorite color` to the +YAML header of a page and output it using `{{ meta.headline }}`, you'll end up +seeing `My favorite color` - yes, including the markup! To +actually get it parsed, you must use `{{ meta.headline|raw }}` (resulting in +the expected My **favorite** color). Notable exceptions to this +are Pico's `content` variable (e.g. `{{ content }}`), Pico's `content` filter +(e.g. `{{ "sub/page"|content }}`), and Pico's `markdown` filter, they all are +marked as HTML safe. + +#### Dealing with pages + +There are several ways to access Pico's pages list. You can access the current +page's data using the `current_page` variable, or use the `prev_page` and/or +`next_page` variables to access the respective previous/next page in Pico's +pages list. But more importantly there's the `pages()` function. No matter how +you access a page, it will always consist of the following data: + +* `{{ id }}` - The relative path to the content file (unique ID) +* `{{ url }}` - The URL to the page +* `{{ title }}` - The title of the page (`Title` YAML header) +* `{{ description }}` - The description of the page (`Description` YAML header) +* `{{ author }}` - The author of the page (`Author` YAML header) +* `{{ date }}` - The date of the page (`Date` YAML header) +* `{{ date_formatted }}` - The formatted date of the page as specified by the + `date_format` parameter in your `config/config.yml` +* `{{ time }}` - The [Unix timestamp][UnixTimestamp] derived from the page's + date +* `{{ raw_content }}` - The raw, not yet parsed contents of the page; use the + filter to get the parsed contents of a page by passing + its unique ID (e.g. `{{ "sub/page"|content }}`) +* `{{ meta }}` - The meta values of the page (see global `{{ meta }}` above) +* `{{ prev_page }}` - The data of the respective previous page +* `{{ next_page }}` - The data of the respective next page +* `{{ tree_node }}` - The page's node in Pico's page tree; check out Pico's + [page tree documentation][FeaturesPageTree] for details + +Pico's `pages()` function is the best way to access all of your site's pages. +It uses Pico's page tree to easily traverse a subset of Pico's pages list. It +allows you to filter pages and to build recursive menus (like dropdowns). By +default, `pages()` returns a list of all main pages (e.g. `content/page.md` and +`content/sub/index.md`, but not `content/sub/page.md` or `content/index.md`). +If you want to return all pages below a specific folder (e.g. `content/blog/`), +pass the folder name as first parameter to the function (e.g. `pages("blog")`). +Naturally you can also pass variables to the function. For example, to return a +list of all child pages of the current page, use `pages(current_page.id)`. +Check out the following code snippet: + +
+ {% for page in pages(current_page.id) if not page.hidden %} + + {% endfor %} +
+ +The `pages()` function is very powerful and also allows you to return not just +a page's child pages by passing the `depth` and `depthOffset` params. For +example, if you pass `pages(depthOffset=-1)`, the list will also include Pico's +main index page (i.e. `content/index.md`). This one is commonly used to create +a theme's main navigation. If you want to learn more, head over to Pico's +complete [`pages()` function documentation][FeaturesPagesFunction]. + +If you want to access the data of a particular page, use Pico's `pages` +variable. Just take `content/_meta.md` in Pico's sample contents for an +example: `content/_meta.md` contains some meta data you might want to use in +your theme. If you want to output the page's `tagline` meta value, use +`{{ pages["_meta"].meta.logo }}`. Don't ever try to use Pico's `pages` variable +as an replacement for Pico's `pages()` function. Its usage looks very similar, +it will kinda work and you might even see it being used in old themes, but be +warned: It slows down Pico. Always use Pico's `pages()` function when iterating +Pico's page list (e.g. `{% for page in pages() %}…{% endfor %}`). + +#### Twig filters and functions + +Additional to [Twig][]'s extensive list of filters, functions and tags, Pico +also provides some useful additional filters and functions to make theming +even easier. + +* Pass the unique ID of a page to the `link` filter to return the page's URL + (e.g. `{{ "sub/page"|link }}` gets `%base_url%?sub/page`). +* You can replace URL placeholders (like %base_url%) in + arbitrary strings using the `url` filter. This is helpful together with meta + variables, e.g. if you add image: %assets_url%/stock.jpg + to the YAML header of a page, `{{ meta.image|url }}` will return + `%assets_url%/stock.jpg`. +* To get the parsed contents of a page, pass its unique ID to the `content` + filter (e.g. `{{ "sub/page"|content }}`). +* You can parse any Markdown string using the `markdown` filter. For example, + you might use Markdown in the `description` meta variable and later parse it + in your theme using `{{ meta.description|markdown }}`. You can also pass meta + data as parameter to replace %meta.*% placeholders + (e.g. `{{ "Written by *%meta.author%*"|markdown(meta) }}` yields "Written by + *John Doe*"). However, please note that all contents will be wrapped inside + HTML paragraph elements (i.e. `

`). If you want to parse just a single + line of Markdown markup, pass the `singleLine` param to the `markdown` filter + (e.g. `{{ "This really is a *single* line"|markdown(singleLine=true) }}`). +* Arrays can be sorted by one of its keys using the `sort_by` filter + (e.g. `{% for page in pages|sort_by([ 'meta', 'nav' ]) %}...{% endfor %}` + iterates through all pages, ordered by the `nav` meta header; please note the + `[ 'meta', 'nav' ]` part of the example, it instructs Pico to sort by + `page.meta.nav`). Items which couldn't be sorted are moved to the bottom of + the array; you can specify `bottom` (move items to bottom; default), `top` + (move items to top), `keep` (keep original order) or `remove` (remove items) + as second parameter to change this behavior. +* You can return all values of a given array key using the `map` filter + (e.g. `{{ pages|map("title") }}` returns all page titles). +* Use the `url_param` and `form_param` Twig functions to access HTTP GET (i.e. + a URL's query string like `?some-variable=my-value`) and HTTP POST (i.e. data + of a submitted form) parameters. This allows you to implement things like + pagination, tags and categories, dynamic pages, and even more - with pure + Twig! Simply head over to our [introductory page for accessing HTTP + parameters][FeaturesHttpParams] for details. + +### Plugins + +#### Plugins for users + +Officially tested plugins can be found at http://picocms.org/plugins/, but +there are many awesome third-party plugins out there! A good start point for +discovery is [our Wiki][WikiPlugins]. + +Pico makes it very easy for you to add new features to your website using +plugins. Just like Pico, you can install plugins either using [Composer][] +(e.g. `composer require phrozenbyte/pico-file-prefixes`), or manually by +uploading the plugin's file (just for small plugins consisting of a single file, +e.g. `PicoFilePrefixes.php`) or directory (e.g. `PicoFilePrefixes`) to your +`plugins` directory. We always recommend you to use Composer whenever possible, +because it makes updating both Pico and your plugins way easier. Anyway, +depending on the plugin you want to install, you may have to go through some +more steps (e.g. specifying config variables) to make the plugin work. Thus you +should always check out the plugin's docs or `README.md` file to learn the +necessary steps. + +Plugins which were written to work with Pico 1.0 and later can be enabled and +disabled through your `config/config.yml`. If you want to e.g. disable the +`PicoDeprecated` plugin, add the following line to your `config/config.yml`: +`PicoDeprecated.enabled: false`. To force the plugin to be enabled, replace +`false` by `true`. + +#### Plugins for developers + +You're a plugin developer? We love you guys! You can find tons of information +about how to develop plugins at http://picocms.org/development/. If you've +developed a plugin before and want to upgrade it to Pico 2.0, refer to the +[upgrade section of the docs][PluginUpgrade]. + +## Config + +Configuring Pico really is stupidly simple: Just create a `config/config.yml` +to override the default Pico settings (and add your own custom settings). Take +a look at the `config/config.yml.template` for a brief overview of the +available settings and their defaults. To override a setting, simply copy the +line from `config/config.yml.template` to `config/config.yml` and set your +custom value. + +But we didn't stop there. Rather than having just a single config file, you can +use a arbitrary number of config files. Simply create a `.yml` file in Pico's +`config` dir and you're good to go. This allows you to add some structure to +your config, like a separate config file for your theme (`config/my_theme.yml`). + +Please note that Pico loads config files in a special way you should be aware +of. First of all it loads the main config file `config/config.yml`, and then +any other `*.yml` file in Pico's `config` dir in alphabetical order. The file +order is crucial: Config values which have been set already, cannot be +overwritten by a succeeding file. For example, if you set `site_title: Pico` in +`config/a.yml` and `site_title: My awesome site!` in `config/b.yml`, your site +title will be "Pico". + +Since YAML files are plain text files, users might read your Pico config by +navigating to `%base_url%/config/config.yml`. This is no problem in the first +place, but might get a problem if you use plugins that require you to store +security-relevant data in the config (like credentials). Thus you should +*always* make sure to configure your webserver to deny access to Pico's +`config` dir. Just refer to the "URL Rewriting" section below. By following the +instructions, you will not just enable URL rewriting, but also deny access to +Pico's `config` dir. + +### URL Rewriting + +Pico's default URLs (e.g. %base_url%/?sub/page) already are very user-friendly. +Additionally, Pico offers you a URL rewrite feature to make URLs even more +user-friendly (e.g. %base_url%/sub/page). Below you'll find some basic info +about how to configure your webserver proberly to enable URL rewriting. + +#### Apache + +If you're using the Apache web server, URL rewriting probably already is +enabled - try it yourself, click on the [second URL](%base_url%/sub/page). If +URL rewriting doesn't work (you're getting `404 Not Found` error messages from +Apache), please make sure to enable the [`mod_rewrite` module][ModRewrite] and +to enable `.htaccess` overrides. You might have to set the +[`AllowOverride` directive][AllowOverride] to `AllowOverride All` in your +virtual host config file or global `httpd.conf`/`apache.conf`. Assuming +rewritten URLs work, but Pico still shows no rewritten URLs, force URL +rewriting by setting `rewrite_url: true` in your `config/config.yml`. If you +rather get a `500 Internal Server Error` no matter what you do, try removing +the `Options` directive from Pico's `.htaccess` file (it's the last line). + +#### Nginx + +If you're using Nginx, you can use the following config to enable URL rewriting +(lines `5` to `8`) and denying access to Pico's internal files (lines `1` to +`3`). You'll need to adjust the path (`/pico` on lines `1`, `2`, `5` and `7`) +to match your installation directory. Additionally, you'll need to enable URL +rewriting by setting `rewrite_url: true` in your `config/config.yml`. The Nginx +config should provide the *bare minimum* you need for Pico. Nginx is a very +extensive subject. If you have any trouble, please read through our +[Nginx config docs][NginxConfig]. + +``` +location ~ ^/pico/((config|content|vendor|composer\.(json|lock|phar))(/|$)|(.+/)?\.(?!well-known(/|$))) { + try_files /pico/index.php$is_args$args =404; +} + +location /pico/ { + index index.php; + try_files $uri $uri/ /pico/index.php$is_args$args; +} +``` + +#### Lighttpd + +Pico runs smoothly on Lighttpd. You can use the following config to enable URL +rewriting (lines `6` to `9`) and denying access to Pico's internal files (lines +`1` to `4`). Make sure to adjust the path (`/pico` on lines `2`, `3` and `7`) +to match your installation directory, and let Pico know about available URL +rewriting by setting `rewrite_url: true` in your `config/config.yml`. The +config below should provide the *bare minimum* you need for Pico. + +``` +url.rewrite-once = ( + "^/pico/(config|content|vendor|composer\.(json|lock|phar))(/|$)" => "/pico/index.php", + "^/pico/(.+/)?\.(?!well-known(/|$))" => "/pico/index.php" +) + +url.rewrite-if-not-file = ( + "^/pico(/|$)" => "/pico/index.php" +) +``` + +## Documentation + +For more help have a look at the Pico documentation at http://picocms.org/docs. + +[Pico]: http://picocms.org/ +[PicoTheme]: https://github.com/picocms/pico-theme +[SampleContents]: https://github.com/picocms/Pico/tree/master/content-sample +[Markdown]: http://daringfireball.net/projects/markdown/syntax +[MarkdownExtra]: https://michelf.ca/projects/php-markdown/extra/ +[YAML]: https://en.wikipedia.org/wiki/YAML +[Twig]: http://twig.sensiolabs.org/documentation +[UnixTimestamp]: https://en.wikipedia.org/wiki/Unix_timestamp +[Composer]: https://getcomposer.org/ +[FeaturesHttpParams]: http://picocms.org/in-depth/features/http-params/ +[FeaturesPageTree]: http://picocms.org/in-depth/features/page-tree/ +[FeaturesPagesFunction]: http://picocms.org/in-depth/features/pages-function/ +[WikiThemes]: https://github.com/picocms/Pico/wiki/Pico-Themes +[WikiPlugins]: https://github.com/picocms/Pico/wiki/Pico-Plugins +[OfficialThemes]: http://picocms.org/themes/ +[PluginUpgrade]: http://picocms.org/development/#upgrade +[ModRewrite]: https://httpd.apache.org/docs/current/mod/mod_rewrite.html +[AllowOverride]: https://httpd.apache.org/docs/current/mod/core.html#allowoverride +[NginxConfig]: http://picocms.org/in-depth/nginx/ diff --git a/vendor/picocms/pico/content-sample/sub/index.md b/vendor/picocms/pico/content-sample/sub/index.md new file mode 100644 index 0000000..42edf3f --- /dev/null +++ b/vendor/picocms/pico/content-sample/sub/index.md @@ -0,0 +1,11 @@ +--- +Title: Sub Page Index +--- + +## This is a Sub Page Index + +This is `index.md` in the `sub` folder. + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultricies tristique nulla et mattis. Phasellus id massa eget nisl congue blandit sit amet id ligula. Praesent et nulla eu augue tempus sagittis. Mauris faucibus nibh et nibh cursus in vestibulum sapien egestas. Curabitur ut lectus tortor. Sed ipsum eros, egestas ut eleifend non, elementum vitae eros. Mauris felis diam, pellentesque vel lacinia ac, dictum a nunc. Mauris mattis nunc sed mi sagittis et facilisis tortor volutpat. Etiam tincidunt urna mattis erat placerat placerat ac eu tellus. Ut nec velit id nisl tincidunt vehicula id a metus. Pellentesque erat neque, faucibus id ultricies vel, mattis in ante. Donec lobortis, mauris id congue scelerisque, diam nisl accumsan orci, condimentum porta est magna vel arcu. Curabitur varius ante dui. Vivamus sit amet ante ac diam ullamcorper sodales sed a odio. + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultricies tristique nulla et mattis. Phasellus id massa eget nisl congue blandit sit amet id ligula. Praesent et nulla eu augue tempus sagittis. Mauris faucibus nibh et nibh cursus in vestibulum sapien egestas. Curabitur ut lectus tortor. Sed ipsum eros, egestas ut eleifend non, elementum vitae eros. Mauris felis diam, pellentesque vel lacinia ac, dictum a nunc. Mauris mattis nunc sed mi sagittis et facilisis tortor volutpat. Etiam tincidunt urna mattis erat placerat placerat ac eu tellus. Ut nec velit id nisl tincidunt vehicula id a metus. Pellentesque erat neque, faucibus id ultricies vel, mattis in ante. Donec lobortis, mauris id congue scelerisque, diam nisl accumsan orci, condimentum porta est magna vel arcu. Curabitur varius ante dui. Vivamus sit amet ante ac diam ullamcorper sodales sed a odio. \ No newline at end of file diff --git a/vendor/picocms/pico/content-sample/sub/page.md b/vendor/picocms/pico/content-sample/sub/page.md new file mode 100644 index 0000000..95d67bd --- /dev/null +++ b/vendor/picocms/pico/content-sample/sub/page.md @@ -0,0 +1,11 @@ +--- +Title: Sub Page +--- + +## This is a Sub Page + +This is `page.md` in the `sub` folder. + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultricies tristique nulla et mattis. Phasellus id massa eget nisl congue blandit sit amet id ligula. Praesent et nulla eu augue tempus sagittis. Mauris faucibus nibh et nibh cursus in vestibulum sapien egestas. Curabitur ut lectus tortor. Sed ipsum eros, egestas ut eleifend non, elementum vitae eros. Mauris felis diam, pellentesque vel lacinia ac, dictum a nunc. Mauris mattis nunc sed mi sagittis et facilisis tortor volutpat. Etiam tincidunt urna mattis erat placerat placerat ac eu tellus. Ut nec velit id nisl tincidunt vehicula id a metus. Pellentesque erat neque, faucibus id ultricies vel, mattis in ante. Donec lobortis, mauris id congue scelerisque, diam nisl accumsan orci, condimentum porta est magna vel arcu. Curabitur varius ante dui. Vivamus sit amet ante ac diam ullamcorper sodales sed a odio. + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultricies tristique nulla et mattis. Phasellus id massa eget nisl congue blandit sit amet id ligula. Praesent et nulla eu augue tempus sagittis. Mauris faucibus nibh et nibh cursus in vestibulum sapien egestas. Curabitur ut lectus tortor. Sed ipsum eros, egestas ut eleifend non, elementum vitae eros. Mauris felis diam, pellentesque vel lacinia ac, dictum a nunc. Mauris mattis nunc sed mi sagittis et facilisis tortor volutpat. Etiam tincidunt urna mattis erat placerat placerat ac eu tellus. Ut nec velit id nisl tincidunt vehicula id a metus. Pellentesque erat neque, faucibus id ultricies vel, mattis in ante. Donec lobortis, mauris id congue scelerisque, diam nisl accumsan orci, condimentum porta est magna vel arcu. Curabitur varius ante dui. Vivamus sit amet ante ac diam ullamcorper sodales sed a odio. \ No newline at end of file diff --git a/vendor/picocms/pico/content-sample/theme.md b/vendor/picocms/pico/content-sample/theme.md new file mode 100644 index 0000000..a11aaa1 --- /dev/null +++ b/vendor/picocms/pico/content-sample/theme.md @@ -0,0 +1,195 @@ +--- +title: Theme Styling Test +hidden: true +--- + +Theme Styling Test +================== + +This is `theme.md` in Pico's content directory. This page doesn't show up in the website's menu due to `hidden: true` in the page's YAML header. The purpose of this page is to aid theme development - below you'll find basically every format that is possible with Markdown. If you develop a theme, you should make sure that all examples below show decent. + +Text +---- + +**Lorem ipsum dolor sit amet,** consectetur adipisici elit, *sed eiusmod tempor* incidunt ut labore et dolore magna aliqua.[^1] ~~Ut enim ad minim veniam,~~ quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat.[^2] [Quis aute iure reprehenderit][Link] in voluptate velit esse cillum dolore eu fugiat nulla pariatur. `Excepteur` sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +[![Pico Logo](data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSI0MDAiIGhlaWdodD0iNDAwIiB2aWV3Qm94PSIwIDAgNDAwIDQwMCI+PHBhdGggZD0ibTI5OC40IDE5NC43cTAtMTQuMTUtLjgtMzEuMmwtLjg1LTE0LjI1aC01MS4wNXY4OS45NWw4IDEuMXE5LjYgMS4wNSAxNy42IDEuMDUgNy45NSAwIDE3LjUtMS4wNSA0LjgtLjU1IDcuOTUtMS4xIDEuNjUtMjIuMiAxLjY1LTQ0LjVtLTY5Ljc1LTQ1LjhoLTQ5LjN2MTgyLjQ1bDcuNy44NXE5LjMuOCAxNyAuOCAxMi4zIDAgMjQuNi0xLjY1eiIgZmlsbD0iIzJlYWU5YiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTM4Ljg1IC00MC45NSkiLz48L3N2Zz4K)](%base_url% "Pico Logo") {.image .small .float-right} + +Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + +Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. + +Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. + +Headings +-------- + +# h1 + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +## h2 + +Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + +### h3 + +Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. + +#### h4 + +Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. + +##### h5 + +Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. + +###### h6 + +At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. + +Horizontal line +--------------- + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +--- + +Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + +List +---- + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +* Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. + 1. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + 2. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. + 3. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. +* Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. + - Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + - Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. + 1. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. + 2. At vero eos et accusam et justo duo dolores et ea rebum. + 1. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet + 2. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. + 3. At vero eos et accusam et justo duo dolores et ea rebum. + +Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, At accusam aliquyam diam diam dolore dolores duo eirmod eos erat, et nonumy sed tempor et et invidunt justo labore Stet clita ea et gubergren, kasd magna no rebum. sanctus sea sed takimata ut vero voluptua. est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat. + +Definition list +--------------- + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +Duis autem +: Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. + +Lorem ipsum dolor sit amet +: Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + +Ut wisi enim ad minim veniam +: Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. +: Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. + +Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. + +Blockquote +---------- + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +> Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse +> molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero +> eros et accumsan et iusto odio dignissim qui blandit praesent luptatum +> zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum +> dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod +> tincidunt ut laoreet dolore magna aliquam erat volutpat. +> +> > Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit +> > lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure +> > dolor in hendrerit in vulputate velit esse molestie consequat, vel illum +> > dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio +> > dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te +> > feugait nulla facilisi. +> +> Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet +> doming id quod mazim placerat facer possim assum. Lorem ipsum dolor sit amet, +> consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut +> laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, +> quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex +> ea commodo consequat. + +Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. + +Code block +---------- + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +``` + + + + This is a title + + +

Hello world!

+ + +``` + +Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + +Table +----- + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +Lorem ipsum | Duis autem vel eum | Ut wisi enim ad minim veniam +----------- | ------------------ | ---------------------------- +**Duis autem vel eum iriure dolor** in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. | *Lorem ipsum dolor sit amet,* consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. | ~~Ut wisi enim ad minim veniam,~~ quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. +[Duis autem vel eum iriure dolor][Link] in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. | `Nam liber tempor` cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. | Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. +Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. | | Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis. + +At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. + +Forms +----- + +Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. + +
+ Legend + + + + +
+ +
+ + + +
+
+
+ +
+ +Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. + +*[Lorem ipsum]: Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. + +[Link]: %base_url% "Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat." + +[^1]: Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. +[^2]: Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. diff --git a/vendor/picocms/pico/index.php b/vendor/picocms/pico/index.php new file mode 100644 index 0000000..0d13d6d --- /dev/null +++ b/vendor/picocms/pico/index.php @@ -0,0 +1,40 @@ + + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +// load dependencies +if (is_file(__DIR__ . '/vendor/autoload.php')) { + // composer root package + require_once(__DIR__ . '/vendor/autoload.php'); +} elseif (is_file(__DIR__ . '/../../../vendor/autoload.php')) { + // composer dependency package + require_once(__DIR__ . '/../../../vendor/autoload.php'); +} else { + die( + "Cannot find 'vendor/autoload.php'. If you're using a composer-based Pico install, run `composer install`. " + . "If you're rather trying to use one of Pico's pre-built release packages, make sure to download Pico's " + . "latest release package named 'pico-release-v*.tar.gz' (don't download a source code package)." + ); +} + +// instance Pico +$pico = new Pico( + __DIR__, // root dir + 'config/', // config dir + 'plugins/', // plugins dir + 'themes/' // themes dir +); + +// override configuration? +//$pico->setConfig(array()); + +// run application +echo $pico->run(); diff --git a/vendor/picocms/pico/index.php.dist b/vendor/picocms/pico/index.php.dist new file mode 100644 index 0000000..a1f981d --- /dev/null +++ b/vendor/picocms/pico/index.php.dist @@ -0,0 +1,39 @@ + + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +// check PHP platform requirements +if (PHP_VERSION_ID < 50306) { + die('Pico requires PHP 5.3.6 or above to run'); +} +if (!extension_loaded('dom')) { + die("Pico requires the PHP extension 'dom' to run"); +} +if (!extension_loaded('mbstring')) { + die("Pico requires the PHP extension 'mbstring' to run"); +} + +// load dependencies +require_once(__DIR__ . '/vendor/autoload.php'); + +// instance Pico +$pico = new Pico( + __DIR__, // root dir + 'config/', // config dir + 'plugins/', // plugins dir + 'themes/' // themes dir +); + +// override configuration? +//$pico->setConfig(array()); + +// run application +echo $pico->run(); diff --git a/vendor/picocms/pico/lib/AbstractPicoPlugin.php b/vendor/picocms/pico/lib/AbstractPicoPlugin.php new file mode 100644 index 0000000..b732ac2 --- /dev/null +++ b/vendor/picocms/pico/lib/AbstractPicoPlugin.php @@ -0,0 +1,358 @@ + + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +/** + * Abstract class to extend from when implementing a Pico plugin + * + * Please refer to {@see PicoPluginInterface} for more information about how + * to develop a plugin for Pico. + * + * @see PicoPluginInterface + * + * @author Daniel Rudolf + * @link http://picocms.org + * @license http://opensource.org/licenses/MIT The MIT License + * @version 2.1 + */ +abstract class AbstractPicoPlugin implements PicoPluginInterface +{ + /** + * Current instance of Pico + * + * @see PicoPluginInterface::getPico() + * @var Pico + */ + protected $pico; + + /** + * Boolean indicating if this plugin is enabled (TRUE) or disabled (FALSE) + * + * @see PicoPluginInterface::isEnabled() + * @see PicoPluginInterface::setEnabled() + * @var bool|null + */ + protected $enabled; + + /** + * Boolean indicating if this plugin was ever enabled/disabled manually + * + * @see PicoPluginInterface::isStatusChanged() + * @var bool + */ + protected $statusChanged = false; + + /** + * Boolean indicating whether this plugin matches Pico's API version + * + * @see AbstractPicoPlugin::checkCompatibility() + * @var bool|null + */ + protected $nativePlugin; + + /** + * List of plugins which this plugin depends on + * + * @see AbstractPicoPlugin::checkDependencies() + * @see PicoPluginInterface::getDependencies() + * @var string[] + */ + protected $dependsOn = array(); + + /** + * List of plugin which depend on this plugin + * + * @see AbstractPicoPlugin::checkDependants() + * @see PicoPluginInterface::getDependants() + * @var object[]|null + */ + protected $dependants; + + /** + * Constructs a new instance of a Pico plugin + * + * @param Pico $pico current instance of Pico + */ + public function __construct(Pico $pico) + { + $this->pico = $pico; + } + + /** + * {@inheritDoc} + */ + public function handleEvent($eventName, array $params) + { + // plugins can be enabled/disabled using the config + if ($eventName === 'onConfigLoaded') { + $this->configEnabled(); + } + + if ($this->isEnabled() || ($eventName === 'onPluginsLoaded')) { + if (method_exists($this, $eventName)) { + call_user_func_array(array($this, $eventName), $params); + } + } + } + + /** + * Enables or disables this plugin depending on Pico's config + */ + protected function configEnabled() + { + $pluginEnabled = $this->getPico()->getConfig(get_called_class() . '.enabled'); + if ($pluginEnabled !== null) { + $this->setEnabled($pluginEnabled); + } else { + $pluginEnabled = $this->getPluginConfig('enabled'); + if ($pluginEnabled !== null) { + $this->setEnabled($pluginEnabled); + } elseif ($this->enabled) { + $this->setEnabled(true, true, true); + } elseif ($this->enabled === null) { + // make sure dependencies are already fulfilled, + // otherwise the plugin needs to be enabled manually + try { + $this->setEnabled(true, false, true); + } catch (RuntimeException $e) { + $this->enabled = false; + } + } + } + } + + /** + * {@inheritDoc} + */ + public function setEnabled($enabled, $recursive = true, $auto = false) + { + $this->statusChanged = (!$this->statusChanged) ? !$auto : true; + $this->enabled = (bool) $enabled; + + if ($enabled) { + $this->checkCompatibility(); + $this->checkDependencies($recursive); + } else { + $this->checkDependants($recursive); + } + } + + /** + * {@inheritDoc} + */ + public function isEnabled() + { + return $this->enabled; + } + + /** + * {@inheritDoc} + */ + public function isStatusChanged() + { + return $this->statusChanged; + } + + /** + * {@inheritDoc} + */ + public function getPico() + { + return $this->pico; + } + + /** + * Returns either the value of the specified plugin config variable or + * the config array + * + * @param string $configName optional name of a config variable + * @param mixed $default optional default value to return when the + * named config variable doesn't exist + * + * @return mixed if no name of a config variable has been supplied, the + * plugin's config array is returned; otherwise it returns either the + * value of the named config variable, or, if the named config variable + * doesn't exist, the provided default value or NULL + */ + public function getPluginConfig($configName = null, $default = null) + { + $pluginConfig = $this->getPico()->getConfig(get_called_class(), array()); + + if ($configName === null) { + return $pluginConfig; + } + + return isset($pluginConfig[$configName]) ? $pluginConfig[$configName] : $default; + } + + /** + * Passes all not satisfiable method calls to Pico + * + * @see PicoPluginInterface::getPico() + * + * @deprecated 2.1.0 + * + * @param string $methodName name of the method to call + * @param array $params parameters to pass + * + * @return mixed return value of the called method + */ + public function __call($methodName, array $params) + { + if (method_exists($this->getPico(), $methodName)) { + return call_user_func_array(array($this->getPico(), $methodName), $params); + } + + throw new BadMethodCallException( + 'Call to undefined method ' . get_class($this->getPico()) . '::' . $methodName . '() ' + . 'through ' . get_called_class() . '::__call()' + ); + } + + /** + * Enables all plugins which this plugin depends on + * + * @see PicoPluginInterface::getDependencies() + * + * @param bool $recursive enable required plugins automatically + * + * @throws RuntimeException thrown when a dependency fails + */ + protected function checkDependencies($recursive) + { + foreach ($this->getDependencies() as $pluginName) { + try { + $plugin = $this->getPico()->getPlugin($pluginName); + } catch (RuntimeException $e) { + throw new RuntimeException( + "Unable to enable plugin '" . get_called_class() . "': " + . "Required plugin '" . $pluginName . "' not found" + ); + } + + // plugins which don't implement PicoPluginInterface are always enabled + if (($plugin instanceof PicoPluginInterface) && !$plugin->isEnabled()) { + if ($recursive) { + if (!$plugin->isStatusChanged()) { + $plugin->setEnabled(true, true, true); + } else { + throw new RuntimeException( + "Unable to enable plugin '" . get_called_class() . "': " + . "Required plugin '" . $pluginName . "' was disabled manually" + ); + } + } else { + throw new RuntimeException( + "Unable to enable plugin '" . get_called_class() . "': " + . "Required plugin '" . $pluginName . "' is disabled" + ); + } + } + } + } + + /** + * {@inheritDoc} + */ + public function getDependencies() + { + return (array) $this->dependsOn; + } + + /** + * Disables all plugins which depend on this plugin + * + * @see PicoPluginInterface::getDependants() + * + * @param bool $recursive disabled dependant plugins automatically + * + * @throws RuntimeException thrown when a dependency fails + */ + protected function checkDependants($recursive) + { + $dependants = $this->getDependants(); + if ($dependants) { + if ($recursive) { + foreach ($this->getDependants() as $pluginName => $plugin) { + if ($plugin->isEnabled()) { + if (!$plugin->isStatusChanged()) { + $plugin->setEnabled(false, true, true); + } else { + throw new RuntimeException( + "Unable to disable plugin '" . get_called_class() . "': " + . "Required by manually enabled plugin '" . $pluginName . "'" + ); + } + } + } + } else { + $dependantsList = 'plugin' . ((count($dependants) > 1) ? 's' : '') . ' ' + . "'" . implode("', '", array_keys($dependants)) . "'"; + throw new RuntimeException( + "Unable to disable plugin '" . get_called_class() . "': " + . "Required by " . $dependantsList + ); + } + } + } + + /** + * {@inheritDoc} + */ + public function getDependants() + { + if ($this->dependants === null) { + $this->dependants = array(); + foreach ($this->getPico()->getPlugins() as $pluginName => $plugin) { + // only plugins which implement PicoPluginInterface support dependencies + if ($plugin instanceof PicoPluginInterface) { + $dependencies = $plugin->getDependencies(); + if (in_array(get_called_class(), $dependencies)) { + $this->dependants[$pluginName] = $plugin; + } + } + } + } + + return $this->dependants; + } + + /** + * Checks compatibility with Pico's API version + * + * Pico automatically adds a dependency to {@see PicoDeprecated} when the + * plugin's API is older than Pico's API. {@see PicoDeprecated} furthermore + * throws a exception if it can't provide compatibility in such cases. + * However, we still have to decide whether this plugin is compatible to + * newer API versions, what requires some special (version specific) + * precaution and is therefore usually not the case. + * + * @throws RuntimeException thrown when the plugin's and Pico's API aren't + * compatible + */ + protected function checkCompatibility() + { + if ($this->nativePlugin === null) { + $picoClassName = get_class($this->pico); + $picoApiVersion = defined($picoClassName . '::API_VERSION') ? $picoClassName::API_VERSION : 1; + $pluginApiVersion = defined('static::API_VERSION') ? static::API_VERSION : 1; + + $this->nativePlugin = ($pluginApiVersion === $picoApiVersion); + + if (!$this->nativePlugin && ($pluginApiVersion > $picoApiVersion)) { + throw new RuntimeException( + "Unable to enable plugin '" . get_called_class() . "': The plugin's API (version " + . $pluginApiVersion . ") isn't compatible with Pico's API (version " . $picoApiVersion . ")" + ); + } + } + } +} diff --git a/vendor/picocms/pico/lib/Pico.php b/vendor/picocms/pico/lib/Pico.php new file mode 100644 index 0000000..af68379 --- /dev/null +++ b/vendor/picocms/pico/lib/Pico.php @@ -0,0 +1,2791 @@ + + * + * The file has been renamed in the past; the version control history of the + * original file applies accordingly, available from the following original + * location: + * + * + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +/** + * Pico + * + * Pico is a stupidly simple, blazing fast, flat file CMS. + * + * - Stupidly Simple: Pico makes creating and maintaining a + * website as simple as editing text files. + * - Blazing Fast: Pico is seriously lightweight and doesn't + * use a database, making it super fast. + * - No Database: Pico is a "flat file" CMS, meaning no + * database woes, no MySQL queries, nothing. + * - Markdown Formatting: Edit your website in your favourite + * text editor using simple Markdown formatting. + * - Twig Templates: Pico uses the Twig templating engine, + * for powerful and flexible themes. + * - Open Source: Pico is completely free and open source, + * released under the MIT license. + * + * See for more info. + * + * @author Gilbert Pellegrom + * @author Daniel Rudolf + * @link http://picocms.org + * @license http://opensource.org/licenses/MIT The MIT License + * @version 2.1 + */ +class Pico +{ + /** + * Pico version + * + * @var string + */ + const VERSION = '2.1.4'; + + /** + * Pico version ID + * + * @var int + */ + const VERSION_ID = 20104; + + /** + * Pico API version + * + * @var int + */ + const API_VERSION = 3; + + /** + * Sort files in alphabetical ascending order + * + * @see Pico::getFiles() + * @var int + */ + const SORT_ASC = 0; + + /** + * Sort files in alphabetical descending order + * + * @see Pico::getFiles() + * @var int + */ + const SORT_DESC = 1; + + /** + * Don't sort files + * + * @see Pico::getFiles() + * @var int + */ + const SORT_NONE = 2; + + /** + * Root directory of this Pico instance + * + * @see Pico::getRootDir() + * @var string + */ + protected $rootDir; + + /** + * Vendor directory of this Pico instance + * + * @see Pico::getVendorDir() + * @var string + */ + protected $vendorDir; + + /** + * Config directory of this Pico instance + * + * @see Pico::getConfigDir() + * @var string + */ + protected $configDir; + + /** + * Plugins directory of this Pico instance + * + * @see Pico::getPluginsDir() + * @var string + */ + protected $pluginsDir; + + /** + * Themes directory of this Pico instance + * + * @see Pico::getThemesDir() + * @var string + */ + protected $themesDir; + + /** + * Boolean indicating whether Pico started processing yet + * + * @var bool + */ + protected $locked = false; + + /** + * List of loaded plugins + * + * @see Pico::getPlugins() + * @var object[] + */ + protected $plugins = array(); + + /** + * List of loaded plugins using the current API version + * + * @var PicoPluginInterface[] + */ + protected $nativePlugins = array(); + + /** + * Boolean indicating whether Pico loads plugins from the filesystem + * + * @see Pico::loadPlugins() + * @see Pico::loadLocalPlugins() + * @var bool + */ + protected $enableLocalPlugins = true; + + /** + * Current configuration of this Pico instance + * + * @see Pico::getConfig() + * @var array|null + */ + protected $config; + + /** + * Theme in use + * + * @see Pico::getTheme() + * @var string + */ + protected $theme; + + /** + * API version of the current theme + * + * @see Pico::getThemeApiVersion() + * @var int + */ + protected $themeApiVersion; + + /** + * Additional meta headers of the current theme + * + * @var array|null + */ + protected $themeMetaHeaders; + + /** + * Part of the URL describing the requested contents + * + * @see Pico::getRequestUrl() + * @var string|null + */ + protected $requestUrl; + + /** + * Absolute path to the content file being served + * + * @see Pico::getRequestFile() + * @var string|null + */ + protected $requestFile; + + /** + * Raw, not yet parsed contents to serve + * + * @see Pico::getRawContent() + * @var string|null + */ + protected $rawContent; + + /** + * Boolean indicating whether Pico is serving a 404 page + * + * @see Pico::is404Content() + * @var bool + */ + protected $is404Content = false; + + /** + * Symfony YAML instance used for meta header parsing + * + * @see Pico::getYamlParser() + * @var \Symfony\Component\Yaml\Parser|null + */ + protected $yamlParser; + + /** + * List of known meta headers + * + * @see Pico::getMetaHeaders() + * @var array|null + */ + protected $metaHeaders; + + /** + * Meta data of the page to serve + * + * @see Pico::getFileMeta() + * @var array|null + */ + protected $meta; + + /** + * Parsedown Extra instance used for markdown parsing + * + * @see Pico::getParsedown() + * @var Parsedown|null + */ + protected $parsedown; + + /** + * Parsed content being served + * + * @see Pico::getFileContent() + * @var string|null + */ + protected $content; + + /** + * List of known pages + * + * @see Pico::getPages() + * @var array[]|null + */ + protected $pages; + + /** + * Data of the page being served + * + * @see Pico::getCurrentPage() + * @var array|null + */ + protected $currentPage; + + /** + * Data of the previous page relative to the page being served + * + * @see Pico::getPreviousPage() + * @var array|null + */ + protected $previousPage; + + /** + * Data of the next page relative to the page being served + * + * @see Pico::getNextPage() + * @var array|null + */ + protected $nextPage; + + /** + * Tree structure of known pages + * + * @see Pico::getPageTree() + * @var array[]|null + */ + protected $pageTree; + + /** + * Twig instance used for template parsing + * + * @see Pico::getTwig() + * @var Twig_Environment|null + */ + protected $twig; + + /** + * Variables passed to the twig template + * + * @see Pico::getTwigVariables() + * @var array|null + */ + protected $twigVariables; + + /** + * Name of the Twig template to render + * + * @see Pico::getTwigTemplate() + * @var string|null + */ + protected $twigTemplate; + + /** + * Constructs a new Pico instance + * + * To carry out all the processing in Pico, call {@see Pico::run()}. + * + * @param string $rootDir root dir of this Pico instance + * @param string $configDir config dir of this Pico instance + * @param string $pluginsDir plugins dir of this Pico instance + * @param string $themesDir themes dir of this Pico instance + * @param bool $enableLocalPlugins enables (TRUE; default) or disables + * (FALSE) loading plugins from the filesystem + */ + public function __construct($rootDir, $configDir, $pluginsDir, $themesDir, $enableLocalPlugins = true) + { + $this->rootDir = rtrim($rootDir, '/\\') . '/'; + $this->vendorDir = dirname(__DIR__) . '/'; + $this->configDir = $this->getAbsolutePath($configDir); + $this->pluginsDir = $this->getAbsolutePath($pluginsDir); + $this->themesDir = $this->getAbsolutePath($themesDir); + $this->enableLocalPlugins = (bool) $enableLocalPlugins; + } + + /** + * Returns the root directory of this Pico instance + * + * @return string root directory path + */ + public function getRootDir() + { + return $this->rootDir; + } + + /** + * Returns the vendor directory of this Pico instance + * + * @return string vendor directory path + */ + public function getVendorDir() + { + return $this->vendorDir; + } + + /** + * Returns the config directory of this Pico instance + * + * @return string config directory path + */ + public function getConfigDir() + { + return $this->configDir; + } + + /** + * Returns the plugins directory of this Pico instance + * + * @return string plugins directory path + */ + public function getPluginsDir() + { + return $this->pluginsDir; + } + + /** + * Returns the themes directory of this Pico instance + * + * @return string themes directory path + */ + public function getThemesDir() + { + return $this->themesDir; + } + + /** + * Runs this Pico instance + * + * Loads plugins, evaluates the config file, does URL routing, parses + * meta headers, processes Markdown, does Twig processing and returns + * the rendered contents. + * + * @return string rendered Pico contents + * + * @throws Exception thrown when a irrecoverable error occurs + */ + public function run() + { + // check lock + if ($this->locked) { + throw new LogicException('You cannot run the same Pico instance multiple times'); + } + + // lock Pico + $this->locked = true; + + // load plugins + $this->loadPlugins(); + $this->sortPlugins(); + $this->triggerEvent('onPluginsLoaded', array($this->plugins)); + + // load config + $this->loadConfig(); + $this->triggerEvent('onConfigLoaded', array(&$this->config)); + + // check content dir + if (!is_dir($this->getConfig('content_dir'))) { + throw new RuntimeException('Invalid content directory "' . $this->getConfig('content_dir') . '"'); + } + + // load theme + $this->theme = $this->config['theme']; + $this->triggerEvent('onThemeLoading', array(&$this->theme)); + + $this->loadTheme(); + $this->triggerEvent( + 'onThemeLoaded', + array($this->theme, $this->themeApiVersion, &$this->config['theme_config']) + ); + + // evaluate request url + $this->evaluateRequestUrl(); + $this->triggerEvent('onRequestUrl', array(&$this->requestUrl)); + + // discover requested file + $this->requestFile = $this->resolveFilePath($this->requestUrl); + $this->triggerEvent('onRequestFile', array(&$this->requestFile)); + + // load raw file content + $this->triggerEvent('onContentLoading'); + + $requestedPageId = $this->getPageId($this->requestFile) ?: $this->requestFile; + $hiddenFileRegex = '/(?:^|\/)(?:_|404' . preg_quote($this->getConfig('content_ext'), '/') . '$)/'; + if (is_file($this->requestFile) && !preg_match($hiddenFileRegex, $requestedPageId)) { + $this->rawContent = $this->loadFileContent($this->requestFile); + } else { + $this->triggerEvent('on404ContentLoading'); + + $serverProtocol = !empty($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.1'; + header($serverProtocol . ' 404 Not Found'); + + $this->rawContent = $this->load404Content($this->requestFile); + $this->is404Content = true; + + $this->triggerEvent('on404ContentLoaded', array(&$this->rawContent)); + } + + $this->triggerEvent('onContentLoaded', array(&$this->rawContent)); + + // parse file meta + $this->triggerEvent('onMetaParsing'); + $this->meta = $this->parseFileMeta($this->rawContent, $this->getMetaHeaders()); + $this->triggerEvent('onMetaParsed', array(&$this->meta)); + + // parse file content + $this->triggerEvent('onContentParsing'); + + $markdown = $this->prepareFileContent($this->rawContent, $this->meta); + $this->triggerEvent('onContentPrepared', array(&$markdown)); + + $this->content = $this->parseFileContent($markdown); + $this->triggerEvent('onContentParsed', array(&$this->content)); + + // read pages + $this->triggerEvent('onPagesLoading'); + + $this->readPages(); + $this->triggerEvent('onPagesDiscovered', array(&$this->pages)); + + $this->sortPages(); + $this->triggerEvent('onPagesLoaded', array(&$this->pages)); + + $this->discoverPageSiblings(); + $this->discoverCurrentPage(); + $this->triggerEvent( + 'onCurrentPageDiscovered', + array(&$this->currentPage, &$this->previousPage, &$this->nextPage) + ); + + $this->buildPageTree(); + $this->triggerEvent('onPageTreeBuilt', array(&$this->pageTree)); + + // render template + $this->twigVariables = $this->getTwigVariables(); + $this->twigTemplate = $this->getTwigTemplate(); + $this->triggerEvent('onPageRendering', array(&$this->twigTemplate, &$this->twigVariables)); + + $output = $this->getTwig()->render($this->twigTemplate, $this->twigVariables); + $this->triggerEvent('onPageRendered', array(&$output)); + + return $output; + } + + /** + * Loads plugins from vendor/pico-plugin.php and Pico::$pluginsDir + * + * See {@see Pico::loadComposerPlugins()} for details about plugins loaded + * from `vendor/pico-plugin.php` (i.e. plugins that were installed using + * composer), and {@see Pico::loadLocalPlugins()} for details about plugins + * installed to {@see Pico::$pluginsDir}. Pico loads plugins from the + * filesystem only if {@see Pico::$enableLocalPlugins} is set to TRUE + * (this is the default). + * + * Pico always loads plugins from `vendor/pico-plugin.php` first and + * ignores conflicting plugins in {@see Pico::$pluginsDir}. + * + * The official PicoDeprecated plugin must be loaded when plugins that use + * an older API version than Pico's API version ({@see Pico::API_VERSION}) + * are loaded. + * + * Please note that Pico will change the processing order when needed to + * incorporate plugin dependencies. See {@see Pico::sortPlugins()} for + * details. + * + * @see Pico::loadPlugin() + * @see Pico::getPlugin() + * @see Pico::getPlugins() + * + * @throws RuntimeException thrown when a plugin couldn't be loaded + */ + protected function loadPlugins() + { + $composerPlugins = $this->loadComposerPlugins(); + + if ($this->enableLocalPlugins) { + $this->loadLocalPlugins($composerPlugins); + } + + if (!isset($this->plugins['PicoDeprecated']) && (count($this->plugins) !== count($this->nativePlugins))) { + throw new RuntimeException( + "Plugins using an older API than version " . static::API_VERSION . " found, " + . "but PicoDeprecated isn't loaded" + ); + } + } + + /** + * Loads plugins from vendor/pico-plugin.php + * + * This method loads all plugins installed using composer and Pico's + * `picocms/composer-installer` installer by reading the `pico-plugin.php` + * in composer's `vendor` dir. + * + * @see Pico::loadPlugins() + * @see Pico::loadLocalPlugins() + * + * @param string[] $pluginBlacklist class names of plugins not to load + * + * @return string[] installer names of the loaded plugins + * + * @throws RuntimeException thrown when a plugin couldn't be loaded + */ + protected function loadComposerPlugins(array $pluginBlacklist = array()) + { + $composerPlugins = array(); + if (is_file($this->getVendorDir() . 'vendor/pico-plugin.php')) { + // composer root package + $composerPlugins = require($this->getVendorDir() . 'vendor/pico-plugin.php') ?: array(); + } elseif (is_file($this->getVendorDir() . '../../../vendor/pico-plugin.php')) { + // composer dependency package + $composerPlugins = require($this->getVendorDir() . '../../../vendor/pico-plugin.php') ?: array(); + } + + $pluginBlacklist = array_fill_keys($pluginBlacklist, true); + + $loadedPlugins = array(); + foreach ($composerPlugins as $package => $pluginData) { + $loadedPlugins[] = $pluginData['installerName']; + + foreach ($pluginData['classNames'] as $className) { + $plugin = new $className($this); + $className = get_class($plugin); + + if (isset($this->plugins[$className]) || isset($pluginBlacklist[$className])) { + continue; + } + + if (!($plugin instanceof PicoPluginInterface)) { + throw new RuntimeException( + "Unable to load plugin '" . $className . "' via 'vendor/pico-plugin.php': " + . "Plugins installed by composer must implement 'PicoPluginInterface'" + ); + } + + $this->plugins[$className] = $plugin; + + if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) { + $this->nativePlugins[$className] = $plugin; + } + } + } + + return $loadedPlugins; + } + + /** + * Loads plugins from Pico::$pluginsDir in alphabetical order + * + * Pico tries to load plugins from `/.php` and + * `.php` only. Plugin names are treated case insensitive. + * Pico will throw a RuntimeException if it can't load a plugin. + * + * Plugin files MAY be prefixed by a number (e.g. `00-PicoDeprecated.php`) + * to indicate their processing order. Plugins without a prefix will be + * loaded last. If you want to use a prefix, you MUST NOT use the reserved + * prefixes `00` to `09`. Prefixes are completely optional, however, you + * SHOULD take the following prefix classification into consideration: + * - 10 to 19: Reserved + * - 20 to 39: Low level code helper plugins + * - 40 to 59: Plugins manipulating routing or the pages array + * - 60 to 79: Plugins hooking into template or markdown parsing + * - 80 to 99: Plugins using the `onPageRendered` event + * + * @see Pico::loadPlugins() + * @see Pico::loadComposerPlugins() + * + * @param string[] $pluginBlacklist class names of plugins not to load + * + * @throws RuntimeException thrown when a plugin couldn't be loaded + */ + protected function loadLocalPlugins(array $pluginBlacklist = array()) + { + // scope isolated require() + $includeClosure = function ($pluginFile) { + require($pluginFile); + }; + if (PHP_VERSION_ID >= 50400) { + $includeClosure = $includeClosure->bindTo(null); + } + + $pluginBlacklist = array_fill_keys($pluginBlacklist, true); + + $files = scandir($this->getPluginsDir()) ?: array(); + foreach ($files as $file) { + if ($file[0] === '.') { + continue; + } + + $className = $pluginFile = null; + if (is_dir($this->getPluginsDir() . $file)) { + $className = preg_replace('/^[0-9]+-/', '', $file); + $pluginFile = $file . '/' . $className . '.php'; + + if (!is_file($this->getPluginsDir() . $pluginFile)) { + throw new RuntimeException( + "Unable to load plugin '" . $className . "' from '" . $pluginFile . "': File not found" + ); + } + } elseif (substr($file, -4) === '.php') { + $className = preg_replace('/^[0-9]+-/', '', substr($file, 0, -4)); + $pluginFile = $file; + } else { + throw new RuntimeException("Unable to load plugin from '" . $file . "': Not a valid plugin file"); + } + + if (isset($this->plugins[$className]) || isset($pluginBlacklist[$className])) { + continue; + } + + $includeClosure($this->getPluginsDir() . $pluginFile); + + if (class_exists($className, false)) { + // class name and file name can differ regarding case sensitivity + $plugin = new $className($this); + $className = get_class($plugin); + + $this->plugins[$className] = $plugin; + + if ($plugin instanceof PicoPluginInterface) { + if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) { + $this->nativePlugins[$className] = $plugin; + } + } + } else { + throw new RuntimeException( + "Unable to load plugin '" . $className . "' from '" . $pluginFile . "': Plugin class not found" + ); + } + } + } + + /** + * Manually loads a plugin + * + * Manually loaded plugins MUST implement {@see PicoPluginInterface}. They + * are simply appended to the plugins array without any additional checks, + * so you might get unexpected results, depending on *when* you're loading + * a plugin. You SHOULD NOT load plugins after a event has been triggered + * by Pico. In-depth knowledge of Pico's inner workings is strongly advised + * otherwise, and you MUST NOT rely on {@see PicoDeprecated} to maintain + * backward compatibility in such cases. + * + * If you e.g. load a plugin after the `onPluginsLoaded` event, Pico + * doesn't guarantee the plugin's order ({@see Pico::sortPlugins()}). + * Already triggered events won't get triggered on the manually loaded + * plugin. Thus you SHOULD load plugins either before {@see Pico::run()} + * is called, or via the constructor of another plugin (i.e. the plugin's + * `__construct()` method; plugins are instanced in + * {@see Pico::loadPlugins()}). + * + * This method triggers the `onPluginManuallyLoaded` event. + * + * @see Pico::loadPlugins() + * @see Pico::getPlugin() + * @see Pico::getPlugins() + * + * @param PicoPluginInterface|string $plugin either the class name of a + * plugin to instantiate or a plugin instance + * + * @return PicoPluginInterface instance of the loaded plugin + * + * @throws RuntimeException thrown when the plugin couldn't be loaded + */ + public function loadPlugin($plugin) + { + if (!is_object($plugin)) { + $className = (string) $plugin; + if (class_exists($className)) { + $plugin = new $className($this); + } else { + throw new RuntimeException("Unable to load plugin '" . $className . "': Class not found"); + } + } + + $className = get_class($plugin); + + if (!($plugin instanceof PicoPluginInterface)) { + throw new RuntimeException( + "Unable to load plugin '" . $className . "': " + . "Manually loaded plugins must implement 'PicoPluginInterface'" + ); + } + + $this->plugins[$className] = $plugin; + + if (defined($className . '::API_VERSION') && ($className::API_VERSION >= static::API_VERSION)) { + $this->nativePlugins[$className] = $plugin; + } + + // trigger onPluginManuallyLoaded event + // the event is also triggered on the newly loaded plugin, allowing you to distinguish manual and auto loading + $this->triggerEvent('onPluginManuallyLoaded', array($plugin)); + + return $plugin; + } + + /** + * Sorts all loaded plugins using a plugin dependency topology + * + * Execution order matters: if plugin A depends on plugin B, it usually + * means that plugin B does stuff which plugin A requires. However, Pico + * loads plugins in alphabetical order, so events might get fired on + * plugin A before plugin B. + * + * Hence plugins need to be sorted. Pico sorts plugins using a dependency + * topology, this means that it moves all plugins, on which a plugin + * depends, in front of that plugin. The order isn't touched apart from + * that, so they are still sorted alphabetically, as long as this doesn't + * interfere with the dependency topology. Circular dependencies are being + * ignored; their behavior is undefiend. Missing dependencies are being + * ignored until you try to enable the dependant plugin. + * + * This method bases on Marc J. Schmidt's Topological Sort library in + * version 1.1.0, licensed under the MIT license. It uses the `ArraySort` + * implementation (class `\MJS\TopSort\Implementations\ArraySort`). + * + * @see Pico::loadPlugins() + * @see Pico::getPlugins() + * @see https://github.com/marcj/topsort.php + * Marc J. Schmidt's Topological Sort / Dependency resolver in PHP + * @see https://github.com/marcj/topsort.php/blob/1.1.0/src/Implementations/ArraySort.php + * \MJS\TopSort\Implementations\ArraySort class + */ + protected function sortPlugins() + { + $plugins = $this->plugins; + $nativePlugins = $this->nativePlugins; + $sortedPlugins = array(); + $sortedNativePlugins = array(); + $visitedPlugins = array(); + + $visitPlugin = function ($plugin) use ( + $plugins, + $nativePlugins, + &$sortedPlugins, + &$sortedNativePlugins, + &$visitedPlugins, + &$visitPlugin + ) { + $pluginName = get_class($plugin); + + // skip already visited plugins and ignore circular dependencies + if (!isset($visitedPlugins[$pluginName])) { + $visitedPlugins[$pluginName] = true; + + $dependencies = array(); + if ($plugin instanceof PicoPluginInterface) { + $dependencies = $plugin->getDependencies(); + } + if (!isset($nativePlugins[$pluginName])) { + $dependencies[] = 'PicoDeprecated'; + } + + foreach ($dependencies as $dependency) { + // ignore missing dependencies + // this is only a problem when the user tries to enable this plugin + if (isset($plugins[$dependency])) { + $visitPlugin($plugins[$dependency]); + } + } + + $sortedPlugins[$pluginName] = $plugin; + if (isset($nativePlugins[$pluginName])) { + $sortedNativePlugins[$pluginName] = $plugin; + } + } + }; + + if (isset($this->plugins['PicoDeprecated'])) { + $visitPlugin($this->plugins['PicoDeprecated']); + } + + foreach ($this->plugins as $plugin) { + $visitPlugin($plugin); + } + + $this->plugins = $sortedPlugins; + $this->nativePlugins = $sortedNativePlugins; + } + + /** + * Returns the instance of a named plugin + * + * Plugins SHOULD implement {@see PicoPluginInterface}, but you MUST NOT + * rely on it. For more information see {@see PicoPluginInterface}. + * + * @see Pico::loadPlugins() + * @see Pico::getPlugins() + * + * @param string $pluginName name of the plugin + * + * @return object instance of the plugin + * + * @throws RuntimeException thrown when the plugin wasn't found + */ + public function getPlugin($pluginName) + { + if (isset($this->plugins[$pluginName])) { + return $this->plugins[$pluginName]; + } + + throw new RuntimeException("Missing plugin '" . $pluginName . "'"); + } + + /** + * Returns all loaded plugins + * + * @see Pico::loadPlugins() + * @see Pico::getPlugin() + * + * @return object[]|null + */ + public function getPlugins() + { + return $this->plugins; + } + + /** + * Loads config.yml and any other *.yml from Pico::$configDir + * + * After loading {@path "config/config.yml"}, Pico proceeds with any other + * existing `config/*.yml` file in alphabetical order. The file order is + * crucial: Config values which have been set already, cannot be + * overwritten by a succeeding file. This is also true for arrays, i.e. + * when specifying `test: { foo: bar }` in `config/a.yml` and + * `test: { baz: 42 }` in `config/b.yml`, `{{ config.test.baz }}` will be + * undefined! + * + * @see Pico::setConfig() + * @see Pico::getConfig() + */ + protected function loadConfig() + { + // load config closure + $yamlParser = $this->getYamlParser(); + $loadConfigClosure = function ($configFile) use ($yamlParser) { + $yaml = file_get_contents($configFile); + $config = $yamlParser->parse($yaml); + return is_array($config) ? $config : array(); + }; + + // load main config file (config/config.yml) + $this->config = is_array($this->config) ? $this->config : array(); + if (is_file($this->getConfigDir() . 'config.yml')) { + $this->config += $loadConfigClosure($this->getConfigDir() . 'config.yml'); + } + + // merge $config of config/*.yml files + $configFiles = $this->getFilesGlob($this->getConfigDir() . '*.yml'); + foreach ($configFiles as $configFile) { + if ($configFile !== $this->getConfigDir() . 'config.yml') { + $this->config += $loadConfigClosure($configFile); + } + } + + // merge default config + $this->config += array( + 'site_title' => 'Pico', + 'base_url' => null, + 'rewrite_url' => null, + 'debug' => null, + 'timezone' => null, + 'locale' => null, + 'theme' => 'default', + 'theme_config' => null, + 'theme_meta' => null, + 'themes_url' => null, + 'twig_config' => null, + 'date_format' => '%D %T', + 'pages_order_by_meta' => 'author', + 'pages_order_by' => 'alpha', + 'pages_order' => 'asc', + 'content_dir' => null, + 'content_ext' => '.md', + 'content_config' => null, + 'assets_dir' => 'assets/', + 'assets_url' => null, + 'plugins_url' => null + ); + + if (!$this->config['base_url']) { + $this->config['base_url'] = $this->getBaseUrl(); + } else { + $this->config['base_url'] = rtrim($this->config['base_url'], '/') . '/'; + } + + if ($this->config['rewrite_url'] === null) { + $this->config['rewrite_url'] = $this->isUrlRewritingEnabled(); + } + + if ($this->config['debug'] === null) { + $this->config['debug'] = $this->isDebugModeEnabled(); + } + + if (!$this->config['timezone']) { + // explicitly set a default timezone to prevent a E_NOTICE when no timezone is set; + // the `date_default_timezone_get()` function always returns a timezone, at least UTC + $this->config['timezone'] = @date_default_timezone_get(); + } + date_default_timezone_set($this->config['timezone']); + + if ($this->config['locale'] !== null) { + setlocale(LC_ALL, $this->config['locale']); + } + + if (!$this->config['plugins_url']) { + $this->config['plugins_url'] = $this->getUrlFromPath($this->getPluginsDir()); + } else { + $this->config['plugins_url'] = $this->getAbsoluteUrl($this->config['plugins_url']); + } + + if (!$this->config['themes_url']) { + $this->config['themes_url'] = $this->getUrlFromPath($this->getThemesDir()); + } else { + $this->config['themes_url'] = $this->getAbsoluteUrl($this->config['themes_url']); + } + + if (!$this->config['content_dir']) { + // try to guess the content directory + if (is_file($this->getRootDir() . 'content/index' . $this->config['content_ext'])) { + $this->config['content_dir'] = $this->getRootDir() . 'content/'; + } elseif (is_file($this->getRootDir() . 'content-sample/index' . $this->config['content_ext'])) { + $this->config['content_dir'] = $this->getRootDir() . 'content-sample/'; + } else { + $this->config['content_dir'] = $this->getVendorDir() . 'content-sample/'; + } + } else { + $this->config['content_dir'] = $this->getAbsolutePath($this->config['content_dir']); + } + + $defaultContentConfig = array('extra' => true, 'breaks' => false, 'escape' => false, 'auto_urls' => true); + if (!is_array($this->config['content_config'])) { + $this->config['content_config'] = $defaultContentConfig; + } else { + $this->config['content_config'] += $defaultContentConfig; + } + + if (!$this->config['assets_dir']) { + $this->config['assets_dir'] = $this->getRootDir() . 'assets/'; + } else { + $this->config['assets_dir'] = $this->getAbsolutePath($this->config['assets_dir']); + } + + if (!$this->config['assets_url']) { + $this->config['assets_url'] = $this->getUrlFromPath($this->config['assets_dir']); + } else { + $this->config['assets_url'] = $this->getAbsoluteUrl($this->config['assets_url']); + } + } + + /** + * Sets Pico's config before calling Pico::run() + * + * This method allows you to modify Pico's config without creating a + * {@path "config/config.yml"} or changing some of its variables before + * Pico starts processing. + * + * You can call this method between {@see Pico::__construct()} and + * {@see Pico::run()} only. Options set with this method cannot be + * overwritten by {@path "config/config.yml"}. + * + * @see Pico::loadConfig() + * @see Pico::getConfig() + * + * @param array $config array with config variables + * + * @throws LogicException thrown if Pico already started processing + */ + public function setConfig(array $config) + { + if ($this->locked) { + throw new LogicException("You cannot modify Pico's config after processing has started"); + } + + $this->config = $config; + } + + /** + * Returns either the value of the specified config variable or + * the config array + * + * @see Pico::setConfig() + * @see Pico::loadConfig() + * + * @param string $configName optional name of a config variable + * @param mixed $default optional default value to return when the + * named config variable doesn't exist + * + * @return mixed if no name of a config variable has been supplied, the + * config array is returned; otherwise it returns either the value of + * the named config variable, or, if the named config variable doesn't + * exist, the provided default value or NULL + */ + public function getConfig($configName = null, $default = null) + { + if ($configName !== null) { + return isset($this->config[$configName]) ? $this->config[$configName] : $default; + } else { + return $this->config; + } + } + + /** + * Loads a theme's config file (pico-theme.yml) + * + * @see Pico::getTheme() + * @see Pico::getThemeApiVersion() + */ + protected function loadTheme() + { + $themeConfig = array(); + + // load theme config from pico-theme.yml + $themeConfigFile = $this->getThemesDir() . $this->getTheme() . '/pico-theme.yml'; + if (is_file($themeConfigFile)) { + $themeConfigYaml = file_get_contents($themeConfigFile); + $themeConfig = $this->getYamlParser()->parse($themeConfigYaml); + $themeConfig = is_array($themeConfig) ? $themeConfig : array(); + } + + $themeConfig += array( + 'api_version' => null, + 'meta' => array(), + 'twig_config' => array() + ); + + // theme API version + if (is_int($themeConfig['api_version']) || preg_match('/^[0-9]+$/', $themeConfig['api_version'])) { + $this->themeApiVersion = (int) $themeConfig['api_version']; + } else { + $this->themeApiVersion = 0; + } + + unset($themeConfig['api_version']); + + // twig config + $themeTwigConfig = array('autoescape' => 'html', 'strict_variables' => false, 'charset' => 'utf-8'); + foreach ($themeTwigConfig as $key => $_) { + if (isset($themeConfig['twig_config'][$key])) { + $themeTwigConfig[$key] = $themeConfig['twig_config'][$key]; + } + } + + unset($themeConfig['twig_config']); + + $defaultTwigConfig = array('debug' => null, 'cache' => false, 'auto_reload' => null); + $this->config['twig_config'] = is_array($this->config['twig_config']) ? $this->config['twig_config'] : array(); + $this->config['twig_config'] = array_merge($defaultTwigConfig, $themeTwigConfig, $this->config['twig_config']); + + if ($this->config['twig_config']['autoescape'] === true) { + $this->config['twig_config']['autoescape'] = 'html'; + } + if ($this->config['twig_config']['cache']) { + $this->config['twig_config']['cache'] = $this->getAbsolutePath($this->config['twig_config']['cache']); + } + if ($this->config['twig_config']['debug'] === null) { + $this->config['twig_config']['debug'] = $this->isDebugModeEnabled(); + } + + // meta headers + $this->themeMetaHeaders = is_array($themeConfig['meta']) ? $themeConfig['meta'] : array(); + unset($themeConfig['meta']); + + // theme config + if (!is_array($this->config['theme_config'])) { + $this->config['theme_config'] = $themeConfig; + } else { + $this->config['theme_config'] += $themeConfig; + } + + // check for theme compatibility + if (!isset($this->plugins['PicoDeprecated']) && ($this->themeApiVersion < static::API_VERSION)) { + throw new RuntimeException( + 'Current theme "' . $this->theme . '" uses API version ' . $this->themeApiVersion . ', but Pico ' + . 'provides API version ' . static::API_VERSION . ' and PicoDeprecated isn\'t loaded' + ); + } + } + + /** + * Returns the name of the current theme + * + * @see Pico::loadTheme() + * @see Pico::getThemeApiVersion() + * + * @return string + */ + public function getTheme() + { + return $this->theme; + } + + /** + * Returns the API version of the current theme + * + * @see Pico::loadTheme() + * @see Pico::getTheme() + * + * @return int + */ + public function getThemeApiVersion() + { + return $this->themeApiVersion; + } + + /** + * Evaluates the requested URL + * + * Pico uses the `QUERY_STRING` routing method (e.g. `/pico/?sub/page`) + * to support SEO-like URLs out-of-the-box with any webserver. You can + * still setup URL rewriting to basically remove the `?` from URLs. + * However, URL rewriting requires some special configuration of your + * webserver, but this should be "basic work" for any webmaster... + * + * With Pico 1.0 you had to setup URL rewriting (e.g. using `mod_rewrite` + * on Apache) in a way that rewritten URLs follow the `QUERY_STRING` + * principles. Starting with version 2.0, Pico additionally supports the + * `REQUEST_URI` routing method, what allows you to simply rewrite all + * requests to just `index.php`. Pico then reads the requested page from + * the `REQUEST_URI` environment variable provided by the webserver. + * Please note that `QUERY_STRING` takes precedence over `REQUEST_URI`. + * + * Pico 0.9 and older required Apache with `mod_rewrite` enabled, thus old + * plugins, templates and contents may require you to enable URL rewriting + * to work. If you're upgrading from Pico 0.9, you will probably have to + * update your rewriting rules. + * + * We recommend you to use the `link` filter in templates to create + * internal links, e.g. `{{ "sub/page"|link }}` is equivalent to + * `{{ base_url }}/sub/page` and `{{ base_url }}?sub/page`, depending on + * enabled URL rewriting. In content files you can use the `%base_url%` + * variable; e.g. `%base_url%?sub/page` will be replaced accordingly. + * + * Heads up! Pico always interprets the first parameter as name of the + * requested page (provided that the parameter has no value). According to + * that you MUST NOT call Pico with a parameter without value as first + * parameter (e.g. http://example.com/pico/?someBooleanParam), otherwise + * Pico interprets `someBooleanParam` as name of the requested page. Use + * `/pico/?someBooleanParam=` or `/pico/?index&someBooleanParam` instead. + * + * @see Pico::getRequestUrl() + */ + protected function evaluateRequestUrl() + { + // use QUERY_STRING; e.g. /pico/?sub/page + $pathComponent = isset($_SERVER['QUERY_STRING']) ? $_SERVER['QUERY_STRING'] : ''; + if ($pathComponent) { + $pathComponent = strstr($pathComponent, '&', true) ?: $pathComponent; + if (strpos($pathComponent, '=') === false) { + $this->requestUrl = trim(rawurldecode($pathComponent), '/'); + } + } + + // use REQUEST_URI (requires URL rewriting); e.g. /pico/sub/page + if (($this->requestUrl === null) && $this->isUrlRewritingEnabled()) { + $scriptName = isset($_SERVER['SCRIPT_NAME']) ? $_SERVER['SCRIPT_NAME'] : '/index.php'; + + $basePath = dirname($scriptName); + $basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/'; + $basePathLength = strlen($basePath); + + $requestUri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ''; + if ($requestUri && (substr($requestUri, 0, $basePathLength) === $basePath)) { + $requestUri = substr($requestUri, $basePathLength); + if ($requestUri && (($queryStringPos = strpos($requestUri, '?')) !== false)) { + $requestUri = substr($requestUri, 0, $queryStringPos); + } + if ($requestUri && ($requestUri !== basename($scriptName))) { + $this->requestUrl = rtrim(rawurldecode($requestUri), '/'); + } + } + } + + if ($this->requestUrl === null) { + $this->requestUrl = ''; + } + } + + /** + * Returns the URL where a user requested the page + * + * @see Pico::evaluateRequestUrl() + * + * @return string|null request URL + */ + public function getRequestUrl() + { + return $this->requestUrl; + } + + /** + * Resolves a given file path to its corresponding content file + * + * This method also prevents `content_dir` breakouts using malicious + * request URLs. We don't use `realpath()`, because we neither want to + * check for file existance, nor prohibit symlinks which intentionally + * point to somewhere outside the `content_dir` folder. It is STRONGLY + * RECOMMENDED to use PHP's `open_basedir` feature - always, not just + * with Pico! + * + * @see Pico::getRequestFile() + * + * @param string $requestUrl path name (likely from a URL) to resolve + * + * @return string path to the resolved content file + */ + public function resolveFilePath($requestUrl) + { + $contentDir = $this->getConfig('content_dir'); + $contentExt = $this->getConfig('content_ext'); + + if (!$requestUrl) { + return $contentDir . 'index' . $contentExt; + } else { + // normalize path and prevent content_dir breakouts + $requestFile = $this->getNormalizedPath($requestUrl, false, false); + + // discover the content file to serve + if (!$requestFile) { + return $contentDir . 'index' . $contentExt; + } elseif (is_dir($contentDir . $requestFile)) { + // if no index file is found, try a accordingly named file in the previous dir + // if this file doesn't exist either, show the 404 page, but assume the index + // file as being requested (maintains backward compatibility to Pico < 1.0) + $indexFile = $contentDir . $requestFile . '/index' . $contentExt; + if (is_file($indexFile) || !is_file($contentDir . $requestFile . $contentExt)) { + return $indexFile; + } + } + return $contentDir . $requestFile . $contentExt; + } + } + + /** + * Returns the absolute path to the content file to serve + * + * @see Pico::resolveFilePath() + * + * @return string|null file pat + */ + public function getRequestFile() + { + return $this->requestFile; + } + + /** + * Returns the raw contents of a file + * + * @see Pico::getRawContent() + * + * @param string $file file path + * + * @return string raw contents of the file + */ + public function loadFileContent($file) + { + return file_get_contents($file); + } + + /** + * Returns the raw contents of the first found 404 file when traversing + * up from the directory the requested file is in + * + * If no suitable `404.md` is found, fallback to a built-in error message. + * + * @see Pico::getRawContent() + * + * @param string $file path to requested (but not existing) file + * + * @return string raw contents of the 404 file + */ + public function load404Content($file) + { + $contentDir = $this->getConfig('content_dir'); + $contentDirLength = strlen($contentDir); + $contentExt = $this->getConfig('content_ext'); + + if (substr($file, 0, $contentDirLength) === $contentDir) { + $errorFileDir = substr($file, $contentDirLength); + + while ($errorFileDir !== '.') { + $errorFileDir = dirname($errorFileDir); + $errorFile = $errorFileDir . '/404' . $contentExt; + + if (is_file($contentDir . $errorFile)) { + return $this->loadFileContent($contentDir . $errorFile); + } + } + } elseif (is_file($contentDir . '404' . $contentExt)) { + // provided that the requested file is not in the regular + // content directory, fallback to Pico's global `404.md` + return $this->loadFileContent($contentDir . '404' . $contentExt); + } + + // fallback to built-in error message + $rawErrorContent = "---\n" + . "Title: Error 404\n" + . "Robots: noindex,nofollow\n" + . "---\n\n" + . "# Error 404\n\n" + . "Woops. Looks like this page doesn't exist.\n"; + return $rawErrorContent; + } + + /** + * Returns the raw contents, either of the requested or the 404 file + * + * @see Pico::loadFileContent() + * @see Pico::load404Content() + * + * @return string|null raw contents + */ + public function getRawContent() + { + return $this->rawContent; + } + + /** + * Returns TRUE when Pico is serving a 404 page + * + * @see Pico::load404Content() + * + * @return bool TRUE if Pico is serving a 404 page, FALSE otherwise + */ + public function is404Content() + { + return $this->is404Content; + } + + /** + * Returns known meta headers + * + * This method triggers the `onMetaHeaders` event when the known meta + * headers weren't assembled yet. + * + * @return string[] known meta headers; the array key specifies the YAML + * key to search for, the array value is later used to access the + * found value + */ + public function getMetaHeaders() + { + if ($this->metaHeaders === null) { + $this->metaHeaders = array( + 'Title' => 'title', + 'Description' => 'description', + 'Author' => 'author', + 'Date' => 'date', + 'Formatted Date' => 'date_formatted', + 'Time' => 'time', + 'Robots' => 'robots', + 'Template' => 'template', + 'Hidden' => 'hidden' + ); + + if ($this->themeMetaHeaders) { + $this->metaHeaders += $this->themeMetaHeaders; + } + + $this->triggerEvent('onMetaHeaders', array(&$this->metaHeaders)); + } + + return $this->metaHeaders; + } + + /** + * Returns the Symfony YAML parser + * + * This method triggers the `onYamlParserRegistered` event when the Symfony + * YAML parser wasn't initiated yet. + * + * @return \Symfony\Component\Yaml\Parser Symfony YAML parser + */ + public function getYamlParser() + { + if ($this->yamlParser === null) { + $this->yamlParser = new \Symfony\Component\Yaml\Parser(); + $this->triggerEvent('onYamlParserRegistered', array(&$this->yamlParser)); + } + + return $this->yamlParser; + } + + /** + * Parses the file meta from raw file contents + * + * Meta data MUST start on the first line of the file, either opened and + * closed by `---` or C-style block comments (deprecated). The headers are + * parsed by the YAML component of the Symfony project. If you're a plugin + * developer, you MUST register new headers during the `onMetaHeaders` + * event first. The implicit availability of headers is for users and + * pure (!) theme developers ONLY. + * + * @see Pico::getFileMeta() + * + * @param string $rawContent the raw file contents + * @param string[] $headers known meta headers + * + * @return array parsed meta data + * + * @throws \Symfony\Component\Yaml\Exception\ParseException thrown when the + * meta data is invalid + */ + public function parseFileMeta($rawContent, array $headers) + { + $meta = array(); + $pattern = "/^(?:\xEF\xBB\xBF)?(\/(\*)|---)[[:blank:]]*(?:\r)?\n" + . "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s"; + if (preg_match($pattern, $rawContent, $rawMetaMatches) && isset($rawMetaMatches[3])) { + $meta = $this->getYamlParser()->parse($rawMetaMatches[3]) ?: array(); + $meta = is_array($meta) ? $meta : array('title' => $meta); + + foreach ($headers as $name => $key) { + if (isset($meta[$name])) { + // rename field (e.g. remove whitespaces) + if ($key != $name) { + $meta[$key] = $meta[$name]; + unset($meta[$name]); + } + } elseif (!isset($meta[$key])) { + // guarantee array key existance + $meta[$key] = ''; + } + } + + if (!empty($meta['date']) || !empty($meta['time'])) { + // workaround for issue #336 + // Symfony YAML interprets ISO-8601 datetime strings and returns timestamps instead of the string + // this behavior conforms to the YAML standard, i.e. this is no bug of Symfony YAML + if (is_int($meta['date'])) { + $meta['time'] = $meta['date']; + $meta['date'] = ''; + } + + if (empty($meta['time'])) { + $meta['time'] = strtotime($meta['date']) ?: ''; + } elseif (empty($meta['date'])) { + $rawDateFormat = (date('H:i:s', $meta['time']) === '00:00:00') ? 'Y-m-d' : 'Y-m-d H:i:s'; + $meta['date'] = date($rawDateFormat, $meta['time']); + } + } else { + $meta['date'] = $meta['time'] = ''; + } + + if (empty($meta['date_formatted'])) { + if ($meta['time']) { + $encodingList = mb_detect_order(); + if ($encodingList === array('ASCII', 'UTF-8')) { + $encodingList[] = 'Windows-1252'; + } + + $rawFormattedDate = strftime($this->getConfig('date_format'), $meta['time']); + $meta['date_formatted'] = mb_convert_encoding($rawFormattedDate, 'UTF-8', $encodingList); + } else { + $meta['date_formatted'] = ''; + } + } + } else { + // guarantee array key existance + $meta = array_fill_keys($headers, ''); + } + + return $meta; + } + + /** + * Returns the parsed meta data of the requested page + * + * @see Pico::parseFileMeta() + * + * @return array|null parsed meta data + */ + public function getFileMeta() + { + return $this->meta; + } + + /** + * Returns the Parsedown markdown parser + * + * This method triggers the `onParsedownRegistered` event when the + * Parsedown markdown parser wasn't initiated yet. + * + * @return Parsedown Parsedown markdown parser + */ + public function getParsedown() + { + if ($this->parsedown === null) { + $className = $this->config['content_config']['extra'] ? 'ParsedownExtra' : 'Parsedown'; + $this->parsedown = new $className(); + + $this->parsedown->setBreaksEnabled((bool) $this->config['content_config']['breaks']); + $this->parsedown->setMarkupEscaped((bool) $this->config['content_config']['escape']); + $this->parsedown->setUrlsLinked((bool) $this->config['content_config']['auto_urls']); + + $this->triggerEvent('onParsedownRegistered', array(&$this->parsedown)); + } + + return $this->parsedown; + } + + /** + * Applies some static preparations to the raw contents of a page + * + * This method removes the meta header and replaces `%...%` placeholders + * by calling the {@see Pico::substituteFileContent()} method. + * + * @see Pico::substituteFileContent() + * @see Pico::parseFileContent() + * @see Pico::getFileContent() + * + * @param string $rawContent raw contents of a page + * @param array $meta meta data to use for %meta.*% replacement + * + * @return string prepared Markdown contents + */ + public function prepareFileContent($rawContent, array $meta = array()) + { + // remove meta header + $metaHeaderPattern = "/^(?:\xEF\xBB\xBF)?(\/(\*)|---)[[:blank:]]*(?:\r)?\n" + . "(?:(.*?)(?:\r)?\n)?(?(2)\*\/|---)[[:blank:]]*(?:(?:\r)?\n|$)/s"; + $markdown = preg_replace($metaHeaderPattern, '', $rawContent, 1); + + // replace placeholders + $markdown = $this->substituteFileContent($markdown, $meta); + + return $markdown; + } + + /** + * Replaces all %...% placeholders in a page's contents + * + * @param string $markdown Markdown contents of a page + * @param array $meta meta data to use for %meta.*% replacement + * + * @return string substituted Markdown contents + */ + public function substituteFileContent($markdown, array $meta = array()) + { + $variables = array(); + + // replace %version% + $variables['%version%'] = static::VERSION; + + // replace %site_title% + $variables['%site_title%'] = $this->getConfig('site_title'); + + // replace %base_url% + if ($this->isUrlRewritingEnabled()) { + // always use `%base_url%?sub/page` syntax for internal links + // we'll replace the links accordingly, depending on enabled rewriting + $variables['%base_url%?'] = $this->getBaseUrl(); + } else { + // actually not necessary, but makes the URL look a little nicer + $variables['%base_url%?'] = $this->getBaseUrl() . '?'; + } + $variables['%base_url%'] = rtrim($this->getBaseUrl(), '/'); + + // replace %plugins_url%, %themes_url% and %assets_url% + $variables['%plugins_url%'] = rtrim($this->getConfig('plugins_url'), '/'); + $variables['%themes_url%'] = rtrim($this->getConfig('themes_url'), '/'); + $variables['%assets_url%'] = rtrim($this->getConfig('assets_url'), '/'); + + // replace %theme_url% + $variables['%theme_url%'] = $this->getConfig('themes_url') . $this->getTheme(); + + // replace %meta.*% + if ($meta) { + foreach ($meta as $metaKey => $metaValue) { + if (is_scalar($metaValue) || ($metaValue === null)) { + $variables['%meta.' . $metaKey . '%'] = (string) $metaValue; + } + } + } + + // replace %config.*% + foreach ($this->config as $configKey => $configValue) { + if (is_scalar($configValue) || ($configValue === null)) { + $variables['%config.' . $configKey . '%'] = (string) $configValue; + } + } + + return str_replace(array_keys($variables), $variables, $markdown); + } + + /** + * Parses the contents of a page using ParsedownExtra + * + * @see Pico::prepareFileContent() + * @see Pico::substituteFileContent() + * @see Pico::getFileContent() + * + * @param string $markdown Markdown contents of a page + * @param bool $singleLine whether to parse just a single line of markup + * + * @return string parsed contents (HTML) + */ + public function parseFileContent($markdown, $singleLine = false) + { + $markdownParser = $this->getParsedown(); + return !$singleLine ? @$markdownParser->text($markdown) : @$markdownParser->line($markdown); + } + + /** + * Returns the cached contents of the requested page + * + * @see Pico::prepareFileContent() + * @see Pico::substituteFileContent() + * @see Pico::parseFileContent() + * + * @return string|null parsed contents + */ + public function getFileContent() + { + return $this->content; + } + + /** + * Reads the data of all pages known to Pico + * + * The page data will be an array containing the following values: + * + * | Array key | Type | Description | + * | -------------- | ------- | ---------------------------------------- | + * | id | string | relative path to the content file | + * | url | string | URL to the page | + * | title | string | title of the page (YAML header) | + * | description | string | description of the page (YAML header) | + * | author | string | author of the page (YAML header) | + * | time | int | timestamp derived from the Date header | + * | date | string | date of the page (YAML header) | + * | date_formatted | string | formatted date of the page | + * | hidden | bool | this page shouldn't be visible | + * | raw_content | string | raw, not yet parsed contents of the page | + * | meta | string[] | parsed meta data of the page | + * | previous_page | &array[] | reference to the previous page | + * | next_page | &array[] | reference to the next page | + * | tree_node | &array[] | reference to the page's tree node | + * + * Please note that the `previous_page` and `next_page` keys don't + * exist until the `onCurrentPageDiscovered` event is triggered + * ({@see Pico::discoverPageSiblings()}). The `tree_node` key doesn't + * exit until the `onPageTreeBuilt` event is triggered + * ({@see Pico::buildPageTree()}). + * + * @see Pico::sortPages() + * @see Pico::discoverPageSiblings() + * @see Pico::getPages() + */ + protected function readPages() + { + $contentDir = $this->getConfig('content_dir'); + $contentExt = $this->getConfig('content_ext'); + + $this->pages = array(); + $files = $this->getFiles($contentDir, $contentExt, self::SORT_NONE); + foreach ($files as $i => $file) { + // skip 404 page + if (basename($file) === '404' . $contentExt) { + unset($files[$i]); + continue; + } + + $id = substr($file, strlen($contentDir), -strlen($contentExt)); + + // trigger onSinglePageLoading event + // skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists) by default + $conflictFile = $contentDir . $id . '/index' . $contentExt; + $skipFile = in_array($conflictFile, $files, true) ?: null; + $this->triggerEvent('onSinglePageLoading', array($id, &$skipFile)); + + if ($skipFile) { + continue; + } + + $url = $this->getPageUrl($id); + if ($file !== $this->requestFile) { + $rawContent = $this->loadFileContent($file); + + // trigger onSinglePageContent event + $this->triggerEvent('onSinglePageContent', array($id, &$rawContent)); + + $headers = $this->getMetaHeaders(); + try { + $meta = $this->parseFileMeta($rawContent, $headers); + } catch (\Symfony\Component\Yaml\Exception\ParseException $e) { + $meta = $this->parseFileMeta('', $headers); + $meta['YAML_ParseError'] = $e->getMessage(); + } + } else { + $rawContent = &$this->rawContent; + $meta = &$this->meta; + } + + // build page data + // title, description, author and date are assumed to be pretty basic data + // everything else is accessible through $page['meta'] + $page = array( + 'id' => $id, + 'url' => $url, + 'title' => &$meta['title'], + 'description' => &$meta['description'], + 'author' => &$meta['author'], + 'time' => &$meta['time'], + 'date' => &$meta['date'], + 'date_formatted' => &$meta['date_formatted'], + 'hidden' => ($meta['hidden'] || preg_match('/(?:^|\/)_/', $id)), + 'raw_content' => &$rawContent, + 'meta' => &$meta + ); + + if ($file === $this->requestFile) { + $page['content'] = &$this->content; + } + + unset($rawContent, $meta); + + // trigger onSinglePageLoaded event + $this->triggerEvent('onSinglePageLoaded', array(&$page)); + + if ($page !== null) { + $this->pages[$id] = $page; + } + } + } + + /** + * Sorts all pages known to Pico + * + * @see Pico::readPages() + * @see Pico::getPages() + */ + protected function sortPages() + { + // sort pages + $order = strtolower($this->getConfig('pages_order')); + $orderBy = strtolower($this->getConfig('pages_order_by')); + + if (($orderBy !== 'alpha') && ($orderBy !== 'date') && ($orderBy !== 'meta')) { + return; + } + + $alphaSortClosure = function ($a, $b) use ($order) { + if (!empty($a['hidden']) xor !empty($b['hidden'])) { + return (!empty($a['hidden']) - !empty($b['hidden'])) * (($order === 'desc') ? -1 : 1); + } + + $aSortKey = (basename($a['id']) === 'index') ? dirname($a['id']) : $a['id']; + $bSortKey = (basename($b['id']) === 'index') ? dirname($b['id']) : $b['id']; + + $cmp = strcmp($aSortKey, $bSortKey); + return $cmp * (($order === 'desc') ? -1 : 1); + }; + + if ($orderBy === 'meta') { + // sort by arbitrary meta value + $orderByMeta = $this->getConfig('pages_order_by_meta'); + uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order, $orderByMeta) { + $aSortValue = isset($a['meta'][$orderByMeta]) ? $a['meta'][$orderByMeta] : null; + $aSortValueNull = ($aSortValue === null); + + $bSortValue = isset($b['meta'][$orderByMeta]) ? $b['meta'][$orderByMeta] : null; + $bSortValueNull = ($bSortValue === null); + + $cmp = 0; + if ($aSortValueNull || $bSortValueNull) { + $cmp = ($aSortValueNull - $bSortValueNull); + } elseif ($aSortValue != $bSortValue) { + $cmp = ($aSortValue > $bSortValue) ? 1 : -1; + } + + if ($cmp === 0) { + // never assume equality; fallback to alphabetical order + return $alphaSortClosure($a, $b); + } + + return $cmp * (($order === 'desc') ? -1 : 1); + }); + } elseif ($orderBy === 'date') { + // sort by date + uasort($this->pages, function ($a, $b) use ($alphaSortClosure, $order) { + if (!empty($a['hidden']) xor !empty($b['hidden'])) { + return $alphaSortClosure($a, $b); + } + + if (!$a['time'] || !$b['time']) { + $cmp = (!$a['time'] - !$b['time']); + } else { + $cmp = ($b['time'] - $a['time']); + } + + if ($cmp === 0) { + // never assume equality; fallback to alphabetical order + return $alphaSortClosure($a, $b); + } + + return $cmp * (($order === 'desc') ? 1 : -1); + }); + } else { + // sort alphabetically + uasort($this->pages, $alphaSortClosure); + } + } + + /** + * Walks through the list of all known pages and discovers the previous and + * next page respectively + * + * @see Pico::readPages() + * @see Pico::getPages() + */ + protected function discoverPageSiblings() + { + if (($this->getConfig('order_by') === 'date') && ($this->getConfig('order') === 'desc')) { + $precedingPageKey = 'next_page'; + $succeedingPageKey = 'previous_page'; + } else { + $precedingPageKey = 'previous_page'; + $succeedingPageKey = 'next_page'; + } + + $precedingPageId = null; + foreach ($this->pages as $id => &$pageData) { + $pageData[$precedingPageKey] = null; + $pageData[$succeedingPageKey] = null; + + if (!empty($pageData['hidden'])) { + continue; + } + + if ($precedingPageId !== null) { + $precedingPageData = &$this->pages[$precedingPageId]; + $pageData[$precedingPageKey] = &$precedingPageData; + $precedingPageData[$succeedingPageKey] = &$pageData; + } + + $precedingPageId = $id; + } + } + + /** + * Returns the list of known pages + * + * @see Pico::readPages() + * + * @return array[]|null the data of all pages + */ + public function getPages() + { + return $this->pages; + } + + /** + * Discovers the page data of the requested page as well as the previous + * and next page relative to it + * + * @see Pico::getCurrentPage() + * @see Pico::getPreviousPage() + * @see Pico::getNextPage() + */ + protected function discoverCurrentPage() + { + $currentPageId = $this->getPageId($this->requestFile); + if ($currentPageId && isset($this->pages[$currentPageId])) { + $this->currentPage = &$this->pages[$currentPageId]; + $this->previousPage = &$this->pages[$currentPageId]['previous_page']; + $this->nextPage = &$this->pages[$currentPageId]['next_page']; + } + } + + /** + * Returns the data of the requested page + * + * @see Pico::discoverCurrentPage() + * + * @return array|null page data + */ + public function getCurrentPage() + { + return $this->currentPage; + } + + /** + * Returns the data of the previous page relative to the page being served + * + * @see Pico::discoverCurrentPage() + * + * @return array|null page data + */ + public function getPreviousPage() + { + return $this->previousPage; + } + + /** + * Returns the data of the next page relative to the page being served + * + * @see Pico::discoverCurrentPage() + * + * @return array|null page data + */ + public function getNextPage() + { + return $this->nextPage; + } + + /** + * Builds a tree structure containing all known pages + * + * Pico's page tree is a list of all the tree's branches (no matter the + * depth). Thus, by iterating a array element, you get the nodes of a given + * branch. All leaf nodes do represent a page, but inner nodes may or may + * not represent a page (e.g. if there's a `sub/page.md`, but neither a + * `sub/index.md` nor a `sub.md`, the inner node `sub`, that is the parent + * of the `sub/page` node, represents no page itself). + * + * A page's file path describes its node's path in the tree (e.g. the page + * `sub/page.md` is represented by the `sub/page` node, thus a child of the + * `sub` node and a element of the `sub` branch). However, the index page + * of a folder (e.g. `sub/index.md`), is *not* a node of the `sub` branch, + * but rather of the `/` branch. The page's node is not `sub/index`, but + * `sub`. If two pages are described by the same node (e.g. if both a + * `sub/index.md` and a `sub.md` exist), the index page takes precedence. + * Pico's main index page (i.e. `index.md`) is represented by the tree's + * root node `/` and a special case: it is the only node of the `` (i.e. + * the empty string) branch. + * + * A node is represented by an array with the keys `id`, `page` and + * `children`. The `id` key contains a string with the node's name. If the + * node represents a page, the `page` key is a reference to the page's + * data array. If the node is a inner node, the `children` key is a + * reference to its matching branch (i.e. a list of the node's children). + * The order of a node's children matches the order in Pico's pages array. + * + * If you want to walk the whole page tree, start with the tree's root node + * at `$pageTree[""]["/"]`, or rather, use `$pages["index"]["tree_node"]`. + * The root node's `children` key is a reference to the `/` branch at + * `$pageTree["/"]`, that is a list of the root node's direct child nodes + * and their siblings. + * + * You MUST NOT iterate the page tree itself (i.e. the list of the tree's + * branches), its order is undefined and the array will be replaced by a + * non-iterable data structure with Pico 3.0. + * + * @see Pico::getPageTree() + */ + protected function buildPageTree() + { + $this->pageTree = array(); + foreach ($this->pages as $id => &$pageData) { + // main index page + if ($id === 'index') { + $this->pageTree['']['/']['id'] = '/'; + $this->pageTree['']['/']['page'] = &$pageData; + $pageData['tree_node'] = &$this->pageTree['']['/']; + continue; + } + + // get a page's node and branch + $basename = basename($id); + $branch = dirname($id); + + $isIndexPage = ($basename === 'index'); + if ($isIndexPage) { + $basename = basename($branch); + $branch = dirname($branch); + } + + $branch = ($branch !== '.') ? $branch : '/'; + $node = ($branch !== '/') ? $branch . '/' . $basename : $basename; + + // skip inaccessible pages (e.g. drop "sub.md" if "sub/index.md" exists) + if (isset($this->pageTree[$branch][$node]['page']) && !$isIndexPage) { + continue; + } + + // add node to page tree + $isNewBranch = !isset($this->pageTree[$branch]); + $this->pageTree[$branch][$node]['id'] = $node; + $this->pageTree[$branch][$node]['page'] = &$pageData; + + $pageData['tree_node'] = &$this->pageTree[$branch][$node]; + + // add parent nodes to page tree, if necessary + while ($isNewBranch && $branch) { + $parentNode = $branch; + $parentBranch = ($branch !== '/') ? dirname($parentNode) : ''; + $parentBranch = ($parentBranch !== '.') ? $parentBranch : '/'; + + $isNewBranch = !isset($this->pageTree[$parentBranch]); + $this->pageTree[$parentBranch][$parentNode]['id'] = $parentNode; + $this->pageTree[$parentBranch][$parentNode]['children'] = &$this->pageTree[$branch]; + + $branch = $parentBranch; + } + } + } + + /** + * Returns a tree structure of known pages + * + * @see Pico::buildPageTree() + * + * @return array[]|null the tree structure of all pages + */ + public function getPageTree() + { + return $this->pageTree; + } + + /** + * Returns the Twig template engine + * + * This method triggers the `onTwigRegistered` event when the Twig template + * engine wasn't initiated yet. When initiating Twig, this method also + * registers Pico's core Twig filter `content` as well as Pico's + * {@see PicoTwigExtension} Twig extension. + * + * @see Pico::getTwig() + * @see http://twig.sensiolabs.org/ Twig website + * @see https://github.com/twigphp/Twig Twig on GitHub + * + * @return Twig_Environment|null Twig template engine + */ + public function getTwig() + { + if ($this->twig === null) { + $twigConfig = $this->getConfig('twig_config'); + + $twigLoader = new Twig_Loader_Filesystem($this->getThemesDir() . $this->getTheme()); + $this->twig = new Twig_Environment($twigLoader, $twigConfig); + $this->twig->addExtension(new PicoTwigExtension($this)); + + if (!empty($twigConfig['debug'])) { + $this->twig->addExtension(new Twig_Extension_Debug()); + } + + // register content filter + // we pass the $pages array by reference to prevent multiple parser runs for the same page + // this is the reason why we can't register this filter as part of PicoTwigExtension + $pico = $this; + $pages = &$this->pages; + $this->twig->addFilter(new Twig_SimpleFilter( + 'content', + function ($page) use ($pico, &$pages) { + if (isset($pages[$page])) { + $pageData = &$pages[$page]; + if (!isset($pageData['content'])) { + $markdown = $pico->prepareFileContent($pageData['raw_content'], $pageData['meta']); + $pageData['content'] = $pico->parseFileContent($markdown); + } + return $pageData['content']; + } + return null; + }, + array('is_safe' => array('html')) + )); + + // trigger onTwigRegistration event + $this->triggerEvent('onTwigRegistered', array(&$this->twig)); + } + + return $this->twig; + } + + /** + * Returns the variables passed to the template + * + * URLs and paths don't add a trailing slash for historic reasons. + * + * @return array template variables + */ + protected function getTwigVariables() + { + return array( + 'config' => $this->getConfig(), + 'base_url' => rtrim($this->getBaseUrl(), '/'), + 'plugins_url' => rtrim($this->getConfig('plugins_url'), '/'), + 'themes_url' => rtrim($this->getConfig('themes_url'), '/'), + 'assets_url' => rtrim($this->getConfig('assets_url'), '/'), + 'theme_url' => $this->getConfig('themes_url') . $this->getTheme(), + 'site_title' => $this->getConfig('site_title'), + 'meta' => $this->meta, + 'content' => new Twig_Markup($this->content, 'UTF-8'), + 'pages' => $this->pages, + 'previous_page' => $this->previousPage, + 'current_page' => $this->currentPage, + 'next_page' => $this->nextPage, + 'version' => static::VERSION + ); + } + + /** + * Returns the name of the Twig template to render + * + * @return string template name + */ + protected function getTwigTemplate() + { + $templateName = !empty($this->meta['template']) ? $this->meta['template'] : 'index'; + return $templateName . '.twig'; + } + + /** + * Returns the base URL of this Pico instance + * + * Security Notice: You MUST configure Pico's base URL explicitly when + * using the base URL in contexts that are potentially vulnerable to + * HTTP Host Header Injection attacks (e.g. when generating emails). + * + * @return string the base url + */ + public function getBaseUrl() + { + $baseUrl = $this->getConfig('base_url'); + if ($baseUrl) { + return $baseUrl; + } + + $host = 'localhost'; + if (!empty($_SERVER['HTTP_X_FORWARDED_HOST'])) { + $host = $_SERVER['HTTP_X_FORWARDED_HOST']; + } elseif (!empty($_SERVER['HTTP_HOST'])) { + $host = $_SERVER['HTTP_HOST']; + } elseif (!empty($_SERVER['SERVER_NAME'])) { + $host = $_SERVER['SERVER_NAME']; + } + + $port = 80; + if (!empty($_SERVER['HTTP_X_FORWARDED_PORT'])) { + $port = (int) $_SERVER['HTTP_X_FORWARDED_PORT']; + } elseif (!empty($_SERVER['SERVER_PORT'])) { + $port = (int) $_SERVER['SERVER_PORT']; + } + + $hostPortPosition = ($host[0] === '[') ? strpos($host, ':', strrpos($host, ']') ?: 0) : strrpos($host, ':'); + if ($hostPortPosition !== false) { + $port = (int) substr($host, $hostPortPosition + 1); + $host = substr($host, 0, $hostPortPosition); + } + + $protocol = 'http'; + if (!empty($_SERVER['HTTP_X_FORWARDED_PROTO'])) { + $secureProxyHeader = strtolower(current(explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO']))); + $protocol = in_array($secureProxyHeader, array('https', 'on', 'ssl', '1'), true) ? 'https' : 'http'; + } elseif (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] !== 'off')) { + $protocol = 'https'; + } elseif ($port === 443) { + $protocol = 'https'; + } + + $basePath = isset($_SERVER['SCRIPT_NAME']) ? dirname($_SERVER['SCRIPT_NAME']) : '/'; + $basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/'; + + if ((($protocol === 'http') && ($port !== 80)) || (($protocol === 'https') && ($port !== 443))) { + $host = $host . ':' . $port; + } + + $this->config['base_url'] = $protocol . "://" . $host . $basePath; + return $this->config['base_url']; + } + + /** + * Returns TRUE if URL rewriting is enabled + * + * @return bool TRUE if URL rewriting is enabled, FALSE otherwise + */ + public function isUrlRewritingEnabled() + { + $urlRewritingEnabled = $this->getConfig('rewrite_url'); + if ($urlRewritingEnabled !== null) { + return $urlRewritingEnabled; + } + + if (isset($_SERVER['PICO_URL_REWRITING'])) { + $this->config['rewrite_url'] = (bool) $_SERVER['PICO_URL_REWRITING']; + } elseif (isset($_SERVER['REDIRECT_PICO_URL_REWRITING'])) { + $this->config['rewrite_url'] = (bool) $_SERVER['REDIRECT_PICO_URL_REWRITING']; + } else { + $this->config['rewrite_url'] = false; + } + + return $this->config['rewrite_url']; + } + + /** + * Returns TRUE if Pico's debug mode is enabled + * + * @return bool TRUE if Pico's debug mode is enabled, FALSE otherwise + */ + public function isDebugModeEnabled() + { + $debugModeEnabled = $this->getConfig('debug'); + if ($debugModeEnabled !== null) { + return $debugModeEnabled; + } + + if (isset($_SERVER['PICO_DEBUG'])) { + $this->config['debug'] = (bool) $_SERVER['PICO_DEBUG']; + } elseif (isset($_SERVER['REDIRECT_PICO_DEBUG'])) { + $this->config['debug'] = (bool) $_SERVER['REDIRECT_PICO_DEBUG']; + } else { + $this->config['debug'] = false; + } + + return $this->config['debug']; + } + + /** + * Returns the URL to a given page + * + * This method can be used in Twig templates by applying the `link` filter + * to a string representing a page ID. + * + * @param string $page ID of the page to link to + * @param array|string|null $queryData either an array of properties to + * create a URL-encoded query string from, or a already encoded string + * @param bool $dropIndex if the last path component is + * "index", passing TRUE (default) will remove this path component + * + * @return string URL + * + * @throws InvalidArgumentException thrown when invalid arguments got passed + */ + public function getPageUrl($page, $queryData = null, $dropIndex = true) + { + if (is_array($queryData)) { + $queryData = http_build_query($queryData, '', '&'); + } elseif (($queryData !== null) && !is_string($queryData)) { + throw new InvalidArgumentException( + 'Argument 2 passed to ' . __METHOD__ . ' must be of the type array or string, ' + . (is_object($queryData) ? get_class($queryData) : gettype($queryData)) . ' given' + ); + } + + // drop "index" + if ($dropIndex) { + if ($page === 'index') { + $page = ''; + } elseif (($pagePathLength = strrpos($page, '/')) !== false) { + if (substr($page, $pagePathLength + 1) === 'index') { + $page = substr($page, 0, $pagePathLength); + } + } + } + + if ($queryData) { + $queryData = ($this->isUrlRewritingEnabled() || !$page) ? '?' . $queryData : '&' . $queryData; + } else { + $queryData = ''; + } + + if (!$page) { + return $this->getBaseUrl() . $queryData; + } elseif (!$this->isUrlRewritingEnabled()) { + return $this->getBaseUrl() . '?' . rawurlencode($page) . $queryData; + } else { + return $this->getBaseUrl() . implode('/', array_map('rawurlencode', explode('/', $page))) . $queryData; + } + } + + /** + * Returns the page ID of a given content file + * + * @param string $path path to the content file + * + * @return string|null either the corresponding page ID or NULL + */ + public function getPageId($path) + { + $contentDir = $this->getConfig('content_dir'); + $contentDirLength = strlen($contentDir); + if (substr($path, 0, $contentDirLength) !== $contentDir) { + return null; + } + + $contentExt = $this->getConfig('content_ext'); + $contentExtLength = strlen($contentExt); + if (substr($path, -$contentExtLength) !== $contentExt) { + return null; + } + + return substr($path, $contentDirLength, -$contentExtLength) ?: null; + } + + /** + * Substitutes URL placeholders (e.g. %base_url%) + * + * This method is registered as the `url` Twig filter and often used to + * allow users to specify absolute URLs in meta data utilizing the known + * URL placeholders `%base_url%`, `%plugins_url%`, `%themes_url%`, + * `%assets_url%` and `%theme_url%`. + * + * Don't confuse this with the `link` Twig filter, which takes a page ID as + * parameter. However, you can indeed use this method to create page URLs, + * e.g. `{{ "%base_url%?sub/page"|url }}`. + * + * @param string $url URL with placeholders + * + * @return string URL with replaced placeholders + */ + public function substituteUrl($url) + { + $variables = array( + '%base_url%?' => $this->getBaseUrl() . (!$this->isUrlRewritingEnabled() ? '?' : ''), + '%base_url%' => rtrim($this->getBaseUrl(), '/'), + '%plugins_url%' => rtrim($this->getConfig('plugins_url'), '/'), + '%themes_url%' => rtrim($this->getConfig('themes_url'), '/'), + '%assets_url%' => rtrim($this->getConfig('assets_url'), '/'), + '%theme_url%' => $this->getConfig('themes_url') . $this->getTheme() + ); + + return str_replace(array_keys($variables), $variables, $url); + } + + /** + * Returns the URL of the themes folder of this Pico instance + * + * @see Pico::getUrlFromPath() + * + * @deprecated 2.1.0 + * + * @return string + */ + public function getBaseThemeUrl() + { + return $this->getConfig('themes_url'); + } + + /** + * Returns the URL of a given absolute path within this Pico instance + * + * We assume that the given path is a arbitrary deep sub folder of the + * script's base path (i.e. the directory {@path "index.php"} is in resp. + * the `httpdocs` directory). If this isn't the case, we check whether it's + * a sub folder of {@see Pico::$rootDir} (what is often identical to the + * script's base path). If this isn't the case either, we fall back to + * the basename of the given folder. This whole process ultimately allows + * us to use {@see Pico::getBaseUrl()} as origin for the URL. + * + * This method is used to guess Pico's `plugins_url`, `themes_url` and + * `assets_url`. However, guessing might fail, requiring a manual config. + * + * @param string $absolutePath the absolute path to interpret + * + * @return string the URL of the given folder + */ + public function getUrlFromPath($absolutePath) + { + $absolutePath = str_replace('\\', '/', $absolutePath); + + $basePath = ''; + if (isset($_SERVER['SCRIPT_FILENAME']) && strrpos($_SERVER['SCRIPT_FILENAME'], '/')) { + $basePath = dirname($_SERVER['SCRIPT_FILENAME']); + $basePath = !in_array($basePath, array('.', '/', '\\'), true) ? $basePath . '/' : '/'; + $basePathLength = strlen($basePath); + + if ((substr($absolutePath, 0, $basePathLength) === $basePath) && ($basePath !== '/')) { + return $this->getBaseUrl() . substr($absolutePath, $basePathLength); + } + } + + if ($basePath !== $this->getRootDir()) { + $basePath = $this->getRootDir(); + $basePathLength = strlen($basePath); + + if (substr($absolutePath, 0, $basePathLength) === $basePath) { + return $this->getBaseUrl() . substr($absolutePath, $basePathLength); + } + } + + return $this->getBaseUrl() . basename($absolutePath) . '/'; + } + + /** + * Filters a URL GET parameter with a specified filter + * + * This method is just an alias for {@see Pico::filterVariable()}, see + * {@see Pico::filterVariable()} for a detailed description. It can be + * used in Twig templates by calling the `url_param` function. + * + * @see Pico::filterVariable() + * + * @param string $name name of the URL GET parameter + * to filter + * @param int|string $filter the filter to apply + * @param mixed|array $options either a associative options + * array to be used by the filter or a scalar default value + * @param int|string|int[]|string[] $flags flags and flag strings to be + * used by the filter + * + * @return mixed either the filtered data, FALSE if the filter fails, or + * NULL if the URL GET parameter doesn't exist and no default value is + * given + */ + public function getUrlParameter($name, $filter = '', $options = null, $flags = null) + { + $variable = (isset($_GET[$name]) && is_scalar($_GET[$name])) ? $_GET[$name] : null; + return $this->filterVariable($variable, $filter, $options, $flags); + } + + /** + * Filters a HTTP POST parameter with a specified filter + * + * This method is just an alias for {@see Pico::filterVariable()}, see + * {@see Pico::filterVariable()} for a detailed description. It can be + * used in Twig templates by calling the `form_param` function. + * + * @see Pico::filterVariable() + * + * @param string $name name of the HTTP POST + * parameter to filter + * @param int|string $filter the filter to apply + * @param mixed|array $options either a associative options + * array to be used by the filter or a scalar default value + * @param int|string|int[]|string[] $flags flags and flag strings to be + * used by the filter + * + * @return mixed either the filtered data, FALSE if the filter fails, or + * NULL if the HTTP POST parameter doesn't exist and no default value + * is given + */ + public function getFormParameter($name, $filter = '', $options = null, $flags = null) + { + $variable = (isset($_POST[$name]) && is_scalar($_POST[$name])) ? $_POST[$name] : null; + return $this->filterVariable($variable, $filter, $options, $flags); + } + + /** + * Filters a variable with a specified filter + * + * This method basically wraps around PHP's `filter_var()` function. It + * filters data by either validating or sanitizing it. This is especially + * useful when the data source contains unknown (or foreign) data, like + * user supplied input. Validation is used to validate or check if the data + * meets certain qualifications, but will not change the data itself. + * Sanitization will sanitize the data, so it may alter it by removing + * undesired characters. It doesn't actually validate the data! The + * behaviour of most filters can optionally be tweaked by flags. + * + * Heads up! Input validation is hard! Always validate your input data the + * most paranoid way you can imagine. Always prefer validation filters over + * sanitization filters; be very careful with sanitization filters, you + * might create cross-site scripting vulnerabilities! + * + * @see https://secure.php.net/manual/en/function.filter-var.php + * PHP's `filter_var()` function + * @see https://secure.php.net/manual/en/filter.filters.validate.php + * Validate filters + * @see https://secure.php.net/manual/en/filter.filters.sanitize.php + * Sanitize filters + * + * @param mixed $variable value to filter + * @param int|string $filter ID (int) or name (string) of + * the filter to apply; if omitted, the method will return FALSE + * @param mixed|array $options either a associative array + * of options to be used by the filter (e.g. `array('default' => 42)`), + * or a scalar default value that will be returned when the passed + * value is NULL (optional) + * @param int|string|int[]|string[] $flags either a bitwise disjunction + * of flags or a string with the significant part of a flag constant + * (the constant name is the result of "FILTER_FLAG_" and the given + * string in ASCII-only uppercase); you may also pass an array of flags + * and flag strings (optional) + * + * @return mixed with a validation filter, the method either returns the + * validated value or, provided that the value wasn't valid, the given + * default value or FALSE; with a sanitization filter, the method + * returns the sanitized value; if no value (i.e. NULL) was given, the + * method always returns either the provided default value or NULL + */ + protected function filterVariable($variable, $filter = '', $options = null, $flags = null) + { + $defaultValue = null; + if (is_array($options)) { + $defaultValue = isset($options['default']) ? $options['default'] : null; + } elseif ($options !== null) { + $defaultValue = $options; + $options = array('default' => $defaultValue); + } + + if ($variable === null) { + return $defaultValue; + } + + $filter = $filter ? (is_string($filter) ? filter_id($filter) : (int) $filter) : false; + if (!$filter) { + return false; + } + + $filterOptions = array('options' => $options, 'flags' => 0); + foreach ((array) $flags as $flag) { + if (is_numeric($flag)) { + $filterOptions['flags'] |= (int) $flag; + } elseif (is_string($flag)) { + $flag = strtoupper(preg_replace('/[^a-zA-Z0-9_]/', '', $flag)); + if (($flag === 'NULL_ON_FAILURE') && ($filter === FILTER_VALIDATE_BOOLEAN)) { + $filterOptions['flags'] |= FILTER_NULL_ON_FAILURE; + } else { + $filterOptions['flags'] |= (int) constant('FILTER_FLAG_' . $flag); + } + } + } + + return filter_var($variable, $filter, $filterOptions); + } + + /** + * Recursively walks through a directory and returns all containing files + * matching the specified file extension + * + * @param string $directory start directory + * @param string $fileExtension return files with the given file extension + * only (optional) + * @param int $order specify whether and how files should be + * sorted; use Pico::SORT_ASC for a alphabetical ascending order (this + * is the default behaviour), Pico::SORT_DESC for a descending order + * or Pico::SORT_NONE to leave the result unsorted + * + * @return array list of found files + */ + public function getFiles($directory, $fileExtension = '', $order = self::SORT_ASC) + { + $directory = rtrim($directory, '/'); + $fileExtensionLength = strlen($fileExtension); + $result = array(); + + $files = scandir($directory, $order); + if ($files !== false) { + foreach ($files as $file) { + // exclude hidden files/dirs starting with a .; this also excludes the special dirs . and .. + // exclude files ending with a ~ (vim/nano backup) or # (emacs backup) + if (($file[0] === '.') || in_array(substr($file, -1), array('~', '#'), true)) { + continue; + } + + if (is_dir($directory . '/' . $file)) { + // get files recursively + $result = array_merge($result, $this->getFiles($directory . '/' . $file, $fileExtension, $order)); + } elseif (!$fileExtension || (substr($file, -$fileExtensionLength) === $fileExtension)) { + $result[] = $directory . '/' . $file; + } + } + } + + return $result; + } + + /** + * Returns all files in a directory matching a libc glob() pattern + * + * @see https://secure.php.net/manual/en/function.glob.php + * PHP's glob() function + * + * @param string $pattern the pattern to search for; see PHP's glob() + * function for details + * @param int $order specify whether and how files should be sorted; + * use Pico::SORT_ASC for a alphabetical ascending order (this is the + * default behaviour), Pico::SORT_DESC for a descending order or + * Pico::SORT_NONE to leave the result unsorted + * + * @return array list of found files + */ + public function getFilesGlob($pattern, $order = self::SORT_ASC) + { + $result = array(); + $sortFlag = ($order === self::SORT_NONE) ? GLOB_NOSORT : 0; + + $files = glob($pattern, GLOB_MARK | $sortFlag); + if ($files) { + foreach ($files as $file) { + // exclude dirs and files ending with a ~ (vim/nano backup) or # (emacs backup) + if (in_array(substr($file, -1), array('/', '~', '#'), true)) { + continue; + } + + $result[] = $file; + } + } + + return ($order === self::SORT_DESC) ? array_reverse($result) : $result; + } + + /** + * Makes a relative path absolute to Pico's root dir + * + * @param string $path relative or absolute path + * @param string $basePath treat relative paths relative to the given path; + * defaults to Pico::$rootDir + * @param bool $endSlash whether to add a trailing slash to the absolute + * path or not (defaults to TRUE) + * + * @return string absolute path + */ + public function getAbsolutePath($path, $basePath = null, $endSlash = true) + { + if ($basePath === null) { + $basePath = $this->getRootDir(); + } + + if (DIRECTORY_SEPARATOR === '\\') { + if (preg_match('/^(?>[a-zA-Z]:\\\\|\\\\\\\\)/', $path) !== 1) { + $path = $basePath . $path; + } + } else { + if ($path[0] !== '/') { + $path = $basePath . $path; + } + } + + return rtrim($path, '/\\') . ($endSlash ? '/' : ''); + } + + /** + * Normalizes a path by taking care of '', '.' and '..' parts + * + * @param string $path path to normalize + * @param bool $allowAbsolutePath whether absolute paths are allowed + * @param bool $endSlash whether to add a trailing slash to the + * normalized path or not (defaults to TRUE) + * + * @return string normalized path + * + * @throws UnexpectedValueException thrown when a absolute path is passed + * although absolute paths aren't allowed + */ + public function getNormalizedPath($path, $allowAbsolutePath = false, $endSlash = true) + { + $absolutePath = ''; + if (DIRECTORY_SEPARATOR === '\\') { + if (preg_match('/^(?>[a-zA-Z]:\\\\|\\\\\\\\)/', $path, $pathMatches) === 1) { + $absolutePath = $pathMatches[0]; + $path = substr($path, strlen($absolutePath)); + } + } else { + if ($path[0] === '/') { + $absolutePath = '/'; + $path = substr($path, 1); + } + } + + if ($absolutePath && !$allowAbsolutePath) { + throw new UnexpectedValueException( + 'Argument 1 passed to ' . __METHOD__ . ' must be a relative path, absolute path "' . $path . '" given' + ); + } + + $path = str_replace('\\', '/', $path); + $pathParts = explode('/', $path); + + $resultParts = array(); + foreach ($pathParts as $pathPart) { + if (($pathPart === '') || ($pathPart === '.')) { + continue; + } elseif ($pathPart === '..') { + array_pop($resultParts); + continue; + } + $resultParts[] = $pathPart; + } + + if (!$resultParts) { + return $absolutePath ?: '/'; + } + + return $absolutePath . implode('/', $resultParts) . ($endSlash ? '/' : ''); + } + + /** + * Makes a relative URL absolute to Pico's base URL + * + * Please note that URLs starting with a slash are considered absolute URLs + * even though they don't include a scheme and host. + * + * @param string $url relative or absolute URL + * @param string $baseUrl treat relative URLs relative to the given URL; + * defaults to Pico::getBaseUrl() + * @param bool $endSlash whether to add a trailing slash to the absolute + * URL or not (defaults to TRUE) + * + * @return string absolute URL + */ + public function getAbsoluteUrl($url, $baseUrl = null, $endSlash = true) + { + if (($url[0] !== '/') && !preg_match('#^[A-Za-z][A-Za-z0-9+\-.]*://#', $url)) { + $url = (($baseUrl !== null) ? $baseUrl : $this->getBaseUrl()) . $url; + } + + return rtrim($url, '/') . ($endSlash ? '/' : ''); + } + + /** + * Triggers events on plugins using the current API version + * + * Plugins using older API versions are handled by {@see PicoDeprecated}. + * Please note that {@see PicoDeprecated} also triggers custom events on + * plugins using older API versions, thus you can safely use this method + * to trigger custom events on all loaded plugins, no matter what API + * version - the event will be triggered in any case. + * + * You MUST NOT trigger events of Pico's core with a plugin! + * + * @see PicoPluginInterface + * @see AbstractPicoPlugin + * @see DummyPlugin + * + * @param string $eventName name of the event to trigger + * @param array $params optional parameters to pass + */ + public function triggerEvent($eventName, array $params = array()) + { + foreach ($this->nativePlugins as $plugin) { + $plugin->handleEvent($eventName, $params); + } + } +} diff --git a/vendor/picocms/pico/lib/PicoPluginInterface.php b/vendor/picocms/pico/lib/PicoPluginInterface.php new file mode 100644 index 0000000..85f9dfb --- /dev/null +++ b/vendor/picocms/pico/lib/PicoPluginInterface.php @@ -0,0 +1,105 @@ + + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +/** + * Common interface for Pico plugins + * + * For a list of supported events see {@see DummyPlugin}; you can use + * {@see DummyPlugin} as template for new plugins. For a list of deprecated + * events see {@see PicoDeprecated}. + * + * If you're developing a new plugin, you MUST both implement this interface + * and define the class constant `API_VERSION`. You SHOULD always use the + * API version of Pico's latest milestone when releasing a plugin. If you're + * developing a new version of an existing plugin, it is strongly recommended + * to update your plugin to use Pico's latest API version. + * + * @author Daniel Rudolf + * @link http://picocms.org + * @license http://opensource.org/licenses/MIT The MIT License + * @version 2.1 + */ +interface PicoPluginInterface +{ + /** + * Handles a event that was triggered by Pico + * + * @param string $eventName name of the triggered event + * @param array $params passed parameters + */ + public function handleEvent($eventName, array $params); + + /** + * Enables or disables this plugin + * + * @see PicoPluginInterface::isEnabled() + * @see PicoPluginInterface::isStatusChanged() + * + * @param bool $enabled enable (TRUE) or disable (FALSE) this plugin + * @param bool $recursive when TRUE, enable or disable recursively. + * In other words, if you enable a plugin, all required plugins are + * enabled, too. When disabling a plugin, all depending plugins are + * disabled likewise. Recursive operations are only performed as long + * as a plugin wasn't enabled/disabled manually. This parameter is + * optional and defaults to TRUE. + * @param bool $auto enable or disable to fulfill a dependency. This + * parameter is optional and defaults to FALSE. + * + * @throws RuntimeException thrown when a dependency fails + */ + public function setEnabled($enabled, $recursive = true, $auto = false); + + /** + * Returns a boolean indicating whether this plugin is enabled or not + * + * You musn't rely on the return value when Pico's `onConfigLoaded` event + * wasn't triggered on all plugins yet. This method might even return NULL + * then. The plugin's status might change later. + * + * @see PicoPluginInterface::setEnabled() + * + * @return bool|null plugin is enabled (TRUE) or disabled (FALSE) + */ + public function isEnabled(); + + /** + * Returns TRUE if the plugin was ever enabled/disabled manually + * + * @see PicoPluginInterface::setEnabled() + * + * @return bool plugin is in its default state (TRUE), FALSE otherwise + */ + public function isStatusChanged(); + + /** + * Returns a list of names of plugins required by this plugin + * + * @return string[] required plugins + */ + public function getDependencies(); + + /** + * Returns a list of plugins which depend on this plugin + * + * @return object[] dependant plugins + */ + public function getDependants(); + + /** + * Returns the plugin's instance of Pico + * + * @see Pico + * + * @return Pico the plugin's instance of Pico + */ + public function getPico(); +} diff --git a/vendor/picocms/pico/lib/PicoTwigExtension.php b/vendor/picocms/pico/lib/PicoTwigExtension.php new file mode 100644 index 0000000..0988110 --- /dev/null +++ b/vendor/picocms/pico/lib/PicoTwigExtension.php @@ -0,0 +1,487 @@ + + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +/** + * Pico's Twig extension to implement additional filters + * + * @author Daniel Rudolf + * @link http://picocms.org + * @license http://opensource.org/licenses/MIT The MIT License + * @version 2.1 + */ +class PicoTwigExtension extends Twig_Extension +{ + /** + * Current instance of Pico + * + * @see PicoTwigExtension::getPico() + * @var Pico + */ + private $pico; + + /** + * Constructs a new instance of this Twig extension + * + * @param Pico $pico current instance of Pico + */ + public function __construct(Pico $pico) + { + $this->pico = $pico; + } + + /** + * Returns the extensions instance of Pico + * + * @see Pico + * + * @return Pico the extension's instance of Pico + */ + public function getPico() + { + return $this->pico; + } + + /** + * Returns the name of the extension + * + * @see Twig_ExtensionInterface::getName() + * + * @return string the extension name + */ + public function getName() + { + return 'PicoTwigExtension'; + } + + /** + * Returns a list of Pico-specific Twig filters + * + * @see Twig_ExtensionInterface::getFilters() + * + * @return Twig_SimpleFilter[] array of Pico's Twig filters + */ + public function getFilters() + { + return array( + 'markdown' => new Twig_SimpleFilter( + 'markdown', + array($this, 'markdownFilter'), + array('is_safe' => array('html')) + ), + 'map' => new Twig_SimpleFilter('map', array($this, 'mapFilter')), + 'sort_by' => new Twig_SimpleFilter('sort_by', array($this, 'sortByFilter')), + 'link' => new Twig_SimpleFilter('link', array($this->pico, 'getPageUrl')), + 'url' => new Twig_SimpleFilter('url', array($this->pico, 'substituteUrl')) + ); + } + + /** + * Returns a list of Pico-specific Twig functions + * + * @see Twig_ExtensionInterface::getFunctions() + * + * @return Twig_SimpleFunction[] array of Pico's Twig functions + */ + public function getFunctions() + { + return array( + 'url_param' => new Twig_SimpleFunction('url_param', array($this, 'urlParamFunction')), + 'form_param' => new Twig_SimpleFunction('form_param', array($this, 'formParamFunction')), + 'pages' => new Twig_SimpleFunction('pages', array($this, 'pagesFunction')) + ); + } + + /** + * Parses a markdown string to HTML + * + * This method is registered as the Twig `markdown` filter. You can use it + * to e.g. parse a meta variable (`{{ meta.description|markdown }}`). + * Don't use it to parse the contents of a page, use the `content` filter + * instead, what ensures the proper preparation of the contents. + * + * @see Pico::substituteFileContent() + * @see Pico::parseFileContent() + * + * @param string $markdown markdown to parse + * @param array $meta meta data to use for %meta.*% replacement + * @param bool $singleLine whether to parse just a single line of markup + * + * @return string parsed HTML + */ + public function markdownFilter($markdown, array $meta = array(), $singleLine = false) + { + $markdown = $this->getPico()->substituteFileContent($markdown, $meta); + return $this->getPico()->parseFileContent($markdown, $singleLine); + } + + /** + * Returns a array with the values of the given key or key path + * + * This method is registered as the Twig `map` filter. You can use this + * filter to e.g. get all page titles (`{{ pages|map("title") }}`). + * + * @param array|Traversable $var variable to map + * @param mixed $mapKeyPath key to map; either a scalar or a + * array interpreted as key path (i.e. ['foo', 'bar'] will return all + * $item['foo']['bar'] values) + * + * @return array mapped values + * + * @throws Twig_Error_Runtime + */ + public function mapFilter($var, $mapKeyPath) + { + if (!is_array($var) && (!is_object($var) || !($var instanceof Traversable))) { + throw new Twig_Error_Runtime(sprintf( + 'The map filter only works with arrays or "Traversable", got "%s"', + is_object($var) ? get_class($var) : gettype($var) + )); + } + + $result = array(); + foreach ($var as $key => $value) { + $mapValue = $this->getKeyOfVar($value, $mapKeyPath); + $result[$key] = ($mapValue !== null) ? $mapValue : $value; + } + return $result; + } + + /** + * Sorts an array by one of its keys or a arbitrary deep sub-key + * + * This method is registered as the Twig `sort_by` filter. You can use this + * filter to e.g. sort the pages array by a arbitrary meta value. Calling + * `{{ pages|sort_by([ "meta", "nav" ]) }}` returns all pages sorted by the + * meta value `nav`. The sorting algorithm will never assume equality of + * two values, it will then fall back to the original order. The result is + * always sorted in ascending order, apply Twigs `reverse` filter to + * achieve a descending order. + * + * @param array|Traversable $var variable to sort + * @param mixed $sortKeyPath key to use for sorting; either + * a scalar or a array interpreted as key path (i.e. ['foo', 'bar'] + * will sort $var by $item['foo']['bar']) + * @param string $fallback specify what to do with items + * which don't contain the specified sort key; use "bottom" (default) + * to move these items to the end of the sorted array, "top" to rank + * them first, "keep" to keep the original order, or "remove" to remove + * these items + * + * @return array sorted array + * + * @throws Twig_Error_Runtime + */ + public function sortByFilter($var, $sortKeyPath, $fallback = 'bottom') + { + if (is_object($var) && ($var instanceof Traversable)) { + $var = iterator_to_array($var, true); + } elseif (!is_array($var)) { + throw new Twig_Error_Runtime(sprintf( + 'The sort_by filter only works with arrays or "Traversable", got "%s"', + is_object($var) ? get_class($var) : gettype($var) + )); + } + if (($fallback !== 'top') && ($fallback !== 'bottom') && ($fallback !== 'keep') && ($fallback !== "remove")) { + throw new Twig_Error_Runtime( + 'The sort_by filter only supports the "top", "bottom", "keep" and "remove" fallbacks' + ); + } + + $twigExtension = $this; + $varKeys = array_keys($var); + $removeItems = array(); + uksort($var, function ($a, $b) use ($twigExtension, $var, $varKeys, $sortKeyPath, $fallback, &$removeItems) { + $aSortValue = $twigExtension->getKeyOfVar($var[$a], $sortKeyPath); + $aSortValueNull = ($aSortValue === null); + + $bSortValue = $twigExtension->getKeyOfVar($var[$b], $sortKeyPath); + $bSortValueNull = ($bSortValue === null); + + if (($fallback === 'remove') && ($aSortValueNull || $bSortValueNull)) { + if ($aSortValueNull) { + $removeItems[$a] = $var[$a]; + } + if ($bSortValueNull) { + $removeItems[$b] = $var[$b]; + } + return ($aSortValueNull - $bSortValueNull); + } elseif ($aSortValueNull xor $bSortValueNull) { + if ($fallback === 'top') { + return ($aSortValueNull - $bSortValueNull) * -1; + } elseif ($fallback === 'bottom') { + return ($aSortValueNull - $bSortValueNull); + } + } elseif (!$aSortValueNull && !$bSortValueNull) { + if ($aSortValue != $bSortValue) { + return ($aSortValue > $bSortValue) ? 1 : -1; + } + } + + // never assume equality; fallback to original order + $aIndex = array_search($a, $varKeys); + $bIndex = array_search($b, $varKeys); + return ($aIndex > $bIndex) ? 1 : -1; + }); + + if ($removeItems) { + $var = array_diff_key($var, $removeItems); + } + + return $var; + } + + /** + * Returns the value of a variable item specified by a scalar key or a + * arbitrary deep sub-key using a key path + * + * @param array|Traversable|ArrayAccess|object $var base variable + * @param mixed $keyPath scalar key or a + * array interpreted as key path (when passing e.g. ['foo', 'bar'], + * the method will return $var['foo']['bar']) specifying the value + * + * @return mixed the requested value or NULL when the given key or key path + * didn't match + */ + public static function getKeyOfVar($var, $keyPath) + { + if (!$keyPath) { + return null; + } elseif (!is_array($keyPath)) { + $keyPath = array($keyPath); + } + + foreach ($keyPath as $key) { + if (is_object($var)) { + if ($var instanceof ArrayAccess) { + // use ArrayAccess, see below + } elseif ($var instanceof Traversable) { + $var = iterator_to_array($var); + } elseif (isset($var->{$key})) { + $var = $var->{$key}; + continue; + } elseif (is_callable(array($var, 'get' . ucfirst($key)))) { + try { + $var = call_user_func(array($var, 'get' . ucfirst($key))); + continue; + } catch (BadMethodCallException $e) { + return null; + } + } else { + return null; + } + } elseif (!is_array($var)) { + return null; + } + + if (isset($var[$key])) { + $var = $var[$key]; + continue; + } + + return null; + } + + return $var; + } + + /** + * Filters a URL GET parameter with a specified filter + * + * The Twig function disallows the use of the `callback` filter. + * + * @see Pico::getUrlParameter() + * + * @param string $name name of the URL GET parameter + * to filter + * @param int|string $filter the filter to apply + * @param mixed|array $options either a associative options + * array to be used by the filter or a scalar default value + * @param int|string|int[]|string[] $flags flags and flag strings to be + * used by the filter + * + * @return mixed either the filtered data, FALSE if the filter fails, or + * NULL if the URL GET parameter doesn't exist and no default value is + * given + */ + public function urlParamFunction($name, $filter = '', $options = null, $flags = null) + { + $filter = $filter ? (is_string($filter) ? filter_id($filter) : (int) $filter) : false; + if (!$filter || ($filter === FILTER_CALLBACK)) { + return false; + } + + return $this->pico->getUrlParameter($name, $filter, $options, $flags); + } + + /** + * Filters a HTTP POST parameter with a specified filter + * + * The Twig function disallows the use of the `callback` filter. + * + * @see Pico::getFormParameter() + * + * @param string $name name of the HTTP POST + * parameter to filter + * @param int|string $filter the filter to apply + * @param mixed|array $options either a associative options + * array to be used by the filter or a scalar default value + * @param int|string|int[]|string[] $flags flags and flag strings to be + * used by the filter + * + * @return mixed either the filtered data, FALSE if the filter fails, or + * NULL if the HTTP POST parameter doesn't exist and no default value + * is given + */ + public function formParamFunction($name, $filter = '', $options = null, $flags = null) + { + $filter = $filter ? (is_string($filter) ? filter_id($filter) : (int) $filter) : false; + if (!$filter || ($filter === FILTER_CALLBACK)) { + return false; + } + + return $this->pico->getFormParameter($name, $filter, $options, $flags); + } + + /** + * Returns all pages within a particular branch of Pico's page tree + * + * This function should be used most of the time when dealing with Pico's + * pages array, as it allows one to easily traverse Pico's pages tree + * ({@see Pico::getPageTree()}) to retrieve a subset of Pico's pages array + * in a very convenient and performant way. + * + * The function's default parameters are `$start = ""`, `$depth = 0`, + * `$depthOffset = 0` and `$offset = 1`. A positive `$offset` is equivalent + * to `$depth = $depth + $offset`, `$depthOffset = $depthOffset + $offset` + * and `$offset = 0`. + * + * Consequently the default `$start = ""`, `$depth = 0`, `$depthOffset = 0` + * and `$offset = 1` is equivalent to `$depth = 1`, `$depthOffset = 1` and + * `$offset = 0`. `$start = ""` instruct the function to start from the + * root node (i.e. the node of Pico's main index page at `index.md`). + * `$depth` tells the function what pages to return. In this example, + * `$depth = 1` matches the start node (i.e. the zeroth generation) and all + * its descendant pages until the first generation (i.e. the start node's + * children). `$depthOffset` instructs the function to exclude some of the + * older generations. `$depthOffset = 1` specifically tells the function + * to exclude the zeroth generation, so that the function returns all of + * Pico's main index page's direct child pages (like `sub/index.md` and + * `page.md`, but not `sub/page.md`) only. + * + * Passing `$depthOffset = -1` only is the same as passing `$start = ""`, + * `$depth = 1`, `$depthOffset = 0` and `$offset = 0`. The only difference + * is that `$depthOffset` won't exclude the zeroth generation, so that the + * function returns Pico's main index page as well as all of its direct + * child pages. + * + * Passing `$depth = 0`, `$depthOffset = -2` and `$offset = 2` is the same + * as passing `$depth = 2`, `$depthOffset = 0` and `$offset = 0`. Both will + * return the zeroth, first and second generation of pages. For Pico's main + * index page this would be `index.md` (0th gen), `sub/index.md` (1st gen), + * `sub/page.md` (2nd gen) and `page.md` (1st gen). If you want to return + * 2nd gen pages only, pass `$offset = 2` only (with implicit `$depth = 0` + * and `$depthOffset = 0` it's the same as `$depth = 2`, `$depthOffset = 2` + * and `$offset = 0`). + * + * Instead of an integer you can also pass `$depth = null`. This is the + * same as passing an infinitely large number as `$depth`, so that this + * function simply returns all descendant pages. Consequently passing + * `$start = ""`, `$depth = null`, `$depthOffset = 0` and `$offset = 0` + * returns Pico's full pages array. + * + * If `$depth` is negative after taking `$offset` into consideration, the + * function will throw a {@see Twig_Error_Runtime} exception, since this + * would simply make no sense and is likely an error. Passing a negative + * `$depthOffset` is equivalent to passing `$depthOffset = 0`. + * + * But what about a negative `$offset`? Passing `$offset = -1` instructs + * the function not to start from the given `$start` node, but its parent + * node. Consequently `$offset = -2` instructs the function to use the + * `$start` node's grandparent node. Obviously this won't make any sense + * for Pico's root node, but just image `$start = "sub/index"`. Passing + * this together with `$offset = -1` is equivalent to `$start = ""` and + * `$offset = 0`. + * + * @param string $start name of the node to start from + * @param int|null $depth return pages until the given maximum depth; + * pass NULL to return all descendant pages; defaults to 0 + * @param int $depthOffset start returning pages from the given + * minimum depth; defaults to 0 + * @param int $offset ascend (positive) or descend (negative) the + * given number of branches before returning pages; defaults to 1 + * + * @return array[] the data of the matched pages + * + * @throws Twig_Error_Runtime + */ + public function pagesFunction($start = '', $depth = 0, $depthOffset = 0, $offset = 1) + { + $start = (string) $start; + if (basename($start) === 'index') { + $start = dirname($start); + } + + for (; $offset < 0; $offset++) { + if (in_array($start, array('', '.', '/'), true)) { + $offset = 0; + break; + } + + $start = dirname($start); + } + + $depth = ($depth !== null) ? $depth + $offset : null; + $depthOffset = $depthOffset + $offset; + + if (($depth !== null) && ($depth < 0)) { + throw new Twig_Error_Runtime('The pages function doesn\'t support negative depths'); + } + + $pageTree = $this->getPico()->getPageTree(); + if (in_array($start, array('', '.', '/'), true)) { + if (($depth === null) && ($depthOffset <= 0)) { + return $this->getPico()->getPages(); + } + + $startNode = isset($pageTree['']['/']) ? $pageTree['']['/'] : null; + } else { + $branch = dirname($start); + $branch = ($branch !== '.') ? $branch : '/'; + $node = (($branch !== '/') ? $branch . '/' : '') . basename($start); + $startNode = isset($pageTree[$branch][$node]) ? $pageTree[$branch][$node] : null; + } + + if (!$startNode) { + return array(); + } + + $getPagesClosure = function ($nodes, $depth, $depthOffset) use (&$getPagesClosure) { + $pages = array(); + foreach ($nodes as $node) { + if (isset($node['page']) && ($depthOffset <= 0)) { + $pages[$node['page']['id']] = &$node['page']; + } + if (isset($node['children']) && ($depth > 0)) { + $pages += $getPagesClosure($node['children'], $depth - 1, $depthOffset - 1); + } + } + + return $pages; + }; + + return $getPagesClosure( + array($startNode), + ($depth !== null) ? $depth : INF, + $depthOffset + ); + } +} diff --git a/vendor/picocms/pico/plugins/DummyPlugin.php b/vendor/picocms/pico/plugins/DummyPlugin.php new file mode 100644 index 0000000..10d39b3 --- /dev/null +++ b/vendor/picocms/pico/plugins/DummyPlugin.php @@ -0,0 +1,504 @@ + + * + * SPDX-License-Identifier: MIT + * License-Filename: LICENSE + */ + +/** + * Pico dummy plugin - a template for plugins + * + * You're a plugin developer? This template may be helpful :-) + * Simply remove the events you don't need and add your own logic. + * + * @author Daniel Rudolf + * @link http://picocms.org + * @license http://opensource.org/licenses/MIT The MIT License + * @version 2.1 + */ +class DummyPlugin extends AbstractPicoPlugin +{ + /** + * API version used by this plugin + * + * @var int + */ + const API_VERSION = 3; + + /** + * This plugin is disabled by default + * + * Usually you should remove this class property (or set it to NULL) to + * leave the decision whether this plugin should be enabled or disabled by + * default up to Pico. If all the plugin's dependenies are fulfilled (see + * {@see DummyPlugin::$dependsOn}), Pico enables the plugin by default. + * Otherwise the plugin is silently disabled. + * + * If this plugin should never be disabled *silently* (e.g. when dealing + * with security-relevant stuff like access control, or similar), set this + * to TRUE. If Pico can't fulfill all the plugin's dependencies, it will + * throw an RuntimeException. + * + * If this plugin rather does some "crazy stuff" a user should really be + * aware of before using it, you can set this to FALSE. The user will then + * have to enable the plugin manually. However, if another plugin depends + * on this plugin, it might get enabled silently nevertheless. + * + * No matter what, the user can always explicitly enable or disable this + * plugin in Pico's config. + * + * @see AbstractPicoPlugin::$enabled + * @var bool|null + */ + protected $enabled = false; + + /** + * This plugin depends on ... + * + * If your plugin doesn't depend on any other plugin, remove this class + * property. + * + * @see AbstractPicoPlugin::$dependsOn + * @var string[] + */ + protected $dependsOn = array(); + + /** + * Triggered after Pico has loaded all available plugins + * + * This event is triggered nevertheless the plugin is enabled or not. + * It is NOT guaranteed that plugin dependencies are fulfilled! + * + * @see Pico::loadPlugin() + * @see Pico::getPlugin() + * @see Pico::getPlugins() + * + * @param object[] $plugins loaded plugin instances + */ + public function onPluginsLoaded(array $plugins) + { + // your code + } + + /** + * Triggered when Pico manually loads a plugin + * + * @see Pico::loadPlugin() + * @see Pico::getPlugin() + * @see Pico::getPlugins() + * + * @param object $plugin loaded plugin instance + */ + public function onPluginManuallyLoaded($plugin) + { + // your code + } + + /** + * Triggered after Pico has read its configuration + * + * @see Pico::getConfig() + * @see Pico::getBaseUrl() + * @see Pico::isUrlRewritingEnabled() + * + * @param array &$config array of config variables + */ + public function onConfigLoaded(array &$config) + { + // your code + } + + /** + * Triggered before Pico loads its theme + * + * @see Pico::loadTheme() + * @see DummyPlugin::onThemeLoaded() + * + * @param string &$theme name of current theme + */ + public function onThemeLoading(&$theme) + { + // your code + } + + /** + * Triggered after Pico loaded its theme + * + * @see DummyPlugin::onThemeLoading() + * @see Pico::getTheme() + * @see Pico::getThemeApiVersion() + * + * @param string $theme name of current theme + * @param int $themeApiVersion API version of the theme + * @param array &$themeConfig config array of the theme + */ + public function onThemeLoaded($theme, $themeApiVersion, array &$themeConfig) + { + // your code + } + + /** + * Triggered after Pico has evaluated the request URL + * + * @see Pico::getRequestUrl() + * + * @param string &$url part of the URL describing the requested contents + */ + public function onRequestUrl(&$url) + { + // your code + } + + /** + * Triggered after Pico has discovered the content file to serve + * + * @see Pico::resolveFilePath() + * @see Pico::getRequestFile() + * + * @param string &$file absolute path to the content file to serve + */ + public function onRequestFile(&$file) + { + // your code + } + + /** + * Triggered before Pico reads the contents of the file to serve + * + * @see Pico::loadFileContent() + * @see DummyPlugin::onContentLoaded() + */ + public function onContentLoading() + { + // your code + } + + /** + * Triggered before Pico reads the contents of a 404 file + * + * @see Pico::load404Content() + * @see DummyPlugin::on404ContentLoaded() + */ + public function on404ContentLoading() + { + // your code + } + + /** + * Triggered after Pico has read the contents of the 404 file + * + * @see DummyPlugin::on404ContentLoading() + * @see Pico::getRawContent() + * @see Pico::is404Content() + * + * @param string &$rawContent raw file contents + */ + public function on404ContentLoaded(&$rawContent) + { + // your code + } + + /** + * Triggered after Pico has read the contents of the file to serve + * + * If Pico serves a 404 file, this event is triggered with the raw contents + * of said 404 file. Use {@see Pico::is404Content()} to check for this + * case when necessary. + * + * @see DummyPlugin::onContentLoading() + * @see Pico::getRawContent() + * @see Pico::is404Content() + * + * @param string &$rawContent raw file contents + */ + public function onContentLoaded(&$rawContent) + { + // your code + } + + /** + * Triggered before Pico parses the meta header + * + * @see Pico::parseFileMeta() + * @see DummyPlugin::onMetaParsed() + */ + public function onMetaParsing() + { + // your code + } + + /** + * Triggered after Pico has parsed the meta header + * + * @see DummyPlugin::onMetaParsing() + * @see Pico::getFileMeta() + * + * @param string[] &$meta parsed meta data + */ + public function onMetaParsed(array &$meta) + { + // your code + } + + /** + * Triggered before Pico parses the pages content + * + * @see Pico::prepareFileContent() + * @see Pico::substituteFileContent() + * @see DummyPlugin::onContentPrepared() + * @see DummyPlugin::onContentParsed() + */ + public function onContentParsing() + { + // your code + } + + /** + * Triggered after Pico has prepared the raw file contents for parsing + * + * @see DummyPlugin::onContentParsing() + * @see Pico::parseFileContent() + * @see DummyPlugin::onContentParsed() + * + * @param string &$markdown Markdown contents of the requested page + */ + public function onContentPrepared(&$markdown) + { + // your code + } + + /** + * Triggered after Pico has parsed the contents of the file to serve + * + * @see DummyPlugin::onContentParsing() + * @see DummyPlugin::onContentPrepared() + * @see Pico::getFileContent() + * + * @param string &$content parsed contents (HTML) of the requested page + */ + public function onContentParsed(&$content) + { + // your code + } + + /** + * Triggered before Pico reads all known pages + * + * @see DummyPlugin::onPagesDiscovered() + * @see DummyPlugin::onPagesLoaded() + */ + public function onPagesLoading() + { + // your code + } + + /** + * Triggered before Pico loads a single page + * + * Set the `$skipFile` parameter to TRUE to remove this page from the pages + * array. Pico usually passes NULL by default, unless it is a conflicting + * page (i.e. `content/sub.md`, but there's also a `content/sub/index.md`), + * then it passes TRUE. Don't change this value incautiously if it isn't + * NULL! Someone likely set it to TRUE or FALSE on purpose... + * + * @see DummyPlugin::onSinglePageContent() + * @see DummyPlugin::onSinglePageLoaded() + * + * @param string $id relative path to the content file + * @param bool|null $skipPage set this to TRUE to remove this page from the + * pages array, otherwise leave it unchanged + */ + public function onSinglePageLoading($id, &$skipPage) + { + // your code + } + + /** + * Triggered when Pico loads the raw contents of a single page + * + * Please note that this event isn't triggered when the currently processed + * page is the requested page. The reason for this exception is that the + * raw contents of this page were loaded already. + * + * @see DummyPlugin::onSinglePageLoading() + * @see DummyPlugin::onSinglePageLoaded() + * + * @param string $id relative path to the content file + * @param string &$rawContent raw file contents + */ + public function onSinglePageContent($id, &$rawContent) + { + // your code + } + + /** + * Triggered when Pico loads a single page + * + * Please refer to {@see Pico::readPages()} for information about the + * structure of a single page's data. + * + * @see DummyPlugin::onSinglePageLoading() + * @see DummyPlugin::onSinglePageContent() + * + * @param array &$pageData data of the loaded page + */ + public function onSinglePageLoaded(array &$pageData) + { + // your code + } + + /** + * Triggered after Pico has discovered all known pages + * + * Pico's pages array isn't sorted until the `onPagesLoaded` event is + * triggered. Please refer to {@see Pico::readPages()} for information + * about the structure of Pico's pages array and the structure of a single + * page's data. + * + * @see DummyPlugin::onPagesLoading() + * @see DummyPlugin::onPagesLoaded() + * + * @param array[] &$pages list of all known pages + */ + public function onPagesDiscovered(array &$pages) + { + // your code + } + + /** + * Triggered after Pico has sorted the pages array + * + * Please refer to {@see Pico::readPages()} for information about the + * structure of Pico's pages array and the structure of a single page's + * data. + * + * @see DummyPlugin::onPagesLoading() + * @see DummyPlugin::onPagesDiscovered() + * @see Pico::getPages() + * + * @param array[] &$pages sorted list of all known pages + */ + public function onPagesLoaded(array &$pages) + { + // your code + } + + /** + * Triggered when Pico discovered the current, previous and next pages + * + * If Pico isn't serving a regular page, but a plugin's virtual page, there + * will neither be a current, nor previous or next pages. Please refer to + * {@see Pico::readPages()} for information about the structure of a single + * page's data. + * + * @see Pico::getCurrentPage() + * @see Pico::getPreviousPage() + * @see Pico::getNextPage() + * + * @param array|null &$currentPage data of the page being served + * @param array|null &$previousPage data of the previous page + * @param array|null &$nextPage data of the next page + */ + public function onCurrentPageDiscovered( + array &$currentPage = null, + array &$previousPage = null, + array &$nextPage = null + ) { + // your code + } + + /** + * Triggered after Pico built the page tree + * + * Please refer to {@see Pico::buildPageTree()} for information about + * the structure of Pico's page tree array. + * + * @see Pico::getPageTree() + * + * @param array &$pageTree page tree + */ + public function onPageTreeBuilt(array &$pageTree) + { + // your code + } + + /** + * Triggered before Pico renders the page + * + * @see DummyPlugin::onPageRendered() + * + * @param string &$templateName file name of the template + * @param array &$twigVariables template variables + */ + public function onPageRendering(&$templateName, array &$twigVariables) + { + // your code + } + + /** + * Triggered after Pico has rendered the page + * + * @see DummyPlugin::onPageRendering() + * + * @param string &$output contents which will be sent to the user + */ + public function onPageRendered(&$output) + { + // your code + } + + /** + * Triggered when Pico reads its known meta header fields + * + * @see Pico::getMetaHeaders() + * + * @param string[] &$headers list of known meta header fields; the array + * key specifies the YAML key to search for, the array value is later + * used to access the found value + */ + public function onMetaHeaders(array &$headers) + { + // your code + } + + /** + * Triggered when Pico registers the YAML parser + * + * @see Pico::getYamlParser() + * + * @param \Symfony\Component\Yaml\Parser &$yamlParser YAML parser instance + */ + public function onYamlParserRegistered(\Symfony\Component\Yaml\Parser &$yamlParser) + { + // your code + } + + /** + * Triggered when Pico registers the Parsedown parser + * + * @see Pico::getParsedown() + * + * @param Parsedown &$parsedown Parsedown instance + */ + public function onParsedownRegistered(Parsedown &$parsedown) + { + // your code + } + + /** + * Triggered when Pico registers the twig template engine + * + * @see Pico::getTwig() + * + * @param Twig_Environment &$twig Twig instance + */ + public function onTwigRegistered(Twig_Environment &$twig) + { + // your code + } +} diff --git a/vendor/symfony/polyfill-ctype/Ctype.php b/vendor/symfony/polyfill-ctype/Ctype.php new file mode 100644 index 0000000..58414dc --- /dev/null +++ b/vendor/symfony/polyfill-ctype/Ctype.php @@ -0,0 +1,227 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Polyfill\Ctype; + +/** + * Ctype implementation through regex. + * + * @internal + * + * @author Gert de Pagter + */ +final class Ctype +{ + /** + * Returns TRUE if every character in text is either a letter or a digit, FALSE otherwise. + * + * @see https://php.net/ctype-alnum + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_alnum($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is a letter, FALSE otherwise. + * + * @see https://php.net/ctype-alpha + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_alpha($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Za-z]/', $text); + } + + /** + * Returns TRUE if every character in text is a control character from the current locale, FALSE otherwise. + * + * @see https://php.net/ctype-cntrl + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_cntrl($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^\x00-\x1f\x7f]/', $text); + } + + /** + * Returns TRUE if every character in the string text is a decimal digit, FALSE otherwise. + * + * @see https://php.net/ctype-digit + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_digit($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^0-9]/', $text); + } + + /** + * Returns TRUE if every character in text is printable and actually creates visible output (no white space), FALSE otherwise. + * + * @see https://php.net/ctype-graph + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_graph($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-~]/', $text); + } + + /** + * Returns TRUE if every character in text is a lowercase letter. + * + * @see https://php.net/ctype-lower + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_lower($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^a-z]/', $text); + } + + /** + * Returns TRUE if every character in text will actually create output (including blanks). Returns FALSE if text contains control characters or characters that do not have any output or control function at all. + * + * @see https://php.net/ctype-print + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_print($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^ -~]/', $text); + } + + /** + * Returns TRUE if every character in text is printable, but neither letter, digit or blank, FALSE otherwise. + * + * @see https://php.net/ctype-punct + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_punct($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^!-\/\:-@\[-`\{-~]/', $text); + } + + /** + * Returns TRUE if every character in text creates some sort of white space, FALSE otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. + * + * @see https://php.net/ctype-space + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_space($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^\s]/', $text); + } + + /** + * Returns TRUE if every character in text is an uppercase letter. + * + * @see https://php.net/ctype-upper + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_upper($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Z]/', $text); + } + + /** + * Returns TRUE if every character in text is a hexadecimal 'digit', that is a decimal digit or a character from [A-Fa-f] , FALSE otherwise. + * + * @see https://php.net/ctype-xdigit + * + * @param string|int $text + * + * @return bool + */ + public static function ctype_xdigit($text) + { + $text = self::convert_int_to_char_for_ctype($text); + + return \is_string($text) && '' !== $text && !preg_match('/[^A-Fa-f0-9]/', $text); + } + + /** + * Converts integers to their char versions according to normal ctype behaviour, if needed. + * + * If an integer between -128 and 255 inclusive is provided, + * it is interpreted as the ASCII value of a single character + * (negative values have 256 added in order to allow characters in the Extended ASCII range). + * Any other integer is interpreted as a string containing the decimal digits of the integer. + * + * @param string|int $int + * + * @return mixed + */ + private static function convert_int_to_char_for_ctype($int) + { + if (!\is_int($int)) { + return $int; + } + + if ($int < -128 || $int > 255) { + return (string) $int; + } + + if ($int < 0) { + $int += 256; + } + + return \chr($int); + } +} diff --git a/vendor/symfony/polyfill-ctype/LICENSE b/vendor/symfony/polyfill-ctype/LICENSE new file mode 100644 index 0000000..3f853aa --- /dev/null +++ b/vendor/symfony/polyfill-ctype/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2018-2019 Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/polyfill-ctype/README.md b/vendor/symfony/polyfill-ctype/README.md new file mode 100644 index 0000000..8add1ab --- /dev/null +++ b/vendor/symfony/polyfill-ctype/README.md @@ -0,0 +1,12 @@ +Symfony Polyfill / Ctype +======================== + +This component provides `ctype_*` functions to users who run php versions without the ctype extension. + +More information can be found in the +[main Polyfill README](https://github.com/symfony/polyfill/blob/master/README.md). + +License +======= + +This library is released under the [MIT license](LICENSE). diff --git a/vendor/symfony/polyfill-ctype/bootstrap.php b/vendor/symfony/polyfill-ctype/bootstrap.php new file mode 100644 index 0000000..8d6fc4b --- /dev/null +++ b/vendor/symfony/polyfill-ctype/bootstrap.php @@ -0,0 +1,46 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +use Symfony\Polyfill\Ctype as p; + +if (!function_exists('ctype_alnum')) { + function ctype_alnum($text) { return p\Ctype::ctype_alnum($text); } +} +if (!function_exists('ctype_alpha')) { + function ctype_alpha($text) { return p\Ctype::ctype_alpha($text); } +} +if (!function_exists('ctype_cntrl')) { + function ctype_cntrl($text) { return p\Ctype::ctype_cntrl($text); } +} +if (!function_exists('ctype_digit')) { + function ctype_digit($text) { return p\Ctype::ctype_digit($text); } +} +if (!function_exists('ctype_graph')) { + function ctype_graph($text) { return p\Ctype::ctype_graph($text); } +} +if (!function_exists('ctype_lower')) { + function ctype_lower($text) { return p\Ctype::ctype_lower($text); } +} +if (!function_exists('ctype_print')) { + function ctype_print($text) { return p\Ctype::ctype_print($text); } +} +if (!function_exists('ctype_punct')) { + function ctype_punct($text) { return p\Ctype::ctype_punct($text); } +} +if (!function_exists('ctype_space')) { + function ctype_space($text) { return p\Ctype::ctype_space($text); } +} +if (!function_exists('ctype_upper')) { + function ctype_upper($text) { return p\Ctype::ctype_upper($text); } +} +if (!function_exists('ctype_xdigit')) { + function ctype_xdigit($text) { return p\Ctype::ctype_xdigit($text); } +} diff --git a/vendor/symfony/polyfill-ctype/composer.json b/vendor/symfony/polyfill-ctype/composer.json new file mode 100644 index 0000000..90108c6 --- /dev/null +++ b/vendor/symfony/polyfill-ctype/composer.json @@ -0,0 +1,38 @@ +{ + "name": "symfony/polyfill-ctype", + "type": "library", + "description": "Symfony polyfill for ctype functions", + "keywords": ["polyfill", "compatibility", "portable", "ctype"], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Gert de Pagter", + "email": "BackEndTea@gmail.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=5.3.3" + }, + "autoload": { + "psr-4": { "Symfony\\Polyfill\\Ctype\\": "" }, + "files": [ "bootstrap.php" ] + }, + "suggest": { + "ext-ctype": "For best performance" + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-master": "1.18-dev" + }, + "thanks": { + "name": "symfony/polyfill", + "url": "https://github.com/symfony/polyfill" + } + } +} diff --git a/vendor/symfony/yaml/.gitignore b/vendor/symfony/yaml/.gitignore new file mode 100644 index 0000000..c49a5d8 --- /dev/null +++ b/vendor/symfony/yaml/.gitignore @@ -0,0 +1,3 @@ +vendor/ +composer.lock +phpunit.xml diff --git a/vendor/symfony/yaml/CHANGELOG.md b/vendor/symfony/yaml/CHANGELOG.md new file mode 100644 index 0000000..f55b570 --- /dev/null +++ b/vendor/symfony/yaml/CHANGELOG.md @@ -0,0 +1,28 @@ +CHANGELOG +========= + +2.8.0 +----- + + * Deprecated usage of a colon in an unquoted mapping value + * Deprecated usage of @, \`, | and > at the beginning of an unquoted string + * When surrounding strings with double-quotes, you must now escape `\` characters. Not + escaping those characters (when surrounded by double-quotes) is deprecated. + + Before: + + ```yml + class: "Foo\Var" + ``` + + After: + + ```yml + class: "Foo\\Var" + ``` + +2.1.0 +----- + + * Yaml::parse() does not evaluate loaded files as PHP files by default + anymore (call Yaml::enablePhpParsing() to get back the old behavior) diff --git a/vendor/symfony/yaml/Dumper.php b/vendor/symfony/yaml/Dumper.php new file mode 100644 index 0000000..8b523d1 --- /dev/null +++ b/vendor/symfony/yaml/Dumper.php @@ -0,0 +1,77 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml; + +/** + * Dumper dumps PHP variables to YAML strings. + * + * @author Fabien Potencier + */ +class Dumper +{ + /** + * The amount of spaces to use for indentation of nested nodes. + * + * @var int + */ + protected $indentation = 4; + + /** + * Sets the indentation. + * + * @param int $num The amount of spaces to use for indentation of nested nodes + */ + public function setIndentation($num) + { + if ($num < 1) { + throw new \InvalidArgumentException('The indentation must be greater than zero.'); + } + + $this->indentation = (int) $num; + } + + /** + * Dumps a PHP value to YAML. + * + * @param mixed $input The PHP value + * @param int $inline The level where you switch to inline YAML + * @param int $indent The level of indentation (used internally) + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * + * @return string The YAML representation of the PHP value + */ + public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false) + { + $output = ''; + $prefix = $indent ? str_repeat(' ', $indent) : ''; + + if ($inline <= 0 || !\is_array($input) || empty($input)) { + $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport); + } else { + $isAHash = Inline::isHash($input); + + foreach ($input as $key => $value) { + $willBeInlined = $inline - 1 <= 0 || !\is_array($value) || empty($value); + + $output .= sprintf('%s%s%s%s', + $prefix, + $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-', + $willBeInlined ? ' ' : "\n", + $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport) + ).($willBeInlined ? "\n" : ''); + } + } + + return $output; + } +} diff --git a/vendor/symfony/yaml/Escaper.php b/vendor/symfony/yaml/Escaper.php new file mode 100644 index 0000000..2b1321f --- /dev/null +++ b/vendor/symfony/yaml/Escaper.php @@ -0,0 +1,101 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml; + +/** + * Escaper encapsulates escaping rules for single and double-quoted + * YAML strings. + * + * @author Matthew Lewinski + * + * @internal + */ +class Escaper +{ + // Characters that would cause a dumped string to require double quoting. + const REGEX_CHARACTER_TO_ESCAPE = "[\\x00-\\x1f]|\xc2\x85|\xc2\xa0|\xe2\x80\xa8|\xe2\x80\xa9"; + + // Mapping arrays for escaping a double quoted string. The backslash is + // first to ensure proper escaping because str_replace operates iteratively + // on the input arrays. This ordering of the characters avoids the use of strtr, + // which performs more slowly. + private static $escapees = array('\\', '\\\\', '\\"', '"', + "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", + "\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f", + "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17", + "\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f", + "\xc2\x85", "\xc2\xa0", "\xe2\x80\xa8", "\xe2\x80\xa9", + ); + private static $escaped = array('\\\\', '\\"', '\\\\', '\\"', + '\\0', '\\x01', '\\x02', '\\x03', '\\x04', '\\x05', '\\x06', '\\a', + '\\b', '\\t', '\\n', '\\v', '\\f', '\\r', '\\x0e', '\\x0f', + '\\x10', '\\x11', '\\x12', '\\x13', '\\x14', '\\x15', '\\x16', '\\x17', + '\\x18', '\\x19', '\\x1a', '\\e', '\\x1c', '\\x1d', '\\x1e', '\\x1f', + '\\N', '\\_', '\\L', '\\P', + ); + + /** + * Determines if a PHP value would require double quoting in YAML. + * + * @param string $value A PHP value + * + * @return bool True if the value would require double quotes + */ + public static function requiresDoubleQuoting($value) + { + return 0 < preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value); + } + + /** + * Escapes and surrounds a PHP value with double quotes. + * + * @param string $value A PHP value + * + * @return string The quoted, escaped string + */ + public static function escapeWithDoubleQuotes($value) + { + return sprintf('"%s"', str_replace(self::$escapees, self::$escaped, $value)); + } + + /** + * Determines if a PHP value would require single quoting in YAML. + * + * @param string $value A PHP value + * + * @return bool True if the value would require single quotes + */ + public static function requiresSingleQuoting($value) + { + // Determines if a PHP value is entirely composed of a value that would + // require single quoting in YAML. + if (\in_array(strtolower($value), array('null', '~', 'true', 'false', 'y', 'n', 'yes', 'no', 'on', 'off'))) { + return true; + } + + // Determines if the PHP value contains any single characters that would + // cause it to require single quoting in YAML. + return 0 < preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ \- ? | < > = ! % @ ` ]/x', $value); + } + + /** + * Escapes and surrounds a PHP value with single quotes. + * + * @param string $value A PHP value + * + * @return string The quoted, escaped string + */ + public static function escapeWithSingleQuotes($value) + { + return sprintf("'%s'", str_replace('\'', '\'\'', $value)); + } +} diff --git a/vendor/symfony/yaml/Exception/DumpException.php b/vendor/symfony/yaml/Exception/DumpException.php new file mode 100644 index 0000000..cce972f --- /dev/null +++ b/vendor/symfony/yaml/Exception/DumpException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Exception; + +/** + * Exception class thrown when an error occurs during dumping. + * + * @author Fabien Potencier + */ +class DumpException extends RuntimeException +{ +} diff --git a/vendor/symfony/yaml/Exception/ExceptionInterface.php b/vendor/symfony/yaml/Exception/ExceptionInterface.php new file mode 100644 index 0000000..ad850ee --- /dev/null +++ b/vendor/symfony/yaml/Exception/ExceptionInterface.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Exception; + +/** + * Exception interface for all exceptions thrown by the component. + * + * @author Fabien Potencier + */ +interface ExceptionInterface +{ +} diff --git a/vendor/symfony/yaml/Exception/ParseException.php b/vendor/symfony/yaml/Exception/ParseException.php new file mode 100644 index 0000000..60802b6 --- /dev/null +++ b/vendor/symfony/yaml/Exception/ParseException.php @@ -0,0 +1,144 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Exception; + +/** + * Exception class thrown when an error occurs during parsing. + * + * @author Fabien Potencier + */ +class ParseException extends RuntimeException +{ + private $parsedFile; + private $parsedLine; + private $snippet; + private $rawMessage; + + /** + * @param string $message The error message + * @param int $parsedLine The line where the error occurred + * @param string|null $snippet The snippet of code near the problem + * @param string|null $parsedFile The file name where the error occurred + * @param \Exception|null $previous The previous exception + */ + public function __construct($message, $parsedLine = -1, $snippet = null, $parsedFile = null, \Exception $previous = null) + { + $this->parsedFile = $parsedFile; + $this->parsedLine = $parsedLine; + $this->snippet = $snippet; + $this->rawMessage = $message; + + $this->updateRepr(); + + parent::__construct($this->message, 0, $previous); + } + + /** + * Gets the snippet of code near the error. + * + * @return string The snippet of code + */ + public function getSnippet() + { + return $this->snippet; + } + + /** + * Sets the snippet of code near the error. + * + * @param string $snippet The code snippet + */ + public function setSnippet($snippet) + { + $this->snippet = $snippet; + + $this->updateRepr(); + } + + /** + * Gets the filename where the error occurred. + * + * This method returns null if a string is parsed. + * + * @return string The filename + */ + public function getParsedFile() + { + return $this->parsedFile; + } + + /** + * Sets the filename where the error occurred. + * + * @param string $parsedFile The filename + */ + public function setParsedFile($parsedFile) + { + $this->parsedFile = $parsedFile; + + $this->updateRepr(); + } + + /** + * Gets the line where the error occurred. + * + * @return int The file line + */ + public function getParsedLine() + { + return $this->parsedLine; + } + + /** + * Sets the line where the error occurred. + * + * @param int $parsedLine The file line + */ + public function setParsedLine($parsedLine) + { + $this->parsedLine = $parsedLine; + + $this->updateRepr(); + } + + private function updateRepr() + { + $this->message = $this->rawMessage; + + $dot = false; + if ('.' === substr($this->message, -1)) { + $this->message = substr($this->message, 0, -1); + $dot = true; + } + + if (null !== $this->parsedFile) { + if (\PHP_VERSION_ID >= 50400) { + $jsonOptions = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE; + } else { + $jsonOptions = 0; + } + $this->message .= sprintf(' in %s', json_encode($this->parsedFile, $jsonOptions)); + } + + if ($this->parsedLine >= 0) { + $this->message .= sprintf(' at line %d', $this->parsedLine); + } + + if ($this->snippet) { + $this->message .= sprintf(' (near "%s")', $this->snippet); + } + + if ($dot) { + $this->message .= '.'; + } + } +} diff --git a/vendor/symfony/yaml/Exception/RuntimeException.php b/vendor/symfony/yaml/Exception/RuntimeException.php new file mode 100644 index 0000000..3f36b73 --- /dev/null +++ b/vendor/symfony/yaml/Exception/RuntimeException.php @@ -0,0 +1,21 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Exception; + +/** + * Exception class thrown when an error occurs during parsing. + * + * @author Romain Neutron + */ +class RuntimeException extends \RuntimeException implements ExceptionInterface +{ +} diff --git a/vendor/symfony/yaml/Inline.php b/vendor/symfony/yaml/Inline.php new file mode 100644 index 0000000..639ff4a --- /dev/null +++ b/vendor/symfony/yaml/Inline.php @@ -0,0 +1,609 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml; + +use Symfony\Component\Yaml\Exception\DumpException; +use Symfony\Component\Yaml\Exception\ParseException; + +/** + * Inline implements a YAML parser/dumper for the YAML inline syntax. + * + * @author Fabien Potencier + */ +class Inline +{ + const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*+(?:\\\\.[^"\\\\]*+)*+)"|\'([^\']*+(?:\'\'[^\']*+)*+)\')'; + + private static $exceptionOnInvalidType = false; + private static $objectSupport = false; + private static $objectForMap = false; + + /** + * Converts a YAML string to a PHP value. + * + * @param string $value A YAML string + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * @param bool $objectForMap True if maps should return a stdClass instead of array() + * @param array $references Mapping of variable names to values + * + * @return mixed A PHP value + * + * @throws ParseException + */ + public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false, $references = array()) + { + self::$exceptionOnInvalidType = $exceptionOnInvalidType; + self::$objectSupport = $objectSupport; + self::$objectForMap = $objectForMap; + + $value = trim($value); + + if ('' === $value) { + return ''; + } + + if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('ASCII'); + } + + $i = 0; + switch ($value[0]) { + case '[': + $result = self::parseSequence($value, $i, $references); + ++$i; + break; + case '{': + $result = self::parseMapping($value, $i, $references); + ++$i; + break; + default: + $result = self::parseScalar($value, null, array('"', "'"), $i, true, $references); + } + + // some comments are allowed at the end + if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) { + throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i))); + } + + if (isset($mbEncoding)) { + mb_internal_encoding($mbEncoding); + } + + return $result; + } + + /** + * Dumps a given PHP variable to a YAML string. + * + * @param mixed $value The PHP variable to convert + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * + * @return string The YAML string representing the PHP value + * + * @throws DumpException When trying to dump PHP resource + */ + public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false) + { + switch (true) { + case \is_resource($value): + if ($exceptionOnInvalidType) { + throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value))); + } + + return 'null'; + case \is_object($value): + if ($objectSupport) { + return '!php/object:'.serialize($value); + } + + if ($exceptionOnInvalidType) { + throw new DumpException('Object support when dumping a YAML file has been disabled.'); + } + + return 'null'; + case \is_array($value): + return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport); + case null === $value: + return 'null'; + case true === $value: + return 'true'; + case false === $value: + return 'false'; + case ctype_digit($value): + return \is_string($value) ? "'$value'" : (int) $value; + case is_numeric($value): + $locale = setlocale(LC_NUMERIC, 0); + if (false !== $locale) { + setlocale(LC_NUMERIC, 'C'); + } + if (\is_float($value)) { + $repr = (string) $value; + if (is_infinite($value)) { + $repr = str_ireplace('INF', '.Inf', $repr); + } elseif (floor($value) == $value && $repr == $value) { + // Preserve float data type since storing a whole number will result in integer value. + $repr = '!!float '.$repr; + } + } else { + $repr = \is_string($value) ? "'$value'" : (string) $value; + } + if (false !== $locale) { + setlocale(LC_NUMERIC, $locale); + } + + return $repr; + case '' == $value: + return "''"; + case Escaper::requiresDoubleQuoting($value): + return Escaper::escapeWithDoubleQuotes($value); + case Escaper::requiresSingleQuoting($value): + case Parser::preg_match(self::getHexRegex(), $value): + case Parser::preg_match(self::getTimestampRegex(), $value): + return Escaper::escapeWithSingleQuotes($value); + default: + return $value; + } + } + + /** + * Check if given array is hash or just normal indexed array. + * + * @internal + * + * @param array $value The PHP array to check + * + * @return bool true if value is hash array, false otherwise + */ + public static function isHash(array $value) + { + $expectedKey = 0; + + foreach ($value as $key => $val) { + if ($key !== $expectedKey++) { + return true; + } + } + + return false; + } + + /** + * Dumps a PHP array to a YAML string. + * + * @param array $value The PHP array to dump + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * + * @return string The YAML string representing the PHP array + */ + private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport) + { + // array + if ($value && !self::isHash($value)) { + $output = array(); + foreach ($value as $val) { + $output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport); + } + + return sprintf('[%s]', implode(', ', $output)); + } + + // hash + $output = array(); + foreach ($value as $key => $val) { + $output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport)); + } + + return sprintf('{ %s }', implode(', ', $output)); + } + + /** + * Parses a YAML scalar. + * + * @param string $scalar + * @param string[] $delimiters + * @param string[] $stringDelimiters + * @param int &$i + * @param bool $evaluate + * @param array $references + * + * @return string + * + * @throws ParseException When malformed inline YAML string is parsed + * + * @internal + */ + public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array()) + { + if (\in_array($scalar[$i], $stringDelimiters)) { + // quoted scalar + $output = self::parseQuotedScalar($scalar, $i); + + if (null !== $delimiters) { + $tmp = ltrim(substr($scalar, $i), ' '); + if ('' === $tmp) { + throw new ParseException(sprintf('Unexpected end of line, expected one of "%s".', implode('', $delimiters))); + } + if (!\in_array($tmp[0], $delimiters)) { + throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i))); + } + } + } else { + // "normal" string + if (!$delimiters) { + $output = substr($scalar, $i); + $i += \strlen($output); + + // remove comments + if (Parser::preg_match('/[ \t]+#/', $output, $match, PREG_OFFSET_CAPTURE)) { + $output = substr($output, 0, $match[0][1]); + } + } elseif (Parser::preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) { + $output = $match[1]; + $i += \strlen($output); + } else { + throw new ParseException(sprintf('Malformed inline YAML string: %s.', $scalar)); + } + + // a non-quoted string cannot start with @ or ` (reserved) nor with a scalar indicator (| or >) + if ($output && ('@' === $output[0] || '`' === $output[0] || '|' === $output[0] || '>' === $output[0])) { + @trigger_error(sprintf('Not quoting the scalar "%s" starting with "%s" is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', $output, $output[0]), E_USER_DEPRECATED); + + // to be thrown in 3.0 + // throw new ParseException(sprintf('The reserved indicator "%s" cannot start a plain scalar; you need to quote the scalar.', $output[0])); + } + + if ($evaluate) { + $output = self::evaluateScalar($output, $references); + } + } + + return $output; + } + + /** + * Parses a YAML quoted scalar. + * + * @param string $scalar + * @param int &$i + * + * @return string + * + * @throws ParseException When malformed inline YAML string is parsed + */ + private static function parseQuotedScalar($scalar, &$i) + { + if (!Parser::preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { + throw new ParseException(sprintf('Malformed inline YAML string: %s.', substr($scalar, $i))); + } + + $output = substr($match[0], 1, \strlen($match[0]) - 2); + + $unescaper = new Unescaper(); + if ('"' == $scalar[$i]) { + $output = $unescaper->unescapeDoubleQuotedString($output); + } else { + $output = $unescaper->unescapeSingleQuotedString($output); + } + + $i += \strlen($match[0]); + + return $output; + } + + /** + * Parses a YAML sequence. + * + * @param string $sequence + * @param int &$i + * @param array $references + * + * @return array + * + * @throws ParseException When malformed inline YAML string is parsed + */ + private static function parseSequence($sequence, &$i = 0, $references = array()) + { + $output = array(); + $len = \strlen($sequence); + ++$i; + + // [foo, bar, ...] + while ($i < $len) { + switch ($sequence[$i]) { + case '[': + // nested sequence + $output[] = self::parseSequence($sequence, $i, $references); + break; + case '{': + // nested mapping + $output[] = self::parseMapping($sequence, $i, $references); + break; + case ']': + return $output; + case ',': + case ' ': + break; + default: + $isQuoted = \in_array($sequence[$i], array('"', "'")); + $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references); + + // the value can be an array if a reference has been resolved to an array var + if (!\is_array($value) && !$isQuoted && false !== strpos($value, ': ')) { + // embedded mapping? + try { + $pos = 0; + $value = self::parseMapping('{'.$value.'}', $pos, $references); + } catch (\InvalidArgumentException $e) { + // no, it's not + } + } + + $output[] = $value; + + --$i; + } + + ++$i; + } + + throw new ParseException(sprintf('Malformed inline YAML string: %s.', $sequence)); + } + + /** + * Parses a YAML mapping. + * + * @param string $mapping + * @param int &$i + * @param array $references + * + * @return array|\stdClass + * + * @throws ParseException When malformed inline YAML string is parsed + */ + private static function parseMapping($mapping, &$i = 0, $references = array()) + { + $output = array(); + $len = \strlen($mapping); + ++$i; + $allowOverwrite = false; + + // {foo: bar, bar:foo, ...} + while ($i < $len) { + switch ($mapping[$i]) { + case ' ': + case ',': + ++$i; + continue 2; + case '}': + if (self::$objectForMap) { + return (object) $output; + } + + return $output; + } + + // key + $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); + + if ('<<' === $key) { + $allowOverwrite = true; + } + + // value + $done = false; + + while ($i < $len) { + switch ($mapping[$i]) { + case '[': + // nested sequence + $value = self::parseSequence($mapping, $i, $references); + // Spec: Keys MUST be unique; first one wins. + // Parser cannot abort this mapping earlier, since lines + // are processed sequentially. + // But overwriting is allowed when a merge node is used in current block. + if ('<<' === $key) { + foreach ($value as $parsedValue) { + $output += $parsedValue; + } + } elseif ($allowOverwrite || !isset($output[$key])) { + $output[$key] = $value; + } + $done = true; + break; + case '{': + // nested mapping + $value = self::parseMapping($mapping, $i, $references); + // Spec: Keys MUST be unique; first one wins. + // Parser cannot abort this mapping earlier, since lines + // are processed sequentially. + // But overwriting is allowed when a merge node is used in current block. + if ('<<' === $key) { + $output += $value; + } elseif ($allowOverwrite || !isset($output[$key])) { + $output[$key] = $value; + } + $done = true; + break; + case ':': + case ' ': + break; + default: + $value = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references); + // Spec: Keys MUST be unique; first one wins. + // Parser cannot abort this mapping earlier, since lines + // are processed sequentially. + // But overwriting is allowed when a merge node is used in current block. + if ('<<' === $key) { + $output += $value; + } elseif ($allowOverwrite || !isset($output[$key])) { + $output[$key] = $value; + } + $done = true; + --$i; + } + + ++$i; + + if ($done) { + continue 2; + } + } + } + + throw new ParseException(sprintf('Malformed inline YAML string: %s.', $mapping)); + } + + /** + * Evaluates scalars and replaces magic values. + * + * @param string $scalar + * @param array $references + * + * @return mixed The evaluated YAML string + * + * @throws ParseException when object parsing support was disabled and the parser detected a PHP object or when a reference could not be resolved + */ + private static function evaluateScalar($scalar, $references = array()) + { + $scalar = trim($scalar); + $scalarLower = strtolower($scalar); + + if (0 === strpos($scalar, '*')) { + if (false !== $pos = strpos($scalar, '#')) { + $value = substr($scalar, 1, $pos - 2); + } else { + $value = substr($scalar, 1); + } + + // an unquoted * + if (false === $value || '' === $value) { + throw new ParseException('A reference must contain at least one character.'); + } + + if (!array_key_exists($value, $references)) { + throw new ParseException(sprintf('Reference "%s" does not exist.', $value)); + } + + return $references[$value]; + } + + switch (true) { + case 'null' === $scalarLower: + case '' === $scalar: + case '~' === $scalar: + return; + case 'true' === $scalarLower: + return true; + case 'false' === $scalarLower: + return false; + // Optimise for returning strings. + case '+' === $scalar[0] || '-' === $scalar[0] || '.' === $scalar[0] || '!' === $scalar[0] || is_numeric($scalar[0]): + switch (true) { + case 0 === strpos($scalar, '!str'): + return (string) substr($scalar, 5); + case 0 === strpos($scalar, '! '): + return (int) self::parseScalar(substr($scalar, 2)); + case 0 === strpos($scalar, '!php/object:'): + if (self::$objectSupport) { + return unserialize(substr($scalar, 12)); + } + + if (self::$exceptionOnInvalidType) { + throw new ParseException('Object support when parsing a YAML file has been disabled.'); + } + + return; + case 0 === strpos($scalar, '!!php/object:'): + if (self::$objectSupport) { + return unserialize(substr($scalar, 13)); + } + + if (self::$exceptionOnInvalidType) { + throw new ParseException('Object support when parsing a YAML file has been disabled.'); + } + + return; + case 0 === strpos($scalar, '!!float '): + return (float) substr($scalar, 8); + case ctype_digit($scalar): + $raw = $scalar; + $cast = (int) $scalar; + + return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); + case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)): + $raw = $scalar; + $cast = (int) $scalar; + + return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw === (string) $cast) ? $cast : $raw); + case is_numeric($scalar): + case Parser::preg_match(self::getHexRegex(), $scalar): + return '0x' === $scalar[0].$scalar[1] ? hexdec($scalar) : (float) $scalar; + case '.inf' === $scalarLower: + case '.nan' === $scalarLower: + return -log(0); + case '-.inf' === $scalarLower: + return log(0); + case Parser::preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): + return (float) str_replace(',', '', $scalar); + case Parser::preg_match(self::getTimestampRegex(), $scalar): + $timeZone = date_default_timezone_get(); + date_default_timezone_set('UTC'); + $time = strtotime($scalar); + date_default_timezone_set($timeZone); + + return $time; + } + // no break + default: + return (string) $scalar; + } + } + + /** + * Gets a regex that matches a YAML date. + * + * @return string The regular expression + * + * @see http://www.yaml.org/spec/1.2/spec.html#id2761573 + */ + private static function getTimestampRegex() + { + return <<[0-9][0-9][0-9][0-9]) + -(?P[0-9][0-9]?) + -(?P[0-9][0-9]?) + (?:(?:[Tt]|[ \t]+) + (?P[0-9][0-9]?) + :(?P[0-9][0-9]) + :(?P[0-9][0-9]) + (?:\.(?P[0-9]*))? + (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) + (?::(?P[0-9][0-9]))?))?)? + $~x +EOF; + } + + /** + * Gets a regex that matches a YAML number in hexadecimal notation. + * + * @return string + */ + private static function getHexRegex() + { + return '~^0x[0-9a-f]++$~i'; + } +} diff --git a/vendor/symfony/yaml/LICENSE b/vendor/symfony/yaml/LICENSE new file mode 100644 index 0000000..21d7fb9 --- /dev/null +++ b/vendor/symfony/yaml/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2004-2018 Fabien Potencier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/symfony/yaml/Parser.php b/vendor/symfony/yaml/Parser.php new file mode 100644 index 0000000..cb0d8f1 --- /dev/null +++ b/vendor/symfony/yaml/Parser.php @@ -0,0 +1,852 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml; + +use Symfony\Component\Yaml\Exception\ParseException; + +/** + * Parser parses YAML strings to convert them to PHP arrays. + * + * @author Fabien Potencier + */ +class Parser +{ + const BLOCK_SCALAR_HEADER_PATTERN = '(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?'; + // BC - wrongly named + const FOLDED_SCALAR_PATTERN = self::BLOCK_SCALAR_HEADER_PATTERN; + + private $offset = 0; + private $totalNumberOfLines; + private $lines = array(); + private $currentLineNb = -1; + private $currentLine = ''; + private $refs = array(); + private $skippedLineNumbers = array(); + private $locallySkippedLineNumbers = array(); + + /** + * @param int $offset The offset of YAML document (used for line numbers in error messages) + * @param int|null $totalNumberOfLines The overall number of lines being parsed + * @param int[] $skippedLineNumbers Number of comment lines that have been skipped by the parser + */ + public function __construct($offset = 0, $totalNumberOfLines = null, array $skippedLineNumbers = array()) + { + $this->offset = $offset; + $this->totalNumberOfLines = $totalNumberOfLines; + $this->skippedLineNumbers = $skippedLineNumbers; + } + + /** + * Parses a YAML string to a PHP value. + * + * @param string $value A YAML string + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * @param bool $objectForMap True if maps should return a stdClass instead of array() + * + * @return mixed A PHP value + * + * @throws ParseException If the YAML is not valid + */ + public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false) + { + if (false === preg_match('//u', $value)) { + throw new ParseException('The YAML value does not appear to be valid UTF-8.'); + } + + $this->refs = array(); + + $mbEncoding = null; + $e = null; + $data = null; + + if (2 /* MB_OVERLOAD_STRING */ & (int) ini_get('mbstring.func_overload')) { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('UTF-8'); + } + + try { + $data = $this->doParse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap); + } catch (\Exception $e) { + } catch (\Throwable $e) { + } + + if (null !== $mbEncoding) { + mb_internal_encoding($mbEncoding); + } + + $this->lines = array(); + $this->currentLine = ''; + $this->refs = array(); + $this->skippedLineNumbers = array(); + $this->locallySkippedLineNumbers = array(); + + if (null !== $e) { + throw $e; + } + + return $data; + } + + private function doParse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false) + { + $this->currentLineNb = -1; + $this->currentLine = ''; + $value = $this->cleanup($value); + $this->lines = explode("\n", $value); + $this->locallySkippedLineNumbers = array(); + + if (null === $this->totalNumberOfLines) { + $this->totalNumberOfLines = \count($this->lines); + } + + $data = array(); + $context = null; + $allowOverwrite = false; + + while ($this->moveToNextLine()) { + if ($this->isCurrentLineEmpty()) { + continue; + } + + // tab? + if ("\t" === $this->currentLine[0]) { + throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + + $isRef = $mergeNode = false; + if (self::preg_match('#^\-((?P\s+)(?P.+))?$#u', rtrim($this->currentLine), $values)) { + if ($context && 'mapping' == $context) { + throw new ParseException('You cannot define a sequence item when in a mapping', $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + $context = 'sequence'; + + if (isset($values['value']) && self::preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { + $isRef = $matches['ref']; + $values['value'] = $matches['value']; + } + + // array + if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { + $data[] = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap); + } else { + if (isset($values['leadspaces']) + && self::preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P.+))?$#u', rtrim($values['value']), $matches) + ) { + // this is a compact notation element, add to next block and parse + $block = $values['value']; + if ($this->isNextLineIndented()) { + $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + \strlen($values['leadspaces']) + 1); + } + + $data[] = $this->parseBlock($this->getRealCurrentLineNb(), $block, $exceptionOnInvalidType, $objectSupport, $objectForMap); + } else { + $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap, $context); + } + } + if ($isRef) { + $this->refs[$isRef] = end($data); + } + } elseif ( + self::preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P.+))?$#u', rtrim($this->currentLine), $values) + && (false === strpos($values['key'], ' #') || \in_array($values['key'][0], array('"', "'"))) + ) { + if ($context && 'sequence' == $context) { + throw new ParseException('You cannot define a mapping item when in a sequence', $this->currentLineNb + 1, $this->currentLine); + } + $context = 'mapping'; + + // force correct settings + Inline::parse(null, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs); + try { + $key = Inline::parseScalar($values['key']); + } catch (ParseException $e) { + $e->setParsedLine($this->getRealCurrentLineNb() + 1); + $e->setSnippet($this->currentLine); + + throw $e; + } + + // Convert float keys to strings, to avoid being converted to integers by PHP + if (\is_float($key)) { + $key = (string) $key; + } + + if ('<<' === $key && (!isset($values['value']) || !self::preg_match('#^&(?P[^ ]+)#u', $values['value'], $refMatches))) { + $mergeNode = true; + $allowOverwrite = true; + if (isset($values['value']) && 0 === strpos($values['value'], '*')) { + $refName = substr($values['value'], 1); + if (!array_key_exists($refName, $this->refs)) { + throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + + $refValue = $this->refs[$refName]; + + if (!\is_array($refValue)) { + throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + + $data += $refValue; // array union + } else { + if (isset($values['value']) && '' !== $values['value']) { + $value = $values['value']; + } else { + $value = $this->getNextEmbedBlock(); + } + $parsed = $this->parseBlock($this->getRealCurrentLineNb() + 1, $value, $exceptionOnInvalidType, $objectSupport, $objectForMap); + + if (!\is_array($parsed)) { + throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + + if (isset($parsed[0])) { + // If the value associated with the merge key is a sequence, then this sequence is expected to contain mapping nodes + // and each of these nodes is merged in turn according to its order in the sequence. Keys in mapping nodes earlier + // in the sequence override keys specified in later mapping nodes. + foreach ($parsed as $parsedItem) { + if (!\is_array($parsedItem)) { + throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem); + } + + $data += $parsedItem; // array union + } + } else { + // If the value associated with the key is a single mapping node, each of its key/value pairs is inserted into the + // current mapping, unless the key already exists in it. + $data += $parsed; // array union + } + } + } elseif ('<<' !== $key && isset($values['value']) && self::preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { + $isRef = $matches['ref']; + $values['value'] = $matches['value']; + } + + if ($mergeNode) { + // Merge keys + } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#') || '<<' === $key) { + // hash + // if next line is less indented or equal, then it means that the current value is null + if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) { + // Spec: Keys MUST be unique; first one wins. + // But overwriting is allowed when a merge node is used in current block. + if ($allowOverwrite || !isset($data[$key])) { + $data[$key] = null; + } + } else { + $value = $this->parseBlock($this->getRealCurrentLineNb() + 1, $this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap); + + if ('<<' === $key) { + $this->refs[$refMatches['ref']] = $value; + $data += $value; + } elseif ($allowOverwrite || !isset($data[$key])) { + // Spec: Keys MUST be unique; first one wins. + // But overwriting is allowed when a merge node is used in current block. + $data[$key] = $value; + } + } + } else { + $value = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap, $context); + // Spec: Keys MUST be unique; first one wins. + // But overwriting is allowed when a merge node is used in current block. + if ($allowOverwrite || !isset($data[$key])) { + $data[$key] = $value; + } + } + if ($isRef) { + $this->refs[$isRef] = $data[$key]; + } + } else { + // multiple documents are not supported + if ('---' === $this->currentLine) { + throw new ParseException('Multiple documents are not supported.', $this->currentLineNb + 1, $this->currentLine); + } + + // 1-liner optionally followed by newline(s) + if (\is_string($value) && $this->lines[0] === trim($value)) { + try { + $value = Inline::parse($this->lines[0], $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs); + } catch (ParseException $e) { + $e->setParsedLine($this->getRealCurrentLineNb() + 1); + $e->setSnippet($this->currentLine); + + throw $e; + } + + return $value; + } + + throw new ParseException('Unable to parse.', $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + } + + if ($objectForMap && !\is_object($data) && 'mapping' === $context) { + $object = new \stdClass(); + + foreach ($data as $key => $value) { + $object->$key = $value; + } + + $data = $object; + } + + return empty($data) ? null : $data; + } + + private function parseBlock($offset, $yaml, $exceptionOnInvalidType, $objectSupport, $objectForMap) + { + $skippedLineNumbers = $this->skippedLineNumbers; + + foreach ($this->locallySkippedLineNumbers as $lineNumber) { + if ($lineNumber < $offset) { + continue; + } + + $skippedLineNumbers[] = $lineNumber; + } + + $parser = new self($offset, $this->totalNumberOfLines, $skippedLineNumbers); + $parser->refs = &$this->refs; + + return $parser->doParse($yaml, $exceptionOnInvalidType, $objectSupport, $objectForMap); + } + + /** + * Returns the current line number (takes the offset into account). + * + * @return int The current line number + */ + private function getRealCurrentLineNb() + { + $realCurrentLineNumber = $this->currentLineNb + $this->offset; + + foreach ($this->skippedLineNumbers as $skippedLineNumber) { + if ($skippedLineNumber > $realCurrentLineNumber) { + break; + } + + ++$realCurrentLineNumber; + } + + return $realCurrentLineNumber; + } + + /** + * Returns the current line indentation. + * + * @return int The current line indentation + */ + private function getCurrentLineIndentation() + { + return \strlen($this->currentLine) - \strlen(ltrim($this->currentLine, ' ')); + } + + /** + * Returns the next embed block of YAML. + * + * @param int $indentation The indent level at which the block is to be read, or null for default + * @param bool $inSequence True if the enclosing data structure is a sequence + * + * @return string A YAML string + * + * @throws ParseException When indentation problem are detected + */ + private function getNextEmbedBlock($indentation = null, $inSequence = false) + { + $oldLineIndentation = $this->getCurrentLineIndentation(); + $blockScalarIndentations = array(); + + if ($this->isBlockScalarHeader()) { + $blockScalarIndentations[] = $this->getCurrentLineIndentation(); + } + + if (!$this->moveToNextLine()) { + return; + } + + if (null === $indentation) { + $newIndent = $this->getCurrentLineIndentation(); + + $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem(); + + if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) { + throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + } else { + $newIndent = $indentation; + } + + $data = array(); + if ($this->getCurrentLineIndentation() >= $newIndent) { + $data[] = substr($this->currentLine, $newIndent); + } else { + $this->moveToPreviousLine(); + + return; + } + + if ($inSequence && $oldLineIndentation === $newIndent && isset($data[0][0]) && '-' === $data[0][0]) { + // the previous line contained a dash but no item content, this line is a sequence item with the same indentation + // and therefore no nested list or mapping + $this->moveToPreviousLine(); + + return; + } + + $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem(); + + if (empty($blockScalarIndentations) && $this->isBlockScalarHeader()) { + $blockScalarIndentations[] = $this->getCurrentLineIndentation(); + } + + $previousLineIndentation = $this->getCurrentLineIndentation(); + + while ($this->moveToNextLine()) { + $indent = $this->getCurrentLineIndentation(); + + // terminate all block scalars that are more indented than the current line + if (!empty($blockScalarIndentations) && $indent < $previousLineIndentation && '' !== trim($this->currentLine)) { + foreach ($blockScalarIndentations as $key => $blockScalarIndentation) { + if ($blockScalarIndentation >= $this->getCurrentLineIndentation()) { + unset($blockScalarIndentations[$key]); + } + } + } + + if (empty($blockScalarIndentations) && !$this->isCurrentLineComment() && $this->isBlockScalarHeader()) { + $blockScalarIndentations[] = $this->getCurrentLineIndentation(); + } + + $previousLineIndentation = $indent; + + if ($isItUnindentedCollection && !$this->isCurrentLineEmpty() && !$this->isStringUnIndentedCollectionItem() && $newIndent === $indent) { + $this->moveToPreviousLine(); + break; + } + + if ($this->isCurrentLineBlank()) { + $data[] = substr($this->currentLine, $newIndent); + continue; + } + + // we ignore "comment" lines only when we are not inside a scalar block + if (empty($blockScalarIndentations) && $this->isCurrentLineComment()) { + // remember ignored comment lines (they are used later in nested + // parser calls to determine real line numbers) + // + // CAUTION: beware to not populate the global property here as it + // will otherwise influence the getRealCurrentLineNb() call here + // for consecutive comment lines and subsequent embedded blocks + $this->locallySkippedLineNumbers[] = $this->getRealCurrentLineNb(); + + continue; + } + + if ($indent >= $newIndent) { + $data[] = substr($this->currentLine, $newIndent); + } elseif (0 == $indent) { + $this->moveToPreviousLine(); + + break; + } else { + throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine); + } + } + + return implode("\n", $data); + } + + /** + * Moves the parser to the next line. + * + * @return bool + */ + private function moveToNextLine() + { + if ($this->currentLineNb >= \count($this->lines) - 1) { + return false; + } + + $this->currentLine = $this->lines[++$this->currentLineNb]; + + return true; + } + + /** + * Moves the parser to the previous line. + * + * @return bool + */ + private function moveToPreviousLine() + { + if ($this->currentLineNb < 1) { + return false; + } + + $this->currentLine = $this->lines[--$this->currentLineNb]; + + return true; + } + + /** + * Parses a YAML value. + * + * @param string $value A YAML value + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * @param bool $objectForMap True if maps should return a stdClass instead of array() + * @param string $context The parser context (either sequence or mapping) + * + * @return mixed A PHP value + * + * @throws ParseException When reference does not exist + */ + private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $context) + { + if (0 === strpos($value, '*')) { + if (false !== $pos = strpos($value, '#')) { + $value = substr($value, 1, $pos - 2); + } else { + $value = substr($value, 1); + } + + if (!array_key_exists($value, $this->refs)) { + throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLineNb + 1, $this->currentLine); + } + + return $this->refs[$value]; + } + + if (self::preg_match('/^'.self::BLOCK_SCALAR_HEADER_PATTERN.'$/', $value, $matches)) { + $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; + + return $this->parseBlockScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), (int) abs($modifiers)); + } + + try { + $parsedValue = Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs); + + if ('mapping' === $context && '"' !== $value[0] && "'" !== $value[0] && '[' !== $value[0] && '{' !== $value[0] && '!' !== $value[0] && false !== strpos($parsedValue, ': ')) { + @trigger_error(sprintf('Using a colon in the unquoted mapping value "%s" in line %d is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', $value, $this->getRealCurrentLineNb() + 1), E_USER_DEPRECATED); + + // to be thrown in 3.0 + // throw new ParseException('A colon cannot be used in an unquoted mapping value.'); + } + + return $parsedValue; + } catch (ParseException $e) { + $e->setParsedLine($this->getRealCurrentLineNb() + 1); + $e->setSnippet($this->currentLine); + + throw $e; + } + } + + /** + * Parses a block scalar. + * + * @param string $style The style indicator that was used to begin this block scalar (| or >) + * @param string $chomping The chomping indicator that was used to begin this block scalar (+ or -) + * @param int $indentation The indentation indicator that was used to begin this block scalar + * + * @return string The text value + */ + private function parseBlockScalar($style, $chomping = '', $indentation = 0) + { + $notEOF = $this->moveToNextLine(); + if (!$notEOF) { + return ''; + } + + $isCurrentLineBlank = $this->isCurrentLineBlank(); + $blockLines = array(); + + // leading blank lines are consumed before determining indentation + while ($notEOF && $isCurrentLineBlank) { + // newline only if not EOF + if ($notEOF = $this->moveToNextLine()) { + $blockLines[] = ''; + $isCurrentLineBlank = $this->isCurrentLineBlank(); + } + } + + // determine indentation if not specified + if (0 === $indentation) { + if (self::preg_match('/^ +/', $this->currentLine, $matches)) { + $indentation = \strlen($matches[0]); + } + } + + if ($indentation > 0) { + $pattern = sprintf('/^ {%d}(.*)$/', $indentation); + + while ( + $notEOF && ( + $isCurrentLineBlank || + self::preg_match($pattern, $this->currentLine, $matches) + ) + ) { + if ($isCurrentLineBlank && \strlen($this->currentLine) > $indentation) { + $blockLines[] = substr($this->currentLine, $indentation); + } elseif ($isCurrentLineBlank) { + $blockLines[] = ''; + } else { + $blockLines[] = $matches[1]; + } + + // newline only if not EOF + if ($notEOF = $this->moveToNextLine()) { + $isCurrentLineBlank = $this->isCurrentLineBlank(); + } + } + } elseif ($notEOF) { + $blockLines[] = ''; + } + + if ($notEOF) { + $blockLines[] = ''; + $this->moveToPreviousLine(); + } elseif (!$notEOF && !$this->isCurrentLineLastLineInDocument()) { + $blockLines[] = ''; + } + + // folded style + if ('>' === $style) { + $text = ''; + $previousLineIndented = false; + $previousLineBlank = false; + + for ($i = 0, $blockLinesCount = \count($blockLines); $i < $blockLinesCount; ++$i) { + if ('' === $blockLines[$i]) { + $text .= "\n"; + $previousLineIndented = false; + $previousLineBlank = true; + } elseif (' ' === $blockLines[$i][0]) { + $text .= "\n".$blockLines[$i]; + $previousLineIndented = true; + $previousLineBlank = false; + } elseif ($previousLineIndented) { + $text .= "\n".$blockLines[$i]; + $previousLineIndented = false; + $previousLineBlank = false; + } elseif ($previousLineBlank || 0 === $i) { + $text .= $blockLines[$i]; + $previousLineIndented = false; + $previousLineBlank = false; + } else { + $text .= ' '.$blockLines[$i]; + $previousLineIndented = false; + $previousLineBlank = false; + } + } + } else { + $text = implode("\n", $blockLines); + } + + // deal with trailing newlines + if ('' === $chomping) { + $text = preg_replace('/\n+$/', "\n", $text); + } elseif ('-' === $chomping) { + $text = preg_replace('/\n+$/', '', $text); + } + + return $text; + } + + /** + * Returns true if the next line is indented. + * + * @return bool Returns true if the next line is indented, false otherwise + */ + private function isNextLineIndented() + { + $currentIndentation = $this->getCurrentLineIndentation(); + $EOF = !$this->moveToNextLine(); + + while (!$EOF && $this->isCurrentLineEmpty()) { + $EOF = !$this->moveToNextLine(); + } + + if ($EOF) { + return false; + } + + $ret = $this->getCurrentLineIndentation() > $currentIndentation; + + $this->moveToPreviousLine(); + + return $ret; + } + + /** + * Returns true if the current line is blank or if it is a comment line. + * + * @return bool Returns true if the current line is empty or if it is a comment line, false otherwise + */ + private function isCurrentLineEmpty() + { + return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); + } + + /** + * Returns true if the current line is blank. + * + * @return bool Returns true if the current line is blank, false otherwise + */ + private function isCurrentLineBlank() + { + return '' == trim($this->currentLine, ' '); + } + + /** + * Returns true if the current line is a comment line. + * + * @return bool Returns true if the current line is a comment line, false otherwise + */ + private function isCurrentLineComment() + { + //checking explicitly the first char of the trim is faster than loops or strpos + $ltrimmedLine = ltrim($this->currentLine, ' '); + + return '' !== $ltrimmedLine && '#' === $ltrimmedLine[0]; + } + + private function isCurrentLineLastLineInDocument() + { + return ($this->offset + $this->currentLineNb) >= ($this->totalNumberOfLines - 1); + } + + /** + * Cleanups a YAML string to be parsed. + * + * @param string $value The input YAML string + * + * @return string A cleaned up YAML string + */ + private function cleanup($value) + { + $value = str_replace(array("\r\n", "\r"), "\n", $value); + + // strip YAML header + $count = 0; + $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count); + $this->offset += $count; + + // remove leading comments + $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); + if (1 == $count) { + // items have been removed, update the offset + $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); + $value = $trimmedValue; + } + + // remove start of the document marker (---) + $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); + if (1 == $count) { + // items have been removed, update the offset + $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); + $value = $trimmedValue; + + // remove end of the document marker (...) + $value = preg_replace('#\.\.\.\s*$#', '', $value); + } + + return $value; + } + + /** + * Returns true if the next line starts unindented collection. + * + * @return bool Returns true if the next line starts unindented collection, false otherwise + */ + private function isNextLineUnIndentedCollection() + { + $currentIndentation = $this->getCurrentLineIndentation(); + $notEOF = $this->moveToNextLine(); + + while ($notEOF && $this->isCurrentLineEmpty()) { + $notEOF = $this->moveToNextLine(); + } + + if (false === $notEOF) { + return false; + } + + $ret = $this->getCurrentLineIndentation() === $currentIndentation && $this->isStringUnIndentedCollectionItem(); + + $this->moveToPreviousLine(); + + return $ret; + } + + /** + * Returns true if the string is un-indented collection item. + * + * @return bool Returns true if the string is un-indented collection item, false otherwise + */ + private function isStringUnIndentedCollectionItem() + { + return '-' === rtrim($this->currentLine) || 0 === strpos($this->currentLine, '- '); + } + + /** + * Tests whether or not the current line is the header of a block scalar. + * + * @return bool + */ + private function isBlockScalarHeader() + { + return (bool) self::preg_match('~'.self::BLOCK_SCALAR_HEADER_PATTERN.'$~', $this->currentLine); + } + + /** + * A local wrapper for `preg_match` which will throw a ParseException if there + * is an internal error in the PCRE engine. + * + * This avoids us needing to check for "false" every time PCRE is used + * in the YAML engine + * + * @throws ParseException on a PCRE internal error + * + * @see preg_last_error() + * + * @internal + */ + public static function preg_match($pattern, $subject, &$matches = null, $flags = 0, $offset = 0) + { + if (false === $ret = preg_match($pattern, $subject, $matches, $flags, $offset)) { + switch (preg_last_error()) { + case PREG_INTERNAL_ERROR: + $error = 'Internal PCRE error.'; + break; + case PREG_BACKTRACK_LIMIT_ERROR: + $error = 'pcre.backtrack_limit reached.'; + break; + case PREG_RECURSION_LIMIT_ERROR: + $error = 'pcre.recursion_limit reached.'; + break; + case PREG_BAD_UTF8_ERROR: + $error = 'Malformed UTF-8 data.'; + break; + case PREG_BAD_UTF8_OFFSET_ERROR: + $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.'; + break; + default: + $error = 'Error.'; + } + + throw new ParseException($error); + } + + return $ret; + } +} diff --git a/vendor/symfony/yaml/README.md b/vendor/symfony/yaml/README.md new file mode 100644 index 0000000..0d32488 --- /dev/null +++ b/vendor/symfony/yaml/README.md @@ -0,0 +1,13 @@ +Yaml Component +============== + +The Yaml component loads and dumps YAML files. + +Resources +--------- + + * [Documentation](https://symfony.com/doc/current/components/yaml/index.html) + * [Contributing](https://symfony.com/doc/current/contributing/index.html) + * [Report issues](https://github.com/symfony/symfony/issues) and + [send Pull Requests](https://github.com/symfony/symfony/pulls) + in the [main Symfony repository](https://github.com/symfony/symfony) diff --git a/vendor/symfony/yaml/Tests/DumperTest.php b/vendor/symfony/yaml/Tests/DumperTest.php new file mode 100644 index 0000000..6bac6da --- /dev/null +++ b/vendor/symfony/yaml/Tests/DumperTest.php @@ -0,0 +1,257 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Yaml\Dumper; +use Symfony\Component\Yaml\Parser; + +class DumperTest extends TestCase +{ + protected $parser; + protected $dumper; + protected $path; + + protected $array = array( + '' => 'bar', + 'foo' => '#bar', + 'foo\'bar' => array(), + 'bar' => array(1, 'foo'), + 'foobar' => array( + 'foo' => 'bar', + 'bar' => array(1, 'foo'), + 'foobar' => array( + 'foo' => 'bar', + 'bar' => array(1, 'foo'), + ), + ), + ); + + protected function setUp() + { + $this->parser = new Parser(); + $this->dumper = new Dumper(); + $this->path = __DIR__.'/Fixtures'; + } + + protected function tearDown() + { + $this->parser = null; + $this->dumper = null; + $this->path = null; + $this->array = null; + } + + public function testSetIndentation() + { + $this->dumper->setIndentation(7); + + $expected = <<<'EOF' +'': bar +foo: '#bar' +'foo''bar': { } +bar: + - 1 + - foo +foobar: + foo: bar + bar: + - 1 + - foo + foobar: + foo: bar + bar: + - 1 + - foo + +EOF; + $this->assertEquals($expected, $this->dumper->dump($this->array, 4, 0)); + } + + public function testSpecifications() + { + $files = $this->parser->parse(file_get_contents($this->path.'/index.yml')); + foreach ($files as $file) { + $yamls = file_get_contents($this->path.'/'.$file.'.yml'); + + // split YAMLs documents + foreach (preg_split('/^---( %YAML\:1\.0)?/m', $yamls) as $yaml) { + if (!$yaml) { + continue; + } + + $test = $this->parser->parse($yaml); + if (isset($test['dump_skip']) && $test['dump_skip']) { + continue; + } elseif (isset($test['todo']) && $test['todo']) { + // TODO + } else { + eval('$expected = '.trim($test['php']).';'); + $this->assertSame($expected, $this->parser->parse($this->dumper->dump($expected, 10)), $test['test']); + } + } + } + } + + public function testInlineLevel() + { + $expected = <<<'EOF' +{ '': bar, foo: '#bar', 'foo''bar': { }, bar: [1, foo], foobar: { foo: bar, bar: [1, foo], foobar: { foo: bar, bar: [1, foo] } } } +EOF; + $this->assertEquals($expected, $this->dumper->dump($this->array, -10), '->dump() takes an inline level argument'); + $this->assertEquals($expected, $this->dumper->dump($this->array, 0), '->dump() takes an inline level argument'); + + $expected = <<<'EOF' +'': bar +foo: '#bar' +'foo''bar': { } +bar: [1, foo] +foobar: { foo: bar, bar: [1, foo], foobar: { foo: bar, bar: [1, foo] } } + +EOF; + $this->assertEquals($expected, $this->dumper->dump($this->array, 1), '->dump() takes an inline level argument'); + + $expected = <<<'EOF' +'': bar +foo: '#bar' +'foo''bar': { } +bar: + - 1 + - foo +foobar: + foo: bar + bar: [1, foo] + foobar: { foo: bar, bar: [1, foo] } + +EOF; + $this->assertEquals($expected, $this->dumper->dump($this->array, 2), '->dump() takes an inline level argument'); + + $expected = <<<'EOF' +'': bar +foo: '#bar' +'foo''bar': { } +bar: + - 1 + - foo +foobar: + foo: bar + bar: + - 1 + - foo + foobar: + foo: bar + bar: [1, foo] + +EOF; + $this->assertEquals($expected, $this->dumper->dump($this->array, 3), '->dump() takes an inline level argument'); + + $expected = <<<'EOF' +'': bar +foo: '#bar' +'foo''bar': { } +bar: + - 1 + - foo +foobar: + foo: bar + bar: + - 1 + - foo + foobar: + foo: bar + bar: + - 1 + - foo + +EOF; + $this->assertEquals($expected, $this->dumper->dump($this->array, 4), '->dump() takes an inline level argument'); + $this->assertEquals($expected, $this->dumper->dump($this->array, 10), '->dump() takes an inline level argument'); + } + + public function testObjectSupportEnabled() + { + $dump = $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, false, true); + + $this->assertEquals('{ foo: !php/object:O:30:"Symfony\Component\Yaml\Tests\A":1:{s:1:"a";s:3:"foo";}, bar: 1 }', $dump, '->dump() is able to dump objects'); + } + + public function testObjectSupportDisabledButNoExceptions() + { + $dump = $this->dumper->dump(array('foo' => new A(), 'bar' => 1)); + + $this->assertEquals('{ foo: null, bar: 1 }', $dump, '->dump() does not dump objects when disabled'); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\DumpException + */ + public function testObjectSupportDisabledWithExceptions() + { + $this->dumper->dump(array('foo' => new A(), 'bar' => 1), 0, 0, true, false); + } + + /** + * @dataProvider getEscapeSequences + */ + public function testEscapedEscapeSequencesInQuotedScalar($input, $expected) + { + $this->assertEquals($expected, $this->dumper->dump($input)); + } + + public function getEscapeSequences() + { + return array( + 'empty string' => array('', "''"), + 'null' => array("\x0", '"\\0"'), + 'bell' => array("\x7", '"\\a"'), + 'backspace' => array("\x8", '"\\b"'), + 'horizontal-tab' => array("\t", '"\\t"'), + 'line-feed' => array("\n", '"\\n"'), + 'vertical-tab' => array("\v", '"\\v"'), + 'form-feed' => array("\xC", '"\\f"'), + 'carriage-return' => array("\r", '"\\r"'), + 'escape' => array("\x1B", '"\\e"'), + 'space' => array(' ', "' '"), + 'double-quote' => array('"', "'\"'"), + 'slash' => array('/', '/'), + 'backslash' => array('\\', '\\'), + 'next-line' => array("\xC2\x85", '"\\N"'), + 'non-breaking-space' => array("\xc2\xa0", '"\\_"'), + 'line-separator' => array("\xE2\x80\xA8", '"\\L"'), + 'paragraph-separator' => array("\xE2\x80\xA9", '"\\P"'), + 'colon' => array(':', "':'"), + ); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The indentation must be greater than zero + */ + public function testZeroIndentationThrowsException() + { + $this->dumper->setIndentation(0); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The indentation must be greater than zero + */ + public function testNegativeIndentationThrowsException() + { + $this->dumper->setIndentation(-4); + } +} + +class A +{ + public $a = 'foo'; +} diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsAnchorAlias.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsAnchorAlias.yml new file mode 100644 index 0000000..5f9c942 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsAnchorAlias.yml @@ -0,0 +1,31 @@ +--- %YAML:1.0 +test: Simple Alias Example +brief: > + If you need to refer to the same item of data twice, + you can give that item an alias. The alias is a plain + string, starting with an ampersand. The item may then + be referred to by the alias throughout your document + by using an asterisk before the name of the alias. + This is called an anchor. +yaml: | + - &showell Steve + - Clark + - Brian + - Oren + - *showell +php: | + array('Steve', 'Clark', 'Brian', 'Oren', 'Steve') + +--- +test: Alias of a Mapping +brief: > + An alias can be used on any item of data, including + sequences, mappings, and other complex data types. +yaml: | + - &hello + Meat: pork + Starch: potato + - banana + - *hello +php: | + array(array('Meat'=>'pork', 'Starch'=>'potato'), 'banana', array('Meat'=>'pork', 'Starch'=>'potato')) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsBasicTests.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsBasicTests.yml new file mode 100644 index 0000000..dfd9302 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsBasicTests.yml @@ -0,0 +1,202 @@ +--- %YAML:1.0 +test: Simple Sequence +brief: | + You can specify a list in YAML by placing each + member of the list on a new line with an opening + dash. These lists are called sequences. +yaml: | + - apple + - banana + - carrot +php: | + array('apple', 'banana', 'carrot') +--- +test: Sequence With Item Being Null In The Middle +brief: | + You can specify a list in YAML by placing each + member of the list on a new line with an opening + dash. These lists are called sequences. +yaml: | + - apple + - + - carrot +php: | + array('apple', null, 'carrot') +--- +test: Sequence With Last Item Being Null +brief: | + You can specify a list in YAML by placing each + member of the list on a new line with an opening + dash. These lists are called sequences. +yaml: | + - apple + - banana + - +php: | + array('apple', 'banana', null) +--- +test: Nested Sequences +brief: | + You can include a sequence within another + sequence by giving the sequence an empty + dash, followed by an indented list. +yaml: | + - + - foo + - bar + - baz +php: | + array(array('foo', 'bar', 'baz')) +--- +test: Mixed Sequences +brief: | + Sequences can contain any YAML data, + including strings and other sequences. +yaml: | + - apple + - + - foo + - bar + - x123 + - banana + - carrot +php: | + array('apple', array('foo', 'bar', 'x123'), 'banana', 'carrot') +--- +test: Deeply Nested Sequences +brief: | + Sequences can be nested even deeper, with each + level of indentation representing a level of + depth. +yaml: | + - + - + - uno + - dos +php: | + array(array(array('uno', 'dos'))) +--- +test: Simple Mapping +brief: | + You can add a keyed list (also known as a dictionary or + hash) to your document by placing each member of the + list on a new line, with a colon separating the key + from its value. In YAML, this type of list is called + a mapping. +yaml: | + foo: whatever + bar: stuff +php: | + array('foo' => 'whatever', 'bar' => 'stuff') +--- +test: Sequence in a Mapping +brief: | + A value in a mapping can be a sequence. +yaml: | + foo: whatever + bar: + - uno + - dos +php: | + array('foo' => 'whatever', 'bar' => array('uno', 'dos')) +--- +test: Nested Mappings +brief: | + A value in a mapping can be another mapping. +yaml: | + foo: whatever + bar: + fruit: apple + name: steve + sport: baseball +php: | + array( + 'foo' => 'whatever', + 'bar' => array( + 'fruit' => 'apple', + 'name' => 'steve', + 'sport' => 'baseball' + ) + ) +--- +test: Mixed Mapping +brief: | + A mapping can contain any assortment + of mappings and sequences as values. +yaml: | + foo: whatever + bar: + - + fruit: apple + name: steve + sport: baseball + - more + - + python: rocks + perl: papers + ruby: scissorses +php: | + array( + 'foo' => 'whatever', + 'bar' => array( + array( + 'fruit' => 'apple', + 'name' => 'steve', + 'sport' => 'baseball' + ), + 'more', + array( + 'python' => 'rocks', + 'perl' => 'papers', + 'ruby' => 'scissorses' + ) + ) + ) +--- +test: Mapping-in-Sequence Shortcut +todo: true +brief: | + If you are adding a mapping to a sequence, you + can place the mapping on the same line as the + dash as a shortcut. +yaml: | + - work on YAML.py: + - work on Store +php: | + array(array('work on YAML.py' => array('work on Store'))) +--- +test: Sequence-in-Mapping Shortcut +todo: true +brief: | + The dash in a sequence counts as indentation, so + you can add a sequence inside of a mapping without + needing spaces as indentation. +yaml: | + allow: + - 'localhost' + - '%.sourceforge.net' + - '%.freepan.org' +php: | + array('allow' => array('localhost', '%.sourceforge.net', '%.freepan.org')) +--- +todo: true +test: Merge key +brief: | + A merge key ('<<') can be used in a mapping to insert other mappings. If + the value associated with the merge key is a mapping, each of its key/value + pairs is inserted into the current mapping. +yaml: | + mapping: + name: Joe + job: Accountant + <<: + age: 38 +php: | + array( + 'mapping' => + array( + 'name' => 'Joe', + 'job' => 'Accountant', + 'age' => 38 + ) + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsBlockMapping.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsBlockMapping.yml new file mode 100644 index 0000000..f7ca469 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsBlockMapping.yml @@ -0,0 +1,51 @@ +--- +test: One Element Mapping +brief: | + A mapping with one key/value pair +yaml: | + foo: bar +php: | + array('foo' => 'bar') +--- +test: Multi Element Mapping +brief: | + More than one key/value pair +yaml: | + red: baron + white: walls + blue: berries +php: | + array( + 'red' => 'baron', + 'white' => 'walls', + 'blue' => 'berries', + ) +--- +test: Values aligned +brief: | + Often times human editors of documents will align the values even + though YAML emitters generally don't. +yaml: | + red: baron + white: walls + blue: berries +php: | + array( + 'red' => 'baron', + 'white' => 'walls', + 'blue' => 'berries', + ) +--- +test: Colons aligned +brief: | + Spaces can come before the ': ' key/value separator. +yaml: | + red : baron + white : walls + blue : berries +php: | + array( + 'red' => 'baron', + 'white' => 'walls', + 'blue' => 'berries', + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsDocumentSeparator.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsDocumentSeparator.yml new file mode 100644 index 0000000..d988102 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsDocumentSeparator.yml @@ -0,0 +1,85 @@ +--- %YAML:1.0 +test: Trailing Document Separator +todo: true +brief: > + You can separate YAML documents + with a string of three dashes. +yaml: | + - foo: 1 + bar: 2 + --- + more: stuff +python: | + [ + [ { 'foo': 1, 'bar': 2 } ], + { 'more': 'stuff' } + ] +ruby: | + [ { 'foo' => 1, 'bar' => 2 } ] + +--- +test: Leading Document Separator +todo: true +brief: > + You can explicitly give an opening + document separator to your YAML stream. +yaml: | + --- + - foo: 1 + bar: 2 + --- + more: stuff +python: | + [ + [ {'foo': 1, 'bar': 2}], + {'more': 'stuff'} + ] +ruby: | + [ { 'foo' => 1, 'bar' => 2 } ] + +--- +test: YAML Header +todo: true +brief: > + The opening separator can contain directives + to the YAML parser, such as the version + number. +yaml: | + --- %YAML:1.0 + foo: 1 + bar: 2 +php: | + array('foo' => 1, 'bar' => 2) +documents: 1 + +--- +test: Red Herring Document Separator +brief: > + Separators included in blocks or strings + are treated as blocks or strings, as the + document separator should have no indentation + preceding it. +yaml: | + foo: | + --- +php: | + array('foo' => "---\n") + +--- +test: Multiple Document Separators in Block +brief: > + This technique allows you to embed other YAML + documents within literal blocks. +yaml: | + foo: | + --- + foo: bar + --- + yo: baz + bar: | + fooness +php: | + array( + 'foo' => "---\nfoo: bar\n---\nyo: baz\n", + 'bar' => "fooness\n" + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsErrorTests.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsErrorTests.yml new file mode 100644 index 0000000..e8506fc --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsErrorTests.yml @@ -0,0 +1,25 @@ +--- +test: Missing value for hash item +todo: true +brief: | + Third item in this hash doesn't have a value +yaml: | + okay: value + also okay: ~ + causes error because no value specified + last key: value okay here too +python-error: causes error because no value specified + +--- +test: Not indenting enough +brief: | + There was a bug in PyYaml where it was off by one + in the indentation check. It was allowing the YAML + below. +# This is actually valid YAML now. Someone should tell showell. +yaml: | + foo: + firstline: 1 + secondline: 2 +php: | + array('foo' => null, 'firstline' => 1, 'secondline' => 2) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsFlowCollections.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsFlowCollections.yml new file mode 100644 index 0000000..03090e4 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsFlowCollections.yml @@ -0,0 +1,60 @@ +--- +test: Simple Inline Array +brief: > + Sequences can be contained on a + single line, using the inline syntax. + Separate each entry with commas and + enclose in square brackets. +yaml: | + seq: [ a, b, c ] +php: | + array('seq' => array('a', 'b', 'c')) +--- +test: Simple Inline Hash +brief: > + Mapping can also be contained on + a single line, using the inline + syntax. Each key-value pair is + separated by a colon, with a comma + between each entry in the mapping. + Enclose with curly braces. +yaml: | + hash: { name: Steve, foo: bar } +php: | + array('hash' => array('name' => 'Steve', 'foo' => 'bar')) +--- +test: Multi-line Inline Collections +todo: true +brief: > + Both inline sequences and inline mappings + can span multiple lines, provided that you + indent the additional lines. +yaml: | + languages: [ Ruby, + Perl, + Python ] + websites: { YAML: yaml.org, + Ruby: ruby-lang.org, + Python: python.org, + Perl: use.perl.org } +php: | + array( + 'languages' => array('Ruby', 'Perl', 'Python'), + 'websites' => array( + 'YAML' => 'yaml.org', + 'Ruby' => 'ruby-lang.org', + 'Python' => 'python.org', + 'Perl' => 'use.perl.org' + ) + ) +--- +test: Commas in Values (not in the spec!) +todo: true +brief: > + List items in collections are delimited by commas, but + there must be a space after each comma. This allows you + to add numbers without quoting. +yaml: | + attendances: [ 45,123, 70,000, 17,222 ] +php: | + array('attendances' => array(45123, 70000, 17222)) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsFoldedScalars.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsFoldedScalars.yml new file mode 100644 index 0000000..a14735a --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsFoldedScalars.yml @@ -0,0 +1,176 @@ +--- %YAML:1.0 +test: Single ending newline +brief: > + A pipe character, followed by an indented + block of text is treated as a literal + block, in which newlines are preserved + throughout the block, including the final + newline. +yaml: | + --- + this: | + Foo + Bar +php: | + array('this' => "Foo\nBar\n") +--- +test: The '+' indicator +brief: > + The '+' indicator says to keep newlines at the end of text + blocks. +yaml: | + normal: | + extra new lines not kept + + preserving: |+ + extra new lines are kept + + + dummy: value +php: | + array( + 'normal' => "extra new lines not kept\n", + 'preserving' => "extra new lines are kept\n\n\n", + 'dummy' => 'value' + ) +--- +test: Three trailing newlines in literals +brief: > + To give you more control over how space + is preserved in text blocks, YAML has + the keep '+' and chomp '-' indicators. + The keep indicator will preserve all + ending newlines, while the chomp indicator + will strip all ending newlines. +yaml: | + clipped: | + This has one newline. + + + + same as "clipped" above: "This has one newline.\n" + + stripped: |- + This has no newline. + + + + same as "stripped" above: "This has no newline." + + kept: |+ + This has four newlines. + + + + same as "kept" above: "This has four newlines.\n\n\n\n" +php: | + array( + 'clipped' => "This has one newline.\n", + 'same as "clipped" above' => "This has one newline.\n", + 'stripped' => 'This has no newline.', + 'same as "stripped" above' => 'This has no newline.', + 'kept' => "This has four newlines.\n\n\n\n", + 'same as "kept" above' => "This has four newlines.\n\n\n\n" + ) +--- +test: Extra trailing newlines with spaces +todo: true +brief: > + Normally, only a single newline is kept + from the end of a literal block, unless the + keep '+' character is used in combination + with the pipe. The following example + will preserve all ending whitespace + since the last line of both literal blocks + contains spaces which extend past the indentation + level. +yaml: | + --- + this: | + Foo + + + kept: |+ + Foo + + +php: | + array('this' => "Foo\n\n \n", + 'kept' => "Foo\n\n \n" ) + +--- +test: Folded Block in a Sequence +brief: > + A greater-then character, followed by an indented + block of text is treated as a folded block, in + which lines of text separated by a single newline + are concatenated as a single line. +yaml: | + --- + - apple + - banana + - > + can't you see + the beauty of yaml? + hmm + - dog +php: | + array( + 'apple', + 'banana', + "can't you see the beauty of yaml? hmm\n", + 'dog' + ) +--- +test: Folded Block as a Mapping Value +brief: > + Both literal and folded blocks can be + used in collections, as values in a + sequence or a mapping. +yaml: | + --- + quote: > + Mark McGwire's + year was crippled + by a knee injury. + source: espn +php: | + array( + 'quote' => "Mark McGwire's year was crippled by a knee injury.\n", + 'source' => 'espn' + ) +--- +test: Three trailing newlines in folded blocks +brief: > + The keep and chomp indicators can also + be applied to folded blocks. +yaml: | + clipped: > + This has one newline. + + + + same as "clipped" above: "This has one newline.\n" + + stripped: >- + This has no newline. + + + + same as "stripped" above: "This has no newline." + + kept: >+ + This has four newlines. + + + + same as "kept" above: "This has four newlines.\n\n\n\n" +php: | + array( + 'clipped' => "This has one newline.\n", + 'same as "clipped" above' => "This has one newline.\n", + 'stripped' => 'This has no newline.', + 'same as "stripped" above' => 'This has no newline.', + 'kept' => "This has four newlines.\n\n\n\n", + 'same as "kept" above' => "This has four newlines.\n\n\n\n" + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsNullsAndEmpties.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsNullsAndEmpties.yml new file mode 100644 index 0000000..9a5300f --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsNullsAndEmpties.yml @@ -0,0 +1,45 @@ +--- %YAML:1.0 +test: Empty Sequence +brief: > + You can represent the empty sequence + with an empty inline sequence. +yaml: | + empty: [] +php: | + array('empty' => array()) +--- +test: Empty Mapping +brief: > + You can represent the empty mapping + with an empty inline mapping. +yaml: | + empty: {} +php: | + array('empty' => array()) +--- +test: Empty Sequence as Entire Document +yaml: | + [] +php: | + array() +--- +test: Empty Mapping as Entire Document +yaml: | + {} +php: | + array() +--- +test: Null as Document +yaml: | + ~ +php: | + null +--- +test: Empty String +brief: > + You can represent an empty string + with a pair of quotes. +yaml: | + '' +php: | + '' diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsSpecificationExamples.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsSpecificationExamples.yml new file mode 100644 index 0000000..ec1c4c3 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsSpecificationExamples.yml @@ -0,0 +1,1697 @@ +--- %YAML:1.0 +test: Sequence of scalars +spec: 2.1 +yaml: | + - Mark McGwire + - Sammy Sosa + - Ken Griffey +php: | + array('Mark McGwire', 'Sammy Sosa', 'Ken Griffey') +--- +test: Mapping of scalars to scalars +spec: 2.2 +yaml: | + hr: 65 + avg: 0.278 + rbi: 147 +php: | + array('hr' => 65, 'avg' => 0.278, 'rbi' => 147) +--- +test: Mapping of scalars to sequences +spec: 2.3 +yaml: | + american: + - Boston Red Sox + - Detroit Tigers + - New York Yankees + national: + - New York Mets + - Chicago Cubs + - Atlanta Braves +php: | + array('american' => + array( 'Boston Red Sox', 'Detroit Tigers', + 'New York Yankees' ), + 'national' => + array( 'New York Mets', 'Chicago Cubs', + 'Atlanta Braves' ) + ) +--- +test: Sequence of mappings +spec: 2.4 +yaml: | + - + name: Mark McGwire + hr: 65 + avg: 0.278 + - + name: Sammy Sosa + hr: 63 + avg: 0.288 +php: | + array( + array('name' => 'Mark McGwire', 'hr' => 65, 'avg' => 0.278), + array('name' => 'Sammy Sosa', 'hr' => 63, 'avg' => 0.288) + ) +--- +test: Legacy A5 +todo: true +spec: legacy_A5 +yaml: | + ? + - New York Yankees + - Atlanta Braves + : + - 2001-07-02 + - 2001-08-12 + - 2001-08-14 + ? + - Detroit Tigers + - Chicago Cubs + : + - 2001-07-23 +perl-busted: > + YAML.pm will be able to emulate this behavior soon. In this regard + it may be somewhat more correct than Python's native behaviour which + can only use tuples as mapping keys. PyYAML will also need to figure + out some clever way to roundtrip structured keys. +python: | + [ + { + ('New York Yankees', 'Atlanta Braves'): + [yaml.timestamp('2001-07-02'), + yaml.timestamp('2001-08-12'), + yaml.timestamp('2001-08-14')], + ('Detroit Tigers', 'Chicago Cubs'): + [yaml.timestamp('2001-07-23')] + } + ] +ruby: | + { + [ 'New York Yankees', 'Atlanta Braves' ] => + [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ], + [ 'Detroit Tigers', 'Chicago Cubs' ] => + [ Date.new( 2001, 7, 23 ) ] + } +syck: | + struct test_node seq1[] = { + { T_STR, 0, "New York Yankees" }, + { T_STR, 0, "Atlanta Braves" }, + end_node + }; + struct test_node seq2[] = { + { T_STR, 0, "2001-07-02" }, + { T_STR, 0, "2001-08-12" }, + { T_STR, 0, "2001-08-14" }, + end_node + }; + struct test_node seq3[] = { + { T_STR, 0, "Detroit Tigers" }, + { T_STR, 0, "Chicago Cubs" }, + end_node + }; + struct test_node seq4[] = { + { T_STR, 0, "2001-07-23" }, + end_node + }; + struct test_node map[] = { + { T_SEQ, 0, 0, seq1 }, + { T_SEQ, 0, 0, seq2 }, + { T_SEQ, 0, 0, seq3 }, + { T_SEQ, 0, 0, seq4 }, + end_node + }; + struct test_node stream[] = { + { T_MAP, 0, 0, map }, + end_node + }; + +--- +test: Sequence of sequences +spec: 2.5 +yaml: | + - [ name , hr , avg ] + - [ Mark McGwire , 65 , 0.278 ] + - [ Sammy Sosa , 63 , 0.288 ] +php: | + array( + array( 'name', 'hr', 'avg' ), + array( 'Mark McGwire', 65, 0.278 ), + array( 'Sammy Sosa', 63, 0.288 ) + ) +--- +test: Mapping of mappings +todo: true +spec: 2.6 +yaml: | + Mark McGwire: {hr: 65, avg: 0.278} + Sammy Sosa: { + hr: 63, + avg: 0.288 + } +php: | + array( + 'Mark McGwire' => + array( 'hr' => 65, 'avg' => 0.278 ), + 'Sammy Sosa' => + array( 'hr' => 63, 'avg' => 0.288 ) + ) +--- +test: Two documents in a stream each with a leading comment +todo: true +spec: 2.7 +yaml: | + # Ranking of 1998 home runs + --- + - Mark McGwire + - Sammy Sosa + - Ken Griffey + + # Team ranking + --- + - Chicago Cubs + - St Louis Cardinals +ruby: | + y = YAML::Stream.new + y.add( [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ] ) + y.add( [ 'Chicago Cubs', 'St Louis Cardinals' ] ) +documents: 2 + +--- +test: Play by play feed from a game +todo: true +spec: 2.8 +yaml: | + --- + time: 20:03:20 + player: Sammy Sosa + action: strike (miss) + ... + --- + time: 20:03:47 + player: Sammy Sosa + action: grand slam + ... +perl: | + [ 'Mark McGwire', 'Sammy Sosa', 'Ken Griffey' ] +documents: 2 + +--- +test: Single document with two comments +spec: 2.9 +yaml: | + hr: # 1998 hr ranking + - Mark McGwire + - Sammy Sosa + rbi: + # 1998 rbi ranking + - Sammy Sosa + - Ken Griffey +php: | + array( + 'hr' => array( 'Mark McGwire', 'Sammy Sosa' ), + 'rbi' => array( 'Sammy Sosa', 'Ken Griffey' ) + ) +--- +test: Node for Sammy Sosa appears twice in this document +spec: 2.10 +yaml: | + --- + hr: + - Mark McGwire + # Following node labeled SS + - &SS Sammy Sosa + rbi: + - *SS # Subsequent occurrence + - Ken Griffey +php: | + array( + 'hr' => + array('Mark McGwire', 'Sammy Sosa'), + 'rbi' => + array('Sammy Sosa', 'Ken Griffey') + ) +--- +test: Mapping between sequences +todo: true +spec: 2.11 +yaml: | + ? # PLAY SCHEDULE + - Detroit Tigers + - Chicago Cubs + : + - 2001-07-23 + + ? [ New York Yankees, + Atlanta Braves ] + : [ 2001-07-02, 2001-08-12, + 2001-08-14 ] +ruby: | + { + [ 'Detroit Tigers', 'Chicago Cubs' ] => [ Date.new( 2001, 7, 23 ) ], + [ 'New York Yankees', 'Atlanta Braves' ] => [ Date.new( 2001, 7, 2 ), Date.new( 2001, 8, 12 ), Date.new( 2001, 8, 14 ) ] + } +syck: | + struct test_node seq1[] = { + { T_STR, 0, "New York Yankees" }, + { T_STR, 0, "Atlanta Braves" }, + end_node + }; + struct test_node seq2[] = { + { T_STR, 0, "2001-07-02" }, + { T_STR, 0, "2001-08-12" }, + { T_STR, 0, "2001-08-14" }, + end_node + }; + struct test_node seq3[] = { + { T_STR, 0, "Detroit Tigers" }, + { T_STR, 0, "Chicago Cubs" }, + end_node + }; + struct test_node seq4[] = { + { T_STR, 0, "2001-07-23" }, + end_node + }; + struct test_node map[] = { + { T_SEQ, 0, 0, seq3 }, + { T_SEQ, 0, 0, seq4 }, + { T_SEQ, 0, 0, seq1 }, + { T_SEQ, 0, 0, seq2 }, + end_node + }; + struct test_node stream[] = { + { T_MAP, 0, 0, map }, + end_node + }; + +--- +test: Sequence key shortcut +spec: 2.12 +yaml: | + --- + # products purchased + - item : Super Hoop + quantity: 1 + - item : Basketball + quantity: 4 + - item : Big Shoes + quantity: 1 +php: | + array ( + array ( + 'item' => 'Super Hoop', + 'quantity' => 1, + ), + array ( + 'item' => 'Basketball', + 'quantity' => 4, + ), + array ( + 'item' => 'Big Shoes', + 'quantity' => 1, + ) + ) +perl: | + [ + { item => 'Super Hoop', quantity => 1 }, + { item => 'Basketball', quantity => 4 }, + { item => 'Big Shoes', quantity => 1 } + ] + +ruby: | + [ + { 'item' => 'Super Hoop', 'quantity' => 1 }, + { 'item' => 'Basketball', 'quantity' => 4 }, + { 'item' => 'Big Shoes', 'quantity' => 1 } + ] +python: | + [ + { 'item': 'Super Hoop', 'quantity': 1 }, + { 'item': 'Basketball', 'quantity': 4 }, + { 'item': 'Big Shoes', 'quantity': 1 } + ] +syck: | + struct test_node map1[] = { + { T_STR, 0, "item" }, + { T_STR, 0, "Super Hoop" }, + { T_STR, 0, "quantity" }, + { T_STR, 0, "1" }, + end_node + }; + struct test_node map2[] = { + { T_STR, 0, "item" }, + { T_STR, 0, "Basketball" }, + { T_STR, 0, "quantity" }, + { T_STR, 0, "4" }, + end_node + }; + struct test_node map3[] = { + { T_STR, 0, "item" }, + { T_STR, 0, "Big Shoes" }, + { T_STR, 0, "quantity" }, + { T_STR, 0, "1" }, + end_node + }; + struct test_node seq[] = { + { T_MAP, 0, 0, map1 }, + { T_MAP, 0, 0, map2 }, + { T_MAP, 0, 0, map3 }, + end_node + }; + struct test_node stream[] = { + { T_SEQ, 0, 0, seq }, + end_node + }; + + +--- +test: Literal perserves newlines +todo: true +spec: 2.13 +yaml: | + # ASCII Art + --- | + \//||\/|| + // || ||_ +perl: | + "\\//||\\/||\n// || ||_\n" +ruby: | + "\\//||\\/||\n// || ||_\n" +python: | + [ + flushLeft( + """ + \//||\/|| + // || ||_ + """ + ) + ] +syck: | + struct test_node stream[] = { + { T_STR, 0, "\\//||\\/||\n// || ||_\n" }, + end_node + }; + +--- +test: Folded treats newlines as a space +todo: true +spec: 2.14 +yaml: | + --- + Mark McGwire's + year was crippled + by a knee injury. +perl: | + "Mark McGwire's year was crippled by a knee injury." +ruby: | + "Mark McGwire's year was crippled by a knee injury." +python: | + [ "Mark McGwire's year was crippled by a knee injury." ] +syck: | + struct test_node stream[] = { + { T_STR, 0, "Mark McGwire's year was crippled by a knee injury." }, + end_node + }; + +--- +test: Newlines preserved for indented and blank lines +todo: true +spec: 2.15 +yaml: | + --- > + Sammy Sosa completed another + fine season with great stats. + + 63 Home Runs + 0.288 Batting Average + + What a year! +perl: | + "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n" +ruby: | + "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n" +python: | + [ + flushLeft( + """ + Sammy Sosa completed another fine season with great stats. + + 63 Home Runs + 0.288 Batting Average + + What a year! + """ + ) + ] +syck: | + struct test_node stream[] = { + { T_STR, 0, "Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n" }, + end_node + }; + + +--- +test: Indentation determines scope +spec: 2.16 +yaml: | + name: Mark McGwire + accomplishment: > + Mark set a major league + home run record in 1998. + stats: | + 65 Home Runs + 0.278 Batting Average +php: | + array( + 'name' => 'Mark McGwire', + 'accomplishment' => "Mark set a major league home run record in 1998.\n", + 'stats' => "65 Home Runs\n0.278 Batting Average\n" + ) +--- +test: Quoted scalars +todo: true +spec: 2.17 +yaml: | + unicode: "Sosa did fine.\u263A" + control: "\b1998\t1999\t2000\n" + hexesc: "\x0D\x0A is \r\n" + + single: '"Howdy!" he cried.' + quoted: ' # not a ''comment''.' + tie-fighter: '|\-*-/|' +ruby: | + { + "tie-fighter" => "|\\-*-/|", + "control"=>"\0101998\t1999\t2000\n", + "unicode"=>"Sosa did fine." + ["263A".hex ].pack('U*'), + "quoted"=>" # not a 'comment'.", + "single"=>"\"Howdy!\" he cried.", + "hexesc"=>"\r\n is \r\n" + } +--- +test: Multiline flow scalars +todo: true +spec: 2.18 +yaml: | + plain: + This unquoted scalar + spans many lines. + + quoted: "So does this + quoted scalar.\n" +ruby: | + { + 'plain' => 'This unquoted scalar spans many lines.', + 'quoted' => "So does this quoted scalar.\n" + } +--- +test: Integers +spec: 2.19 +yaml: | + canonical: 12345 + decimal: +12,345 + octal: 014 + hexadecimal: 0xC +php: | + array( + 'canonical' => 12345, + 'decimal' => 12345.0, + 'octal' => 014, + 'hexadecimal' => 0xC + ) +--- +# FIX: spec shows parens around -inf and NaN +test: Floating point +spec: 2.20 +yaml: | + canonical: 1.23015e+3 + exponential: 12.3015e+02 + fixed: 1,230.15 + negative infinity: -.inf + not a number: .NaN + float as whole number: !!float 1 +php: | + array( + 'canonical' => 1230.15, + 'exponential' => 1230.15, + 'fixed' => 1230.15, + 'negative infinity' => log(0), + 'not a number' => -log(0), + 'float as whole number' => (float) 1 + ) +--- +test: Miscellaneous +spec: 2.21 +yaml: | + null: ~ + true: true + false: false + string: '12345' +php: | + array( + '' => null, + 1 => true, + 0 => false, + 'string' => '12345' + ) +--- +test: Timestamps +todo: true +spec: 2.22 +yaml: | + canonical: 2001-12-15T02:59:43.1Z + iso8601: 2001-12-14t21:59:43.10-05:00 + spaced: 2001-12-14 21:59:43.10 -05:00 + date: 2002-12-14 # Time is noon UTC +php: | + array( + 'canonical' => YAML::mktime( 2001, 12, 15, 2, 59, 43, 0.10 ), + 'iso8601' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ), + 'spaced' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ), + 'date' => Date.new( 2002, 12, 14 ) + ) +--- +test: legacy Timestamps test +todo: true +spec: legacy D4 +yaml: | + canonical: 2001-12-15T02:59:43.00Z + iso8601: 2001-02-28t21:59:43.00-05:00 + spaced: 2001-12-14 21:59:43.00 -05:00 + date: 2002-12-14 +php: | + array( + 'canonical' => Time::utc( 2001, 12, 15, 2, 59, 43, 0 ), + 'iso8601' => YAML::mktime( 2001, 2, 28, 21, 59, 43, 0, "-05:00" ), + 'spaced' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0, "-05:00" ), + 'date' => Date.new( 2002, 12, 14 ) + ) +--- +test: Various explicit families +todo: true +spec: 2.23 +yaml: | + not-date: !str 2002-04-28 + picture: !binary | + R0lGODlhDAAMAIQAAP//9/X + 17unp5WZmZgAAAOfn515eXv + Pz7Y6OjuDg4J+fn5OTk6enp + 56enmleECcgggoBADs= + + application specific tag: !!something | + The semantics of the tag + above may be different for + different documents. + +ruby-setup: | + YAML.add_private_type( "something" ) do |type, val| + "SOMETHING: #{val}" + end +ruby: | + { + 'not-date' => '2002-04-28', + 'picture' => "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236i^\020' \202\n\001\000;", + 'application specific tag' => "SOMETHING: The semantics of the tag\nabove may be different for\ndifferent documents.\n" + } +--- +test: Application specific family +todo: true +spec: 2.24 +yaml: | + # Establish a tag prefix + --- !clarkevans.com,2002/graph/^shape + # Use the prefix: shorthand for + # !clarkevans.com,2002/graph/circle + - !^circle + center: &ORIGIN {x: 73, 'y': 129} + radius: 7 + - !^line # !clarkevans.com,2002/graph/line + start: *ORIGIN + finish: { x: 89, 'y': 102 } + - !^label + start: *ORIGIN + color: 0xFFEEBB + value: Pretty vector drawing. +ruby-setup: | + YAML.add_domain_type( "clarkevans.com,2002", 'graph/shape' ) { |type, val| + if Array === val + val << "Shape Container" + val + else + raise YAML::Error, "Invalid graph of class #{ val.class }: " + val.inspect + end + } + one_shape_proc = Proc.new { |type, val| + scheme, domain, type = type.split( /:/, 3 ) + if val.is_a? ::Hash + val['TYPE'] = "Shape: #{type}" + val + else + raise YAML::Error, "Invalid graph of class #{ val.class }: " + val.inspect + end + } + YAML.add_domain_type( "clarkevans.com,2002", 'graph/circle', &one_shape_proc ) + YAML.add_domain_type( "clarkevans.com,2002", 'graph/line', &one_shape_proc ) + YAML.add_domain_type( "clarkevans.com,2002", 'graph/label', &one_shape_proc ) +ruby: | + [ + { + "radius" => 7, + "center"=> + { + "x" => 73, + "y" => 129 + }, + "TYPE" => "Shape: graph/circle" + }, { + "finish" => + { + "x" => 89, + "y" => 102 + }, + "TYPE" => "Shape: graph/line", + "start" => + { + "x" => 73, + "y" => 129 + } + }, { + "TYPE" => "Shape: graph/label", + "value" => "Pretty vector drawing.", + "start" => + { + "x" => 73, + "y" => 129 + }, + "color" => 16772795 + }, + "Shape Container" + ] +# --- +# test: Unordered set +# spec: 2.25 +# yaml: | +# # sets are represented as a +# # mapping where each key is +# # associated with the empty string +# --- !set +# ? Mark McGwire +# ? Sammy Sosa +# ? Ken Griff +--- +test: Ordered mappings +todo: true +spec: 2.26 +yaml: | + # ordered maps are represented as + # a sequence of mappings, with + # each mapping having one key + --- !omap + - Mark McGwire: 65 + - Sammy Sosa: 63 + - Ken Griffy: 58 +ruby: | + YAML::Omap[ + 'Mark McGwire', 65, + 'Sammy Sosa', 63, + 'Ken Griffy', 58 + ] +--- +test: Invoice +dump_skip: true +spec: 2.27 +yaml: | + --- !clarkevans.com,2002/^invoice + invoice: 34843 + date : 2001-01-23 + bill-to: &id001 + given : Chris + family : Dumars + address: + lines: | + 458 Walkman Dr. + Suite #292 + city : Royal Oak + state : MI + postal : 48046 + ship-to: *id001 + product: + - + sku : BL394D + quantity : 4 + description : Basketball + price : 450.00 + - + sku : BL4438H + quantity : 1 + description : Super Hoop + price : 2392.00 + tax : 251.42 + total: 4443.52 + comments: > + Late afternoon is best. + Backup contact is Nancy + Billsmer @ 338-4338. +php: | + array( + 'invoice' => 34843, 'date' => gmmktime(0, 0, 0, 1, 23, 2001), + 'bill-to' => + array( 'given' => 'Chris', 'family' => 'Dumars', 'address' => array( 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak', 'state' => 'MI', 'postal' => 48046 ) ) + , 'ship-to' => + array( 'given' => 'Chris', 'family' => 'Dumars', 'address' => array( 'lines' => "458 Walkman Dr.\nSuite #292\n", 'city' => 'Royal Oak', 'state' => 'MI', 'postal' => 48046 ) ) + , 'product' => + array( + array( 'sku' => 'BL394D', 'quantity' => 4, 'description' => 'Basketball', 'price' => 450.00 ), + array( 'sku' => 'BL4438H', 'quantity' => 1, 'description' => 'Super Hoop', 'price' => 2392.00 ) + ), + 'tax' => 251.42, 'total' => 4443.52, + 'comments' => "Late afternoon is best. Backup contact is Nancy Billsmer @ 338-4338.\n" + ) +--- +test: Log file +todo: true +spec: 2.28 +yaml: | + --- + Time: 2001-11-23 15:01:42 -05:00 + User: ed + Warning: > + This is an error message + for the log file + --- + Time: 2001-11-23 15:02:31 -05:00 + User: ed + Warning: > + A slightly different error + message. + --- + Date: 2001-11-23 15:03:17 -05:00 + User: ed + Fatal: > + Unknown variable "bar" + Stack: + - file: TopClass.py + line: 23 + code: | + x = MoreObject("345\n") + - file: MoreClass.py + line: 58 + code: |- + foo = bar +ruby: | + y = YAML::Stream.new + y.add( { 'Time' => YAML::mktime( 2001, 11, 23, 15, 01, 42, 00, "-05:00" ), + 'User' => 'ed', 'Warning' => "This is an error message for the log file\n" } ) + y.add( { 'Time' => YAML::mktime( 2001, 11, 23, 15, 02, 31, 00, "-05:00" ), + 'User' => 'ed', 'Warning' => "A slightly different error message.\n" } ) + y.add( { 'Date' => YAML::mktime( 2001, 11, 23, 15, 03, 17, 00, "-05:00" ), + 'User' => 'ed', 'Fatal' => "Unknown variable \"bar\"\n", + 'Stack' => [ + { 'file' => 'TopClass.py', 'line' => 23, 'code' => "x = MoreObject(\"345\\n\")\n" }, + { 'file' => 'MoreClass.py', 'line' => 58, 'code' => "foo = bar" } ] } ) +documents: 3 + +--- +test: Throwaway comments +yaml: | + ### These are four throwaway comment ### + + ### lines (the second line is empty). ### + this: | # Comments may trail lines. + contains three lines of text. + The third one starts with a + # character. This isn't a comment. + + # These are three throwaway comment + # lines (the first line is empty). +php: | + array( + 'this' => "contains three lines of text.\nThe third one starts with a\n# character. This isn't a comment.\n" + ) +--- +test: Document with a single value +todo: true +yaml: | + --- > + This YAML stream contains a single text value. + The next stream is a log file - a sequence of + log entries. Adding an entry to the log is a + simple matter of appending it at the end. +ruby: | + "This YAML stream contains a single text value. The next stream is a log file - a sequence of log entries. Adding an entry to the log is a simple matter of appending it at the end.\n" +--- +test: Document stream +todo: true +yaml: | + --- + at: 2001-08-12 09:25:00.00 Z + type: GET + HTTP: '1.0' + url: '/index.html' + --- + at: 2001-08-12 09:25:10.00 Z + type: GET + HTTP: '1.0' + url: '/toc.html' +ruby: | + y = YAML::Stream.new + y.add( { + 'at' => Time::utc( 2001, 8, 12, 9, 25, 00 ), + 'type' => 'GET', + 'HTTP' => '1.0', + 'url' => '/index.html' + } ) + y.add( { + 'at' => Time::utc( 2001, 8, 12, 9, 25, 10 ), + 'type' => 'GET', + 'HTTP' => '1.0', + 'url' => '/toc.html' + } ) +documents: 2 + +--- +test: Top level mapping +yaml: | + # This stream is an example of a top-level mapping. + invoice : 34843 + date : 2001-01-23 + total : 4443.52 +php: | + array( + 'invoice' => 34843, + 'date' => gmmktime(0, 0, 0, 1, 23, 2001), + 'total' => 4443.52 + ) +--- +test: Single-line documents +todo: true +yaml: | + # The following is a sequence of three documents. + # The first contains an empty mapping, the second + # an empty sequence, and the last an empty string. + --- {} + --- [ ] + --- '' +ruby: | + y = YAML::Stream.new + y.add( {} ) + y.add( [] ) + y.add( '' ) +documents: 3 + +--- +test: Document with pause +todo: true +yaml: | + # A communication channel based on a YAML stream. + --- + sent at: 2002-06-06 11:46:25.10 Z + payload: Whatever + # Receiver can process this as soon as the following is sent: + ... + # Even if the next message is sent long after: + --- + sent at: 2002-06-06 12:05:53.47 Z + payload: Whatever + ... +ruby: | + y = YAML::Stream.new + y.add( + { 'sent at' => YAML::mktime( 2002, 6, 6, 11, 46, 25, 0.10 ), + 'payload' => 'Whatever' } + ) + y.add( + { "payload" => "Whatever", "sent at" => YAML::mktime( 2002, 6, 6, 12, 5, 53, 0.47 ) } + ) +documents: 2 + +--- +test: Explicit typing +yaml: | + integer: 12 + also int: ! "12" + string: !str 12 +php: | + array( 'integer' => 12, 'also int' => 12, 'string' => '12' ) +--- +test: Private types +todo: true +yaml: | + # Both examples below make use of the 'x-private:ball' + # type family URI, but with different semantics. + --- + pool: !!ball + number: 8 + color: black + --- + bearing: !!ball + material: steel +ruby: | + y = YAML::Stream.new + y.add( { 'pool' => + YAML::PrivateType.new( 'ball', + { 'number' => 8, 'color' => 'black' } ) } + ) + y.add( { 'bearing' => + YAML::PrivateType.new( 'ball', + { 'material' => 'steel' } ) } + ) +documents: 2 + +--- +test: Type family under yaml.org +yaml: | + # The URI is 'tag:yaml.org,2002:str' + - !str a Unicode string +php: | + array( 'a Unicode string' ) +--- +test: Type family under perl.yaml.org +todo: true +yaml: | + # The URI is 'tag:perl.yaml.org,2002:Text::Tabs' + - !perl/Text::Tabs {} +ruby: | + [ YAML::DomainType.new( 'perl.yaml.org,2002', 'Text::Tabs', {} ) ] +--- +test: Type family under clarkevans.com +todo: true +yaml: | + # The URI is 'tag:clarkevans.com,2003-02:timesheet' + - !clarkevans.com,2003-02/timesheet {} +ruby: | + [ YAML::DomainType.new( 'clarkevans.com,2003-02', 'timesheet', {} ) ] +--- +test: URI Escaping +todo: true +yaml: | + same: + - !domain.tld,2002/type\x30 value + - !domain.tld,2002/type0 value + different: # As far as the YAML parser is concerned + - !domain.tld,2002/type%30 value + - !domain.tld,2002/type0 value +ruby-setup: | + YAML.add_domain_type( "domain.tld,2002", "type0" ) { |type, val| + "ONE: #{val}" + } + YAML.add_domain_type( "domain.tld,2002", "type%30" ) { |type, val| + "TWO: #{val}" + } +ruby: | + { 'same' => [ 'ONE: value', 'ONE: value' ], 'different' => [ 'TWO: value', 'ONE: value' ] } +--- +test: URI Prefixing +todo: true +yaml: | + # 'tag:domain.tld,2002:invoice' is some type family. + invoice: !domain.tld,2002/^invoice + # 'seq' is shorthand for 'tag:yaml.org,2002:seq'. + # This does not effect '^customer' below + # because it is does not specify a prefix. + customers: !seq + # '^customer' is shorthand for the full + # notation 'tag:domain.tld,2002:customer'. + - !^customer + given : Chris + family : Dumars +ruby-setup: | + YAML.add_domain_type( "domain.tld,2002", /(invoice|customer)/ ) { |type, val| + if val.is_a? ::Hash + scheme, domain, type = type.split( /:/, 3 ) + val['type'] = "domain #{type}" + val + else + raise YAML::Error, "Not a Hash in domain.tld/invoice: " + val.inspect + end + } +ruby: | + { "invoice"=> { "customers"=> [ { "given"=>"Chris", "type"=>"domain customer", "family"=>"Dumars" } ], "type"=>"domain invoice" } } + +--- +test: Overriding anchors +yaml: | + anchor : &A001 This scalar has an anchor. + override : &A001 > + The alias node below is a + repeated use of this value. + alias : *A001 +php: | + array( 'anchor' => 'This scalar has an anchor.', + 'override' => "The alias node below is a repeated use of this value.\n", + 'alias' => "The alias node below is a repeated use of this value.\n" ) +--- +test: Flow and block formatting +todo: true +yaml: | + empty: [] + flow: [ one, two, three # May span lines, + , four, # indentation is + five ] # mostly ignored. + block: + - First item in top sequence + - + - Subordinate sequence entry + - > + A folded sequence entry + - Sixth item in top sequence +ruby: | + { 'empty' => [], 'flow' => [ 'one', 'two', 'three', 'four', 'five' ], + 'block' => [ 'First item in top sequence', [ 'Subordinate sequence entry' ], + "A folded sequence entry\n", 'Sixth item in top sequence' ] } +--- +test: Complete mapping test +todo: true +yaml: | + empty: {} + flow: { one: 1, two: 2 } + spanning: { one: 1, + two: 2 } + block: + first : First entry + second: + key: Subordinate mapping + third: + - Subordinate sequence + - { } + - Previous mapping is empty. + - A key: value pair in a sequence. + A second: key:value pair. + - The previous entry is equal to the following one. + - + A key: value pair in a sequence. + A second: key:value pair. + !float 12 : This key is a float. + ? > + ? + : This key had to be protected. + "\a" : This key had to be escaped. + ? > + This is a + multi-line + folded key + : Whose value is + also multi-line. + ? this also works as a key + : with a value at the next line. + ? + - This key + - is a sequence + : + - With a sequence value. + ? + This: key + is a: mapping + : + with a: mapping value. +ruby: | + { 'empty' => {}, 'flow' => { 'one' => 1, 'two' => 2 }, + 'spanning' => { 'one' => 1, 'two' => 2 }, + 'block' => { 'first' => 'First entry', 'second' => + { 'key' => 'Subordinate mapping' }, 'third' => + [ 'Subordinate sequence', {}, 'Previous mapping is empty.', + { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' }, + 'The previous entry is equal to the following one.', + { 'A key' => 'value pair in a sequence.', 'A second' => 'key:value pair.' } ], + 12.0 => 'This key is a float.', "?\n" => 'This key had to be protected.', + "\a" => 'This key had to be escaped.', + "This is a multi-line folded key\n" => "Whose value is also multi-line.", + 'this also works as a key' => 'with a value at the next line.', + [ 'This key', 'is a sequence' ] => [ 'With a sequence value.' ] } } + # Couldn't recreate map exactly, so we'll do a detailed check to be sure it's entact + obj_y['block'].keys.each { |k| + if Hash === k + v = obj_y['block'][k] + if k['This'] == 'key' and k['is a'] == 'mapping' and v['with a'] == 'mapping value.' + obj_r['block'][k] = v + end + end + } +--- +test: Literal explicit indentation +yaml: | + # Explicit indentation must + # be given in all the three + # following cases. + leading spaces: |2 + This value starts with four spaces. + + leading line break: |2 + + This value starts with a line break. + + leading comment indicator: |2 + # first line starts with a + # character. + + # Explicit indentation may + # also be given when it is + # not required. + redundant: |2 + This value is indented 2 spaces. +php: | + array( + 'leading spaces' => " This value starts with four spaces.\n", + 'leading line break' => "\nThis value starts with a line break.\n", + 'leading comment indicator' => "# first line starts with a\n# character.\n", + 'redundant' => "This value is indented 2 spaces.\n" + ) +--- +test: Chomping and keep modifiers +yaml: | + clipped: | + This has one newline. + + same as "clipped" above: "This has one newline.\n" + + stripped: |- + This has no newline. + + same as "stripped" above: "This has no newline." + + kept: |+ + This has two newlines. + + same as "kept" above: "This has two newlines.\n\n" +php: | + array( + 'clipped' => "This has one newline.\n", + 'same as "clipped" above' => "This has one newline.\n", + 'stripped' => 'This has no newline.', + 'same as "stripped" above' => 'This has no newline.', + 'kept' => "This has two newlines.\n\n", + 'same as "kept" above' => "This has two newlines.\n\n" + ) +--- +test: Literal combinations +todo: true +yaml: | + empty: | + + literal: | + The \ ' " characters may be + freely used. Leading white + space is significant. + + Line breaks are significant. + Thus this value contains one + empty line and ends with a + single line break, but does + not start with one. + + is equal to: "The \\ ' \" characters may \ + be\nfreely used. Leading white\n space \ + is significant.\n\nLine breaks are \ + significant.\nThus this value contains \ + one\nempty line and ends with a\nsingle \ + line break, but does\nnot start with one.\n" + + # Comments may follow a block + # scalar value. They must be + # less indented. + + # Modifiers may be combined in any order. + indented and chomped: |2- + This has no newline. + + also written as: |-2 + This has no newline. + + both are equal to: " This has no newline." +php: | + array( + 'empty' => '', + 'literal' => "The \\ ' \" characters may be\nfreely used. Leading white\n space " + + "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" + + "empty line and ends with a\nsingle line break, but does\nnot start with one.\n", + 'is equal to' => "The \\ ' \" characters may be\nfreely used. Leading white\n space " + + "is significant.\n\nLine breaks are significant.\nThus this value contains one\n" + + "empty line and ends with a\nsingle line break, but does\nnot start with one.\n", + 'indented and chomped' => ' This has no newline.', + 'also written as' => ' This has no newline.', + 'both are equal to' => ' This has no newline.' + ) +--- +test: Folded combinations +todo: true +yaml: | + empty: > + + one paragraph: > + Line feeds are converted + to spaces, so this value + contains no line breaks + except for the final one. + + multiple paragraphs: >2 + + An empty line, either + at the start or in + the value: + + Is interpreted as a + line break. Thus this + value contains three + line breaks. + + indented text: > + This is a folded + paragraph followed + by a list: + * first entry + * second entry + Followed by another + folded paragraph, + another list: + + * first entry + + * second entry + + And a final folded + paragraph. + + above is equal to: | + This is a folded paragraph followed by a list: + * first entry + * second entry + Followed by another folded paragraph, another list: + + * first entry + + * second entry + + And a final folded paragraph. + + # Explicit comments may follow + # but must be less indented. +php: | + array( + 'empty' => '', + 'one paragraph' => 'Line feeds are converted to spaces, so this value'. + " contains no line breaks except for the final one.\n", + 'multiple paragraphs' => "\nAn empty line, either at the start or in the value:\n". + "Is interpreted as a line break. Thus this value contains three line breaks.\n", + 'indented text' => "This is a folded paragraph followed by a list:\n". + " * first entry\n * second entry\nFollowed by another folded paragraph, ". + "another list:\n\n * first entry\n\n * second entry\n\nAnd a final folded paragraph.\n", + 'above is equal to' => "This is a folded paragraph followed by a list:\n". + " * first entry\n * second entry\nFollowed by another folded paragraph, ". + "another list:\n\n * first entry\n\n * second entry\n\nAnd a final folded paragraph.\n" + ) +--- +test: Single quotes +todo: true +yaml: | + empty: '' + second: '! : \ etc. can be used freely.' + third: 'a single quote '' must be escaped.' + span: 'this contains + six spaces + + and one + line break' + is same as: "this contains six spaces\nand one line break" +php: | + array( + 'empty' => '', + 'second' => '! : \\ etc. can be used freely.', + 'third' => "a single quote ' must be escaped.", + 'span' => "this contains six spaces\nand one line break", + 'is same as' => "this contains six spaces\nand one line break" + ) +--- +test: Double quotes +todo: true +yaml: | + empty: "" + second: "! : etc. can be used freely." + third: "a \" or a \\ must be escaped." + fourth: "this value ends with an LF.\n" + span: "this contains + four \ + spaces" + is equal to: "this contains four spaces" +php: | + array( + 'empty' => '', + 'second' => '! : etc. can be used freely.', + 'third' => 'a " or a \\ must be escaped.', + 'fourth' => "this value ends with an LF.\n", + 'span' => "this contains four spaces", + 'is equal to' => "this contains four spaces" + ) +--- +test: Unquoted strings +todo: true +yaml: | + first: There is no unquoted empty string. + + second: 12 ## This is an integer. + + third: !str 12 ## This is a string. + + span: this contains + six spaces + + and one + line break + + indicators: this has no comments. + #:foo and bar# are + both text. + + flow: [ can span + lines, # comment + like + this ] + + note: { one-line keys: but multi-line values } + +php: | + array( + 'first' => 'There is no unquoted empty string.', + 'second' => 12, + 'third' => '12', + 'span' => "this contains six spaces\nand one line break", + 'indicators' => "this has no comments. #:foo and bar# are both text.", + 'flow' => [ 'can span lines', 'like this' ], + 'note' => { 'one-line keys' => 'but multi-line values' } + ) +--- +test: Spanning sequences +todo: true +yaml: | + # The following are equal seqs + # with different identities. + flow: [ one, two ] + spanning: [ one, + two ] + block: + - one + - two +php: | + array( + 'flow' => [ 'one', 'two' ], + 'spanning' => [ 'one', 'two' ], + 'block' => [ 'one', 'two' ] + ) +--- +test: Flow mappings +yaml: | + # The following are equal maps + # with different identities. + flow: { one: 1, two: 2 } + block: + one: 1 + two: 2 +php: | + array( + 'flow' => array( 'one' => 1, 'two' => 2 ), + 'block' => array( 'one' => 1, 'two' => 2 ) + ) +--- +test: Representations of 12 +todo: true +yaml: | + - 12 # An integer + # The following scalars + # are loaded to the + # string value '1' '2'. + - !str 12 + - '12' + - "12" + - "\ + 1\ + 2\ + " + # Strings containing paths and regexps can be unquoted: + - /foo/bar + - d:/foo/bar + - foo/bar + - /a.*b/ +php: | + array( 12, '12', '12', '12', '12', '/foo/bar', 'd:/foo/bar', 'foo/bar', '/a.*b/' ) +--- +test: "Null" +todo: true +yaml: | + canonical: ~ + + english: null + + # This sequence has five + # entries, two with values. + sparse: + - ~ + - 2nd entry + - Null + - 4th entry + - + + four: This mapping has five keys, + only two with values. + +php: | + array ( + 'canonical' => null, + 'english' => null, + 'sparse' => array( null, '2nd entry', null, '4th entry', null ]), + 'four' => 'This mapping has five keys, only two with values.' + ) +--- +test: Omap +todo: true +yaml: | + # Explicitly typed dictionary. + Bestiary: !omap + - aardvark: African pig-like ant eater. Ugly. + - anteater: South-American ant eater. Two species. + - anaconda: South-American constrictor snake. Scary. + # Etc. +ruby: | + { + 'Bestiary' => YAML::Omap[ + 'aardvark', 'African pig-like ant eater. Ugly.', + 'anteater', 'South-American ant eater. Two species.', + 'anaconda', 'South-American constrictor snake. Scary.' + ] + } + +--- +test: Pairs +todo: true +yaml: | + # Explicitly typed pairs. + tasks: !pairs + - meeting: with team. + - meeting: with boss. + - break: lunch. + - meeting: with client. +ruby: | + { + 'tasks' => YAML::Pairs[ + 'meeting', 'with team.', + 'meeting', 'with boss.', + 'break', 'lunch.', + 'meeting', 'with client.' + ] + } + +--- +test: Set +todo: true +yaml: | + # Explicitly typed set. + baseball players: !set + Mark McGwire: + Sammy Sosa: + Ken Griffey: +ruby: | + { + 'baseball players' => YAML::Set[ + 'Mark McGwire', nil, + 'Sammy Sosa', nil, + 'Ken Griffey', nil + ] + } + +--- +test: Boolean +yaml: | + false: used as key + logical: true + answer: false +php: | + array( + false => 'used as key', + 'logical' => true, + 'answer' => false + ) +--- +test: Integer +yaml: | + canonical: 12345 + decimal: +12,345 + octal: 014 + hexadecimal: 0xC +php: | + array( + 'canonical' => 12345, + 'decimal' => 12345.0, + 'octal' => 12, + 'hexadecimal' => 12 + ) +--- +test: Float +yaml: | + canonical: 1.23015e+3 + exponential: 12.3015e+02 + fixed: 1,230.15 + negative infinity: -.inf + not a number: .NaN +php: | + array( + 'canonical' => 1230.15, + 'exponential' => 1230.15, + 'fixed' => 1230.15, + 'negative infinity' => log(0), + 'not a number' => -log(0) + ) +--- +test: Timestamp +todo: true +yaml: | + canonical: 2001-12-15T02:59:43.1Z + valid iso8601: 2001-12-14t21:59:43.10-05:00 + space separated: 2001-12-14 21:59:43.10 -05:00 + date (noon UTC): 2002-12-14 +ruby: | + array( + 'canonical' => YAML::mktime( 2001, 12, 15, 2, 59, 43, 0.10 ), + 'valid iso8601' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ), + 'space separated' => YAML::mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ), + 'date (noon UTC)' => Date.new( 2002, 12, 14 ) + ) +--- +test: Binary +todo: true +yaml: | + canonical: !binary "\ + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\ + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\ + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=" + base64: !binary | + R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5 + OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+ + +f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC + AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs= + description: > + The binary value above is a tiny arrow + encoded as a gif image. +ruby-setup: | + arrow_gif = "GIF89a\f\000\f\000\204\000\000\377\377\367\365\365\356\351\351\345fff\000\000\000\347\347\347^^^\363\363\355\216\216\216\340\340\340\237\237\237\223\223\223\247\247\247\236\236\236iiiccc\243\243\243\204\204\204\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371\377\376\371!\376\016Made with GIMP\000,\000\000\000\000\f\000\f\000\000\005, \216\2010\236\343@\024\350i\020\304\321\212\010\034\317\200M$z\357\3770\205p\270\2601f\r\e\316\001\303\001\036\020' \202\n\001\000;" +ruby: | + { + 'canonical' => arrow_gif, + 'base64' => arrow_gif, + 'description' => "The binary value above is a tiny arrow encoded as a gif image.\n" + } + +--- +test: Merge key +todo: true +yaml: | + --- + - &CENTER { x: 1, y: 2 } + - &LEFT { x: 0, y: 2 } + - &BIG { r: 10 } + - &SMALL { r: 1 } + + # All the following maps are equal: + + - # Explicit keys + x: 1 + y: 2 + r: 10 + label: center/big + + - # Merge one map + << : *CENTER + r: 10 + label: center/big + + - # Merge multiple maps + << : [ *CENTER, *BIG ] + label: center/big + + - # Override + << : [ *BIG, *LEFT, *SMALL ] + x: 1 + label: center/big + +ruby-setup: | + center = { 'x' => 1, 'y' => 2 } + left = { 'x' => 0, 'y' => 2 } + big = { 'r' => 10 } + small = { 'r' => 1 } + node1 = { 'x' => 1, 'y' => 2, 'r' => 10, 'label' => 'center/big' } + node2 = center.dup + node2.update( { 'r' => 10, 'label' => 'center/big' } ) + node3 = big.dup + node3.update( center ) + node3.update( { 'label' => 'center/big' } ) + node4 = small.dup + node4.update( left ) + node4.update( big ) + node4.update( { 'x' => 1, 'label' => 'center/big' } ) + +ruby: | + [ + center, left, big, small, node1, node2, node3, node4 + ] + +--- +test: Default key +todo: true +yaml: | + --- # Old schema + link with: + - library1.dll + - library2.dll + --- # New schema + link with: + - = : library1.dll + version: 1.2 + - = : library2.dll + version: 2.3 +ruby: | + y = YAML::Stream.new + y.add( { 'link with' => [ 'library1.dll', 'library2.dll' ] } ) + obj_h = Hash[ 'version' => 1.2 ] + obj_h.default = 'library1.dll' + obj_h2 = Hash[ 'version' => 2.3 ] + obj_h2.default = 'library2.dll' + y.add( { 'link with' => [ obj_h, obj_h2 ] } ) +documents: 2 + +--- +test: Special keys +todo: true +yaml: | + "!": These three keys + "&": had to be quoted + "=": and are normal strings. + # NOTE: the following node should NOT be serialized this way. + encoded node : + !special '!' : '!type' + !special|canonical '&' : 12 + = : value + # The proper way to serialize the above node is as follows: + node : !!type &12 value +ruby: | + { '!' => 'These three keys', '&' => 'had to be quoted', + '=' => 'and are normal strings.', + 'encoded node' => YAML::PrivateType.new( 'type', 'value' ), + 'node' => YAML::PrivateType.new( 'type', 'value' ) } diff --git a/vendor/symfony/yaml/Tests/Fixtures/YtsTypeTransfers.yml b/vendor/symfony/yaml/Tests/Fixtures/YtsTypeTransfers.yml new file mode 100644 index 0000000..46c8d4a --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/YtsTypeTransfers.yml @@ -0,0 +1,244 @@ +--- %YAML:1.0 +test: Strings +brief: > + Any group of characters beginning with an + alphabetic or numeric character is a string, + unless it belongs to one of the groups below + (such as an Integer or Time). +yaml: | + String +php: | + 'String' +--- +test: String characters +brief: > + A string can contain any alphabetic or + numeric character, along with many + punctuation characters, including the + period, dash, space, quotes, exclamation, and + question mark. +yaml: | + - What's Yaml? + - It's for writing data structures in plain text. + - And? + - And what? That's not good enough for you? + - No, I mean, "And what about Yaml?" + - Oh, oh yeah. Uh.. Yaml for Ruby. +php: | + array( + "What's Yaml?", + "It's for writing data structures in plain text.", + "And?", + "And what? That's not good enough for you?", + "No, I mean, \"And what about Yaml?\"", + "Oh, oh yeah. Uh.. Yaml for Ruby." + ) +--- +test: Indicators in Strings +brief: > + Be careful using indicators in strings. In particular, + the comma, colon, and pound sign must be used carefully. +yaml: | + the colon followed by space is an indicator: but is a string:right here + same for the pound sign: here we have it#in a string + the comma can, honestly, be used in most cases: [ but not in, inline collections ] +php: | + array( + 'the colon followed by space is an indicator' => 'but is a string:right here', + 'same for the pound sign' => 'here we have it#in a string', + 'the comma can, honestly, be used in most cases' => array('but not in', 'inline collections') + ) +--- +test: Forcing Strings +brief: > + Any YAML type can be forced into a string using the + explicit !str method. +yaml: | + date string: !str 2001-08-01 + number string: !str 192 +php: | + array( + 'date string' => '2001-08-01', + 'number string' => '192' + ) +--- +test: Single-quoted Strings +brief: > + You can also enclose your strings within single quotes, + which allows use of slashes, colons, and other indicators + freely. Inside single quotes, you can represent a single + quote in your string by using two single quotes next to + each other. +yaml: | + all my favorite symbols: '#:!/%.)' + a few i hate: '&(*' + why do i hate them?: 'it''s very hard to explain' + entities: '£ me' +php: | + array( + 'all my favorite symbols' => '#:!/%.)', + 'a few i hate' => '&(*', + 'why do i hate them?' => 'it\'s very hard to explain', + 'entities' => '£ me' + ) +--- +test: Double-quoted Strings +brief: > + Enclosing strings in double quotes allows you + to use escapings to represent ASCII and + Unicode characters. +yaml: | + i know where i want my line breaks: "one here\nand another here\n" +php: | + array( + 'i know where i want my line breaks' => "one here\nand another here\n" + ) +--- +test: Multi-line Quoted Strings +todo: true +brief: > + Both single- and double-quoted strings may be + carried on to new lines in your YAML document. + They must be indented a step and indentation + is interpreted as a single space. +yaml: | + i want a long string: "so i'm going to + let it go on and on to other lines + until i end it with a quote." +php: | + array('i want a long string' => "so i'm going to ". + "let it go on and on to other lines ". + "until i end it with a quote." + ) + +--- +test: Plain scalars +todo: true +brief: > + Unquoted strings may also span multiple lines, if they + are free of YAML space indicators and indented. +yaml: | + - My little toe is broken in two places; + - I'm crazy to have skied this way; + - I'm not the craziest he's seen, since there was always the German guy + who skied for 3 hours on a broken shin bone (just below the kneecap); + - Nevertheless, second place is respectable, and he doesn't + recommend going for the record; + - He's going to put my foot in plaster for a month; + - This would impair my skiing ability somewhat for the + duration, as can be imagined. +php: | + array( + "My little toe is broken in two places;", + "I'm crazy to have skied this way;", + "I'm not the craziest he's seen, since there was always ". + "the German guy who skied for 3 hours on a broken shin ". + "bone (just below the kneecap);", + "Nevertheless, second place is respectable, and he doesn't ". + "recommend going for the record;", + "He's going to put my foot in plaster for a month;", + "This would impair my skiing ability somewhat for the duration, ". + "as can be imagined." + ) +--- +test: 'Null' +brief: > + You can use the tilde '~' character for a null value. +yaml: | + name: Mr. Show + hosted by: Bob and David + date of next season: ~ +php: | + array( + 'name' => 'Mr. Show', + 'hosted by' => 'Bob and David', + 'date of next season' => null + ) +--- +test: Boolean +brief: > + You can use 'true' and 'false' for Boolean values. +yaml: | + Is Gus a Liar?: true + Do I rely on Gus for Sustenance?: false +php: | + array( + 'Is Gus a Liar?' => true, + 'Do I rely on Gus for Sustenance?' => false + ) +--- +test: Integers +dump_skip: true +brief: > + An integer is a series of numbers, optionally + starting with a positive or negative sign. Integers + may also contain commas for readability. +yaml: | + zero: 0 + simple: 12 + one-thousand: 1,000 + negative one-thousand: -1,000 +php: | + array( + 'zero' => 0, + 'simple' => 12, + 'one-thousand' => 1000.0, + 'negative one-thousand' => -1000.0 + ) +--- +test: Integers as Map Keys +brief: > + An integer can be used a dictionary key. +yaml: | + 1: one + 2: two + 3: three +php: | + array( + 1 => 'one', + 2 => 'two', + 3 => 'three' + ) +--- +test: Floats +dump_skip: true +brief: > + Floats are represented by numbers with decimals, + allowing for scientific notation, as well as + positive and negative infinity and "not a number." +yaml: | + a simple float: 2.00 + larger float: 1,000.09 + scientific notation: 1.00009e+3 +php: | + array( + 'a simple float' => 2.0, + 'larger float' => 1000.09, + 'scientific notation' => 1000.09 + ) +--- +test: Time +todo: true +brief: > + You can represent timestamps by using + ISO8601 format, or a variation which + allows spaces between the date, time and + time zone. +yaml: | + iso8601: 2001-12-14t21:59:43.10-05:00 + space separated: 2001-12-14 21:59:43.10 -05:00 +php: | + array( + 'iso8601' => mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ), + 'space separated' => mktime( 2001, 12, 14, 21, 59, 43, 0.10, "-05:00" ) + ) +--- +test: Date +todo: true +brief: > + A date can be represented by its year, + month and day in ISO8601 order. +yaml: | + 1976-07-31 +php: | + date( 1976, 7, 31 ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/embededPhp.yml b/vendor/symfony/yaml/Tests/Fixtures/embededPhp.yml new file mode 100644 index 0000000..ec456ed --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/embededPhp.yml @@ -0,0 +1 @@ +value: diff --git a/vendor/symfony/yaml/Tests/Fixtures/escapedCharacters.yml b/vendor/symfony/yaml/Tests/Fixtures/escapedCharacters.yml new file mode 100644 index 0000000..6ca044c --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/escapedCharacters.yml @@ -0,0 +1,155 @@ +test: outside double quotes +yaml: | + \0 \ \a \b \n +php: | + "\\0 \\ \\a \\b \\n" +--- +test: null +yaml: | + "\0" +php: | + "\x00" +--- +test: bell +yaml: | + "\a" +php: | + "\x07" +--- +test: backspace +yaml: | + "\b" +php: | + "\x08" +--- +test: horizontal tab (1) +yaml: | + "\t" +php: | + "\x09" +--- +test: horizontal tab (2) +yaml: | + "\ " +php: | + "\x09" +--- +test: line feed +yaml: | + "\n" +php: | + "\x0a" +--- +test: vertical tab +yaml: | + "\v" +php: | + "\x0b" +--- +test: form feed +yaml: | + "\f" +php: | + "\x0c" +--- +test: carriage return +yaml: | + "\r" +php: | + "\x0d" +--- +test: escape +yaml: | + "\e" +php: | + "\x1b" +--- +test: space +yaml: | + "\ " +php: | + "\x20" +--- +test: slash +yaml: | + "\/" +php: | + "\x2f" +--- +test: backslash +yaml: | + "\\" +php: | + "\\" +--- +test: Unicode next line +yaml: | + "\N" +php: | + "\xc2\x85" +--- +test: Unicode non-breaking space +yaml: | + "\_" +php: | + "\xc2\xa0" +--- +test: Unicode line separator +yaml: | + "\L" +php: | + "\xe2\x80\xa8" +--- +test: Unicode paragraph separator +yaml: | + "\P" +php: | + "\xe2\x80\xa9" +--- +test: Escaped 8-bit Unicode +yaml: | + "\x42" +php: | + "B" +--- +test: Escaped 16-bit Unicode +yaml: | + "\u20ac" +php: | + "\xe2\x82\xac" +--- +test: Escaped 32-bit Unicode +yaml: | + "\U00000043" +php: | + "C" +--- +test: Example 5.13 Escaped Characters +note: | + Currently throws an error parsing first line. Maybe Symfony Yaml doesn't support + continuation of string across multiple lines? Keeping test here but disabled. +todo: true +yaml: | + "Fun with \\ + \" \a \b \e \f \ + \n \r \t \v \0 \ + \ \_ \N \L \P \ + \x41 \u0041 \U00000041" +php: | + "Fun with \x5C\n\x22 \x07 \x08 \x1B \x0C\n\x0A \x0D \x09 \x0B \x00\n\x20 \xA0 \x85 \xe2\x80\xa8 \xe2\x80\xa9\nA A A" +--- +test: Double quotes with a line feed +yaml: | + { double: "some value\n \"some quoted string\" and 'some single quotes one'" } +php: | + array( + 'double' => "some value\n \"some quoted string\" and 'some single quotes one'" + ) +--- +test: Backslashes +yaml: | + { single: 'foo\Var', no-quotes: foo\Var, double: "foo\\Var" } +php: | + array( + 'single' => 'foo\Var', 'no-quotes' => 'foo\Var', 'double' => 'foo\Var' + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/index.yml b/vendor/symfony/yaml/Tests/Fixtures/index.yml new file mode 100644 index 0000000..3216a89 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/index.yml @@ -0,0 +1,18 @@ +- escapedCharacters +- sfComments +- sfCompact +- sfTests +- sfObjects +- sfMergeKey +- sfQuotes +- YtsAnchorAlias +- YtsBasicTests +- YtsBlockMapping +- YtsDocumentSeparator +- YtsErrorTests +- YtsFlowCollections +- YtsFoldedScalars +- YtsNullsAndEmpties +- YtsSpecificationExamples +- YtsTypeTransfers +- unindentedCollections diff --git a/vendor/symfony/yaml/Tests/Fixtures/sfComments.yml b/vendor/symfony/yaml/Tests/Fixtures/sfComments.yml new file mode 100644 index 0000000..b72a9b6 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/sfComments.yml @@ -0,0 +1,76 @@ +--- %YAML:1.0 +test: Comments at the end of a line +brief: > + Comments at the end of a line +yaml: | + ex1: "foo # bar" + ex2: "foo # bar" # comment + ex3: 'foo # bar' # comment + ex4: foo # comment + ex5: foo # comment with tab before + ex6: foo#foo # comment here + ex7: foo # ignore me # and me +php: | + array('ex1' => 'foo # bar', 'ex2' => 'foo # bar', 'ex3' => 'foo # bar', 'ex4' => 'foo', 'ex5' => 'foo', 'ex6' => 'foo#foo', 'ex7' => 'foo') +--- +test: Comments in the middle +brief: > + Comments in the middle +yaml: | + foo: + # some comment + # some comment + bar: foo + # some comment + # some comment +php: | + array('foo' => array('bar' => 'foo')) +--- +test: Comments on a hash line +brief: > + Comments on a hash line +yaml: | + foo: # a comment + foo: bar # a comment +php: | + array('foo' => array('foo' => 'bar')) +--- +test: 'Value starting with a #' +brief: > + 'Value starting with a #' +yaml: | + foo: '#bar' +php: | + array('foo' => '#bar') +--- +test: Document starting with a comment and a separator +brief: > + Commenting before document start is allowed +yaml: | + # document comment + --- + foo: bar # a comment +php: | + array('foo' => 'bar') +--- +test: Comment containing a colon on a hash line +brief: > + Comment containing a colon on a scalar line +yaml: 'foo # comment: this is also part of the comment' +php: | + 'foo' +--- +test: 'Hash key containing a #' +brief: > + 'Hash key containing a #' +yaml: 'foo#bar: baz' +php: | + array('foo#bar' => 'baz') +--- +test: 'Hash key ending with a space and a #' +brief: > + 'Hash key ending with a space and a #' +yaml: | + 'foo #': baz +php: | + array('foo #' => 'baz') diff --git a/vendor/symfony/yaml/Tests/Fixtures/sfCompact.yml b/vendor/symfony/yaml/Tests/Fixtures/sfCompact.yml new file mode 100644 index 0000000..1339d23 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/sfCompact.yml @@ -0,0 +1,159 @@ +--- %YAML:1.0 +test: Compact notation +brief: | + Compact notation for sets of mappings with single element +yaml: | + --- + # products purchased + - item : Super Hoop + - item : Basketball + quantity: 1 + - item: + name: Big Shoes + nick: Biggies + quantity: 1 +php: | + array ( + array ( + 'item' => 'Super Hoop', + ), + array ( + 'item' => 'Basketball', + 'quantity' => 1, + ), + array ( + 'item' => array( + 'name' => 'Big Shoes', + 'nick' => 'Biggies' + ), + 'quantity' => 1 + ) + ) +--- +test: Compact notation combined with inline notation +brief: | + Combinations of compact and inline notation are allowed +yaml: | + --- + items: + - { item: Super Hoop, quantity: 1 } + - [ Basketball, Big Shoes ] +php: | + array ( + 'items' => array ( + array ( + 'item' => 'Super Hoop', + 'quantity' => 1, + ), + array ( + 'Basketball', + 'Big Shoes' + ) + ) + ) +--- %YAML:1.0 +test: Compact notation +brief: | + Compact notation for sets of mappings with single element +yaml: | + --- + # products purchased + - item : Super Hoop + - item : Basketball + quantity: 1 + - item: + name: Big Shoes + nick: Biggies + quantity: 1 +php: | + array ( + array ( + 'item' => 'Super Hoop', + ), + array ( + 'item' => 'Basketball', + 'quantity' => 1, + ), + array ( + 'item' => array( + 'name' => 'Big Shoes', + 'nick' => 'Biggies' + ), + 'quantity' => 1 + ) + ) +--- +test: Compact notation combined with inline notation +brief: | + Combinations of compact and inline notation are allowed +yaml: | + --- + items: + - { item: Super Hoop, quantity: 1 } + - [ Basketball, Big Shoes ] +php: | + array ( + 'items' => array ( + array ( + 'item' => 'Super Hoop', + 'quantity' => 1, + ), + array ( + 'Basketball', + 'Big Shoes' + ) + ) + ) +--- %YAML:1.0 +test: Compact notation +brief: | + Compact notation for sets of mappings with single element +yaml: | + --- + # products purchased + - item : Super Hoop + - item : Basketball + quantity: 1 + - item: + name: Big Shoes + nick: Biggies + quantity: 1 +php: | + array ( + array ( + 'item' => 'Super Hoop', + ), + array ( + 'item' => 'Basketball', + 'quantity' => 1, + ), + array ( + 'item' => array( + 'name' => 'Big Shoes', + 'nick' => 'Biggies' + ), + 'quantity' => 1 + ) + ) +--- +test: Compact notation combined with inline notation +brief: | + Combinations of compact and inline notation are allowed +yaml: | + --- + items: + - { item: Super Hoop, quantity: 1 } + - [ Basketball, Big Shoes ] +php: | + array ( + 'items' => array ( + array ( + 'item' => 'Super Hoop', + 'quantity' => 1, + ), + array ( + 'Basketball', + 'Big Shoes' + ) + ) + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/sfMergeKey.yml b/vendor/symfony/yaml/Tests/Fixtures/sfMergeKey.yml new file mode 100644 index 0000000..499446c --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/sfMergeKey.yml @@ -0,0 +1,66 @@ +--- %YAML:1.0 +test: Simple In Place Substitution +brief: > + If you want to reuse an entire alias, only overwriting what is different + you can use a << in place substitution. This is not part of the official + YAML spec, but a widely implemented extension. See the following URL for + details: http://yaml.org/type/merge.html +yaml: | + foo: &foo + a: Steve + b: Clark + c: Brian + e: notnull + bar: + a: before + d: other + e: ~ + <<: *foo + b: new + x: Oren + c: + foo: bar + foo: ignore + bar: foo + bar_inline: {a: before, d: other, <<: *foo, b: new, x: Oren, c: { foo: bar, foo: ignore, bar: foo}} + duplicate: + foo: bar + foo: ignore + foo2: &foo2 + a: Ballmer + ding: &dong [ fi, fei, fo, fam] + check: + <<: + - *foo + - *dong + isit: tested + head: + <<: [ *foo , *dong , *foo2 ] + taz: &taz + a: Steve + w: + p: 1234 + nested: + <<: *taz + d: Doug + w: &nestedref + p: 12345 + z: + <<: *nestedref + head_inline: &head_inline { <<: [ *foo , *dong , *foo2 ] } + recursive_inline: { <<: *head_inline, c: { <<: *foo2 } } +php: | + array( + 'foo' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian', 'e' => 'notnull'), + 'bar' => array('a' => 'before', 'd' => 'other', 'e' => null, 'b' => 'new', 'c' => array('foo' => 'bar', 'bar' => 'foo'), 'x' => 'Oren'), + 'bar_inline' => array('a' => 'before', 'd' => 'other', 'b' => 'new', 'c' => array('foo' => 'bar', 'bar' => 'foo'), 'e' => 'notnull', 'x' => 'Oren'), + 'duplicate' => array('foo' => 'bar'), + 'foo2' => array('a' => 'Ballmer'), + 'ding' => array('fi', 'fei', 'fo', 'fam'), + 'check' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian', 'e' => 'notnull', 'fi', 'fei', 'fo', 'fam', 'isit' => 'tested'), + 'head' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian', 'e' => 'notnull', 'fi', 'fei', 'fo', 'fam'), + 'taz' => array('a' => 'Steve', 'w' => array('p' => 1234)), + 'nested' => array('a' => 'Steve', 'w' => array('p' => 12345), 'd' => 'Doug', 'z' => array('p' => 12345)), + 'head_inline' => array('a' => 'Steve', 'b' => 'Clark', 'c' => 'Brian', 'e' => 'notnull', 'fi', 'fei', 'fo', 'fam'), + 'recursive_inline' => array('a' => 'Steve', 'b' => 'Clark', 'c' => array('a' => 'Ballmer'), 'e' => 'notnull', 'fi', 'fei', 'fo', 'fam'), + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/sfObjects.yml b/vendor/symfony/yaml/Tests/Fixtures/sfObjects.yml new file mode 100644 index 0000000..ee124b2 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/sfObjects.yml @@ -0,0 +1,11 @@ +--- %YAML:1.0 +test: Objects +brief: > + Comments at the end of a line +yaml: | + ex1: "foo # bar" + ex2: "foo # bar" # comment + ex3: 'foo # bar' # comment + ex4: foo # comment +php: | + array('ex1' => 'foo # bar', 'ex2' => 'foo # bar', 'ex3' => 'foo # bar', 'ex4' => 'foo') diff --git a/vendor/symfony/yaml/Tests/Fixtures/sfQuotes.yml b/vendor/symfony/yaml/Tests/Fixtures/sfQuotes.yml new file mode 100644 index 0000000..7c60bae --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/sfQuotes.yml @@ -0,0 +1,33 @@ +--- %YAML:1.0 +test: Some characters at the beginning of a string must be escaped +brief: > + Some characters at the beginning of a string must be escaped +yaml: | + foo: '| bar' +php: | + array('foo' => '| bar') +--- +test: A key can be a quoted string +brief: > + A key can be a quoted string +yaml: | + "foo1": bar + 'foo2': bar + "foo \" bar": bar + 'foo '' bar': bar + 'foo3: ': bar + "foo4: ": bar + foo5: { "foo \" bar: ": bar, 'foo '' bar: ': bar } +php: | + array( + 'foo1' => 'bar', + 'foo2' => 'bar', + 'foo " bar' => 'bar', + 'foo \' bar' => 'bar', + 'foo3: ' => 'bar', + 'foo4: ' => 'bar', + 'foo5' => array( + 'foo " bar: ' => 'bar', + 'foo \' bar: ' => 'bar', + ), + ) diff --git a/vendor/symfony/yaml/Tests/Fixtures/sfTests.yml b/vendor/symfony/yaml/Tests/Fixtures/sfTests.yml new file mode 100644 index 0000000..a427be1 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/sfTests.yml @@ -0,0 +1,149 @@ +--- %YAML:1.0 +test: Multiple quoted string on one line +brief: > + Multiple quoted string on one line +yaml: | + stripped_title: { name: "foo bar", help: "bar foo" } +php: | + array('stripped_title' => array('name' => 'foo bar', 'help' => 'bar foo')) +--- +test: Empty sequence +yaml: | + foo: [ ] +php: | + array('foo' => array()) +--- +test: Empty value +yaml: | + foo: +php: | + array('foo' => null) +--- +test: Inline string parsing +brief: > + Inline string parsing +yaml: | + test: ['complex: string', 'another [string]'] +php: | + array('test' => array('complex: string', 'another [string]')) +--- +test: Boolean +brief: > + Boolean +yaml: | + - false + - true + - null + - ~ + - 'false' + - 'true' + - 'null' + - '~' +php: | + array( + false, + true, + null, + null, + 'false', + 'true', + 'null', + '~', + ) +--- +test: Empty lines in literal blocks +brief: > + Empty lines in literal blocks +yaml: | + foo: + bar: | + foo + + + + bar +php: | + array('foo' => array('bar' => "foo\n\n\n \nbar\n")) +--- +test: Empty lines in folded blocks +brief: > + Empty lines in folded blocks +yaml: | + foo: + bar: > + + foo + + + bar +php: | + array('foo' => array('bar' => "\nfoo\n\nbar\n")) +--- +test: IP addresses +brief: > + IP addresses +yaml: | + foo: 10.0.0.2 +php: | + array('foo' => '10.0.0.2') +--- +test: A sequence with an embedded mapping +brief: > + A sequence with an embedded mapping +yaml: | + - foo + - bar: { bar: foo } +php: | + array('foo', array('bar' => array('bar' => 'foo'))) +--- +test: A sequence with an unordered array +brief: > + A sequence with an unordered array +yaml: | + 1: foo + 0: bar +php: | + array(1 => 'foo', 0 => 'bar') +--- +test: Octal +brief: as in spec example 2.19, octal value is converted +yaml: | + foo: 0123 +php: | + array('foo' => 83) +--- +test: Octal strings +brief: Octal notation in a string must remain a string +yaml: | + foo: "0123" +php: | + array('foo' => '0123') +--- +test: Octal strings +brief: Octal notation in a string must remain a string +yaml: | + foo: '0123' +php: | + array('foo' => '0123') +--- +test: Octal strings +brief: Octal notation in a string must remain a string +yaml: | + foo: | + 0123 +php: | + array('foo' => "0123\n") +--- +test: Document as a simple hash +brief: Document as a simple hash +yaml: | + { foo: bar } +php: | + array('foo' => 'bar') +--- +test: Document as a simple array +brief: Document as a simple array +yaml: | + [ foo, bar ] +php: | + array('foo', 'bar') diff --git a/vendor/symfony/yaml/Tests/Fixtures/unindentedCollections.yml b/vendor/symfony/yaml/Tests/Fixtures/unindentedCollections.yml new file mode 100644 index 0000000..0c96108 --- /dev/null +++ b/vendor/symfony/yaml/Tests/Fixtures/unindentedCollections.yml @@ -0,0 +1,82 @@ +--- %YAML:1.0 +test: Unindented collection +brief: > + Unindented collection +yaml: | + collection: + - item1 + - item2 + - item3 +php: | + array('collection' => array('item1', 'item2', 'item3')) +--- +test: Nested unindented collection (two levels) +brief: > + Nested unindented collection +yaml: | + collection: + key: + - a + - b + - c +php: | + array('collection' => array('key' => array('a', 'b', 'c'))) +--- +test: Nested unindented collection (three levels) +brief: > + Nested unindented collection +yaml: | + collection: + key: + subkey: + - one + - two + - three +php: | + array('collection' => array('key' => array('subkey' => array('one', 'two', 'three')))) +--- +test: Key/value after unindented collection (1) +brief: > + Key/value after unindented collection (1) +yaml: | + collection: + key: + - a + - b + - c + foo: bar +php: | + array('collection' => array('key' => array('a', 'b', 'c')), 'foo' => 'bar') +--- +test: Key/value after unindented collection (at the same level) +brief: > + Key/value after unindented collection +yaml: | + collection: + key: + - a + - b + - c + foo: bar +php: | + array('collection' => array('key' => array('a', 'b', 'c'), 'foo' => 'bar')) +--- +test: Shortcut Key after unindented collection +brief: > + Key/value after unindented collection +yaml: | + collection: + - key: foo + foo: bar +php: | + array('collection' => array(array('key' => 'foo', 'foo' => 'bar'))) +--- +test: Shortcut Key after unindented collection with custom spaces +brief: > + Key/value after unindented collection +yaml: | + collection: + - key: foo + foo: bar +php: | + array('collection' => array(array('key' => 'foo', 'foo' => 'bar'))) diff --git a/vendor/symfony/yaml/Tests/InlineTest.php b/vendor/symfony/yaml/Tests/InlineTest.php new file mode 100644 index 0000000..66ef701 --- /dev/null +++ b/vendor/symfony/yaml/Tests/InlineTest.php @@ -0,0 +1,506 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Yaml\Inline; + +class InlineTest extends TestCase +{ + /** + * @dataProvider getTestsForParse + */ + public function testParse($yaml, $value) + { + $this->assertSame($value, Inline::parse($yaml), sprintf('::parse() converts an inline YAML to a PHP structure (%s)', $yaml)); + } + + /** + * @dataProvider getTestsForParseWithMapObjects + */ + public function testParseWithMapObjects($yaml, $value) + { + $actual = Inline::parse($yaml, false, false, true); + + $this->assertSame(serialize($value), serialize($actual)); + } + + /** + * @dataProvider getTestsForDump + */ + public function testDump($yaml, $value) + { + $this->assertEquals($yaml, Inline::dump($value), sprintf('::dump() converts a PHP structure to an inline YAML (%s)', $yaml)); + + $this->assertSame($value, Inline::parse(Inline::dump($value)), 'check consistency'); + } + + public function testDumpNumericValueWithLocale() + { + $locale = setlocale(LC_NUMERIC, 0); + if (false === $locale) { + $this->markTestSkipped('Your platform does not support locales.'); + } + + try { + $requiredLocales = array('fr_FR.UTF-8', 'fr_FR.UTF8', 'fr_FR.utf-8', 'fr_FR.utf8', 'French_France.1252'); + if (false === setlocale(LC_NUMERIC, $requiredLocales)) { + $this->markTestSkipped('Could not set any of required locales: '.implode(', ', $requiredLocales)); + } + + $this->assertEquals('1.2', Inline::dump(1.2)); + $this->assertContains('fr', strtolower(setlocale(LC_NUMERIC, 0))); + setlocale(LC_NUMERIC, $locale); + } catch (\Exception $e) { + setlocale(LC_NUMERIC, $locale); + throw $e; + } + } + + public function testHashStringsResemblingExponentialNumericsShouldNotBeChangedToINF() + { + $value = '686e444'; + + $this->assertSame($value, Inline::parse(Inline::dump($value))); + } + + /** + * @group legacy + * throws \Symfony\Component\Yaml\Exception\ParseException in 3.0 + */ + public function testParseScalarWithNonEscapedBlackslashShouldThrowException() + { + $this->assertSame('Foo\Var', Inline::parse('"Foo\Var"')); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testParseScalarWithNonEscapedBlackslashAtTheEndShouldThrowException() + { + Inline::parse('"Foo\\"'); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testParseScalarWithIncorrectlyQuotedStringShouldThrowException() + { + $value = "'don't do somthin' like that'"; + Inline::parse($value); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testParseScalarWithIncorrectlyDoubleQuotedStringShouldThrowException() + { + $value = '"don"t do somthin" like that"'; + Inline::parse($value); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testParseInvalidMappingKeyShouldThrowException() + { + $value = '{ "foo " bar": "bar" }'; + Inline::parse($value); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testParseInvalidMappingShouldThrowException() + { + Inline::parse('[foo] bar'); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testParseInvalidSequenceShouldThrowException() + { + Inline::parse('{ foo: bar } bar'); + } + + public function testParseScalarWithCorrectlyQuotedStringShouldReturnString() + { + $value = "'don''t do somthin'' like that'"; + $expect = "don't do somthin' like that"; + + $this->assertSame($expect, Inline::parseScalar($value)); + } + + /** + * @dataProvider getDataForParseReferences + */ + public function testParseReferences($yaml, $expected) + { + $this->assertSame($expected, Inline::parse($yaml, false, false, false, array('var' => 'var-value'))); + } + + public function getDataForParseReferences() + { + return array( + 'scalar' => array('*var', 'var-value'), + 'list' => array('[ *var ]', array('var-value')), + 'list-in-list' => array('[[ *var ]]', array(array('var-value'))), + 'map-in-list' => array('[ { key: *var } ]', array(array('key' => 'var-value'))), + 'embedded-mapping-in-list' => array('[ key: *var ]', array(array('key' => 'var-value'))), + 'map' => array('{ key: *var }', array('key' => 'var-value')), + 'list-in-map' => array('{ key: [*var] }', array('key' => array('var-value'))), + 'map-in-map' => array('{ foo: { bar: *var } }', array('foo' => array('bar' => 'var-value'))), + ); + } + + public function testParseMapReferenceInSequence() + { + $foo = array( + 'a' => 'Steve', + 'b' => 'Clark', + 'c' => 'Brian', + ); + $this->assertSame(array($foo), Inline::parse('[*foo]', false, false, false, array('foo' => $foo))); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage A reference must contain at least one character. + */ + public function testParseUnquotedAsterisk() + { + Inline::parse('{ foo: * }'); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage A reference must contain at least one character. + */ + public function testParseUnquotedAsteriskFollowedByAComment() + { + Inline::parse('{ foo: * #foo }'); + } + + /** + * @group legacy + * @expectedDeprecation Not quoting the scalar "@foo " starting with "@" is deprecated since Symfony 2.8 and will throw a ParseException in 3.0. + * throws \Symfony\Component\Yaml\Exception\ParseException in 3.0 + */ + public function testParseUnquotedScalarStartingWithReservedAtIndicator() + { + Inline::parse('{ foo: @foo }'); + } + + /** + * @group legacy + * @expectedDeprecation Not quoting the scalar "`foo " starting with "`" is deprecated since Symfony 2.8 and will throw a ParseException in 3.0. + * throws \Symfony\Component\Yaml\Exception\ParseException in 3.0 + */ + public function testParseUnquotedScalarStartingWithReservedBacktickIndicator() + { + Inline::parse('{ foo: `foo }'); + } + + /** + * @group legacy + * @expectedDeprecation Not quoting the scalar "|foo " starting with "|" is deprecated since Symfony 2.8 and will throw a ParseException in 3.0. + * throws \Symfony\Component\Yaml\Exception\ParseException in 3.0 + */ + public function testParseUnquotedScalarStartingWithLiteralStyleIndicator() + { + Inline::parse('{ foo: |foo }'); + } + + /** + * @group legacy + * @expectedDeprecation Not quoting the scalar ">foo " starting with ">" is deprecated since Symfony 2.8 and will throw a ParseException in 3.0. + * throws \Symfony\Component\Yaml\Exception\ParseException in 3.0 + */ + public function testParseUnquotedScalarStartingWithFoldedStyleIndicator() + { + Inline::parse('{ foo: >foo }'); + } + + public function getScalarIndicators() + { + return array(array('|'), array('>')); + } + + /** + * @dataProvider getDataForIsHash + */ + public function testIsHash($array, $expected) + { + $this->assertSame($expected, Inline::isHash($array)); + } + + public function getDataForIsHash() + { + return array( + array(array(), false), + array(array(1, 2, 3), false), + array(array(2 => 1, 1 => 2, 0 => 3), true), + array(array('foo' => 1, 'bar' => 2), true), + ); + } + + public function getTestsForParse() + { + return array( + array('', ''), + array('null', null), + array('false', false), + array('true', true), + array('12', 12), + array('-12', -12), + array('"quoted string"', 'quoted string'), + array("'quoted string'", 'quoted string'), + array('12.30e+02', 12.30e+02), + array('0x4D2', 0x4D2), + array('02333', 02333), + array('.Inf', -log(0)), + array('-.Inf', log(0)), + array("'686e444'", '686e444'), + array('686e444', 646e444), + array('123456789123456789123456789123456789', '123456789123456789123456789123456789'), + array('"foo\r\nbar"', "foo\r\nbar"), + array("'foo#bar'", 'foo#bar'), + array("'foo # bar'", 'foo # bar'), + array("'#cfcfcf'", '#cfcfcf'), + array('::form_base.html.twig', '::form_base.html.twig'), + + // Pre-YAML-1.2 booleans + array("'y'", 'y'), + array("'n'", 'n'), + array("'yes'", 'yes'), + array("'no'", 'no'), + array("'on'", 'on'), + array("'off'", 'off'), + + array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)), + array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)), + array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)), + array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)), + array('1730-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 1730)), + + array('"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''), + array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''), + + // sequences + // urls are no key value mapping. see #3609. Valid yaml "key: value" mappings require a space after the colon + array('[foo, http://urls.are/no/mappings, false, null, 12]', array('foo', 'http://urls.are/no/mappings', false, null, 12)), + array('[ foo , bar , false , null , 12 ]', array('foo', 'bar', false, null, 12)), + array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')), + + // mappings + array('{foo:bar,bar:foo,false:false,null:null,integer:12}', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), + array('{ foo : bar, bar : foo, false : false, null : null, integer : 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), + array('{foo: \'bar\', bar: \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')), + array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', array('foo' => 'bar', 'bar' => 'foo: bar')), + array('{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}', array('foo\'' => 'bar', 'bar"' => 'foo: bar')), + array('{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', array('foo: ' => 'bar', 'bar: ' => 'foo: bar')), + + // nested sequences and mappings + array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))), + array('[foo, {bar: foo}]', array('foo', array('bar' => 'foo'))), + array('{ foo: {bar: foo} }', array('foo' => array('bar' => 'foo'))), + array('{ foo: [bar, foo] }', array('foo' => array('bar', 'foo'))), + + array('[ foo, [ bar, foo ] ]', array('foo', array('bar', 'foo'))), + + array('[{ foo: {bar: foo} }]', array(array('foo' => array('bar' => 'foo')))), + + array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))), + + array('[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]', array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo')))), + + array('[foo, bar: { foo: bar }]', array('foo', '1' => array('bar' => array('foo' => 'bar')))), + array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')), + ); + } + + public function getTestsForParseWithMapObjects() + { + return array( + array('', ''), + array('null', null), + array('false', false), + array('true', true), + array('12', 12), + array('-12', -12), + array('"quoted string"', 'quoted string'), + array("'quoted string'", 'quoted string'), + array('12.30e+02', 12.30e+02), + array('0x4D2', 0x4D2), + array('02333', 02333), + array('.Inf', -log(0)), + array('-.Inf', log(0)), + array("'686e444'", '686e444'), + array('686e444', 646e444), + array('123456789123456789123456789123456789', '123456789123456789123456789123456789'), + array('"foo\r\nbar"', "foo\r\nbar"), + array("'foo#bar'", 'foo#bar'), + array("'foo # bar'", 'foo # bar'), + array("'#cfcfcf'", '#cfcfcf'), + array('::form_base.html.twig', '::form_base.html.twig'), + + array('2007-10-30', gmmktime(0, 0, 0, 10, 30, 2007)), + array('2007-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 2007)), + array('2007-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 2007)), + array('1960-10-30 02:59:43 Z', gmmktime(2, 59, 43, 10, 30, 1960)), + array('1730-10-30T02:59:43Z', gmmktime(2, 59, 43, 10, 30, 1730)), + + array('"a \\"string\\" with \'quoted strings inside\'"', 'a "string" with \'quoted strings inside\''), + array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''), + + // sequences + // urls are no key value mapping. see #3609. Valid yaml "key: value" mappings require a space after the colon + array('[foo, http://urls.are/no/mappings, false, null, 12]', array('foo', 'http://urls.are/no/mappings', false, null, 12)), + array('[ foo , bar , false , null , 12 ]', array('foo', 'bar', false, null, 12)), + array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')), + + // mappings + array('{foo:bar,bar:foo,false:false,null:null,integer:12}', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), + array('{ foo : bar, bar : foo, false : false, null : null, integer : 12 }', (object) array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), + array('{foo: \'bar\', bar: \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')), + array('{\'foo\': \'bar\', "bar": \'foo: bar\'}', (object) array('foo' => 'bar', 'bar' => 'foo: bar')), + array('{\'foo\'\'\': \'bar\', "bar\"": \'foo: bar\'}', (object) array('foo\'' => 'bar', 'bar"' => 'foo: bar')), + array('{\'foo: \': \'bar\', "bar: ": \'foo: bar\'}', (object) array('foo: ' => 'bar', 'bar: ' => 'foo: bar')), + + // nested sequences and mappings + array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))), + array('[foo, {bar: foo}]', array('foo', (object) array('bar' => 'foo'))), + array('{ foo: {bar: foo} }', (object) array('foo' => (object) array('bar' => 'foo'))), + array('{ foo: [bar, foo] }', (object) array('foo' => array('bar', 'foo'))), + + array('[ foo, [ bar, foo ] ]', array('foo', array('bar', 'foo'))), + + array('[{ foo: {bar: foo} }]', array((object) array('foo' => (object) array('bar' => 'foo')))), + + array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))), + + array('[foo, {bar: foo, foo: [foo, {bar: foo}]}, [foo, {bar: foo}]]', array('foo', (object) array('bar' => 'foo', 'foo' => array('foo', (object) array('bar' => 'foo'))), array('foo', (object) array('bar' => 'foo')))), + + array('[foo, bar: { foo: bar }]', array('foo', '1' => (object) array('bar' => (object) array('foo' => 'bar')))), + array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', (object) array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')), + + array('{}', new \stdClass()), + array('{ foo : bar, bar : {} }', (object) array('foo' => 'bar', 'bar' => new \stdClass())), + array('{ foo : [], bar : {} }', (object) array('foo' => array(), 'bar' => new \stdClass())), + array('{foo: \'bar\', bar: {} }', (object) array('foo' => 'bar', 'bar' => new \stdClass())), + array('{\'foo\': \'bar\', "bar": {}}', (object) array('foo' => 'bar', 'bar' => new \stdClass())), + array('{\'foo\': \'bar\', "bar": \'{}\'}', (object) array('foo' => 'bar', 'bar' => '{}')), + + array('[foo, [{}, {}]]', array('foo', array(new \stdClass(), new \stdClass()))), + array('[foo, [[], {}]]', array('foo', array(array(), new \stdClass()))), + array('[foo, [[{}, {}], {}]]', array('foo', array(array(new \stdClass(), new \stdClass()), new \stdClass()))), + array('[foo, {bar: {}}]', array('foo', '1' => (object) array('bar' => new \stdClass()))), + ); + } + + public function getTestsForDump() + { + return array( + array('null', null), + array('false', false), + array('true', true), + array('12', 12), + array("'quoted string'", 'quoted string'), + array('!!float 1230', 12.30e+02), + array('1234', 0x4D2), + array('1243', 02333), + array('.Inf', -log(0)), + array('-.Inf', log(0)), + array("'686e444'", '686e444'), + array('"foo\r\nbar"', "foo\r\nbar"), + array("'foo#bar'", 'foo#bar'), + array("'foo # bar'", 'foo # bar'), + array("'#cfcfcf'", '#cfcfcf'), + + array("'a \"string\" with ''quoted strings inside'''", 'a "string" with \'quoted strings inside\''), + + array("'-dash'", '-dash'), + array("'-'", '-'), + + // Pre-YAML-1.2 booleans + array("'y'", 'y'), + array("'n'", 'n'), + array("'yes'", 'yes'), + array("'no'", 'no'), + array("'on'", 'on'), + array("'off'", 'off'), + + // sequences + array('[foo, bar, false, null, 12]', array('foo', 'bar', false, null, 12)), + array('[\'foo,bar\', \'foo bar\']', array('foo,bar', 'foo bar')), + + // mappings + array('{ foo: bar, bar: foo, \'false\': false, \'null\': null, integer: 12 }', array('foo' => 'bar', 'bar' => 'foo', 'false' => false, 'null' => null, 'integer' => 12)), + array('{ foo: bar, bar: \'foo: bar\' }', array('foo' => 'bar', 'bar' => 'foo: bar')), + + // nested sequences and mappings + array('[foo, [bar, foo]]', array('foo', array('bar', 'foo'))), + + array('[foo, [bar, [foo, [bar, foo]], foo]]', array('foo', array('bar', array('foo', array('bar', 'foo')), 'foo'))), + + array('{ foo: { bar: foo } }', array('foo' => array('bar' => 'foo'))), + + array('[foo, { bar: foo }]', array('foo', array('bar' => 'foo'))), + + array('[foo, { bar: foo, foo: [foo, { bar: foo }] }, [foo, { bar: foo }]]', array('foo', array('bar' => 'foo', 'foo' => array('foo', array('bar' => 'foo'))), array('foo', array('bar' => 'foo')))), + + array('[foo, \'@foo.baz\', { \'%foo%\': \'foo is %foo%\', bar: \'%foo%\' }, true, \'@service_container\']', array('foo', '@foo.baz', array('%foo%' => 'foo is %foo%', 'bar' => '%foo%'), true, '@service_container')), + + array('{ foo: { bar: { 1: 2, baz: 3 } } }', array('foo' => array('bar' => array(1 => 2, 'baz' => 3)))), + ); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage Malformed inline YAML string: {this, is not, supported}. + */ + public function testNotSupportedMissingValue() + { + Inline::parse('{this, is not, supported}'); + } + + public function testVeryLongQuotedStrings() + { + $longStringWithQuotes = str_repeat("x\r\n\\\"x\"x", 1000); + + $yamlString = Inline::dump(array('longStringWithQuotes' => $longStringWithQuotes)); + $arrayFromYaml = Inline::parse($yamlString); + + $this->assertEquals($longStringWithQuotes, $arrayFromYaml['longStringWithQuotes']); + } + + public function testBooleanMappingKeysAreConvertedToStrings() + { + $this->assertSame(array('false' => 'foo'), Inline::parse('{false: foo}')); + $this->assertSame(array('true' => 'foo'), Inline::parse('{true: foo}')); + } + + public function testTheEmptyStringIsAValidMappingKey() + { + $this->assertSame(array('' => 'foo'), Inline::parse('{ "": foo }')); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage Unexpected end of line, expected one of ",}". + */ + public function testUnfinishedInlineMap() + { + Inline::parse("{abc: 'def'"); + } +} diff --git a/vendor/symfony/yaml/Tests/ParseExceptionTest.php b/vendor/symfony/yaml/Tests/ParseExceptionTest.php new file mode 100644 index 0000000..b7797fb --- /dev/null +++ b/vendor/symfony/yaml/Tests/ParseExceptionTest.php @@ -0,0 +1,42 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Yaml\Exception\ParseException; + +class ParseExceptionTest extends TestCase +{ + public function testGetMessage() + { + $exception = new ParseException('Error message', 42, 'foo: bar', '/var/www/app/config.yml'); + if (\PHP_VERSION_ID >= 50400) { + $message = 'Error message in "/var/www/app/config.yml" at line 42 (near "foo: bar")'; + } else { + $message = 'Error message in "\\/var\\/www\\/app\\/config.yml" at line 42 (near "foo: bar")'; + } + + $this->assertEquals($message, $exception->getMessage()); + } + + public function testGetMessageWithUnicodeInFilename() + { + $exception = new ParseException('Error message', 42, 'foo: bar', 'äöü.yml'); + if (\PHP_VERSION_ID >= 50400) { + $message = 'Error message in "äöü.yml" at line 42 (near "foo: bar")'; + } else { + $message = 'Error message in "\u00e4\u00f6\u00fc.yml" at line 42 (near "foo: bar")'; + } + + $this->assertEquals($message, $exception->getMessage()); + } +} diff --git a/vendor/symfony/yaml/Tests/ParserTest.php b/vendor/symfony/yaml/Tests/ParserTest.php new file mode 100644 index 0000000..0cf9bd4 --- /dev/null +++ b/vendor/symfony/yaml/Tests/ParserTest.php @@ -0,0 +1,1300 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Yaml\Parser; +use Symfony\Component\Yaml\Yaml; + +class ParserTest extends TestCase +{ + /** @var Parser */ + protected $parser; + + protected function setUp() + { + $this->parser = new Parser(); + } + + protected function tearDown() + { + $this->parser = null; + } + + /** + * @dataProvider getDataFormSpecifications + */ + public function testSpecifications($file, $expected, $yaml, $comment) + { + $this->assertEquals($expected, var_export($this->parser->parse($yaml), true), $comment); + } + + public function getDataFormSpecifications() + { + $parser = new Parser(); + $path = __DIR__.'/Fixtures'; + + $tests = array(); + $files = $parser->parse(file_get_contents($path.'/index.yml')); + foreach ($files as $file) { + $yamls = file_get_contents($path.'/'.$file.'.yml'); + + // split YAMLs documents + foreach (preg_split('/^---( %YAML\:1\.0)?/m', $yamls) as $yaml) { + if (!$yaml) { + continue; + } + + $test = $parser->parse($yaml); + if (isset($test['todo']) && $test['todo']) { + // TODO + } else { + eval('$expected = '.trim($test['php']).';'); + + $tests[] = array($file, var_export($expected, true), $test['yaml'], $test['test']); + } + } + } + + return $tests; + } + + public function testTabsInYaml() + { + // test tabs in YAML + $yamls = array( + "foo:\n bar", + "foo:\n bar", + "foo:\n bar", + "foo:\n bar", + ); + + foreach ($yamls as $yaml) { + try { + $content = $this->parser->parse($yaml); + + $this->fail('YAML files must not contain tabs'); + } catch (\Exception $e) { + $this->assertInstanceOf('\Exception', $e, 'YAML files must not contain tabs'); + $this->assertEquals('A YAML file cannot contain tabs as indentation at line 2 (near "'.strpbrk($yaml, "\t").'").', $e->getMessage(), 'YAML files must not contain tabs'); + } + } + } + + public function testEndOfTheDocumentMarker() + { + $yaml = <<<'EOF' +--- %YAML:1.0 +foo +... +EOF; + + $this->assertEquals('foo', $this->parser->parse($yaml)); + } + + public function getBlockChompingTests() + { + $tests = array(); + + $yaml = <<<'EOF' +foo: |- + one + two +bar: |- + one + two + +EOF; + $expected = array( + 'foo' => "one\ntwo", + 'bar' => "one\ntwo", + ); + $tests['Literal block chomping strip with single trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: |- + one + two + +bar: |- + one + two + + +EOF; + $expected = array( + 'foo' => "one\ntwo", + 'bar' => "one\ntwo", + ); + $tests['Literal block chomping strip with multiple trailing newlines'] = array($expected, $yaml); + + $yaml = <<<'EOF' +{} + + +EOF; + $expected = array(); + $tests['Literal block chomping strip with multiple trailing newlines after a 1-liner'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: |- + one + two +bar: |- + one + two +EOF; + $expected = array( + 'foo' => "one\ntwo", + 'bar' => "one\ntwo", + ); + $tests['Literal block chomping strip without trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: | + one + two +bar: | + one + two + +EOF; + $expected = array( + 'foo' => "one\ntwo\n", + 'bar' => "one\ntwo\n", + ); + $tests['Literal block chomping clip with single trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: | + one + two + +bar: | + one + two + + +EOF; + $expected = array( + 'foo' => "one\ntwo\n", + 'bar' => "one\ntwo\n", + ); + $tests['Literal block chomping clip with multiple trailing newlines'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: +- bar: | + one + + two +EOF; + $expected = array( + 'foo' => array( + array( + 'bar' => "one\n\ntwo", + ), + ), + ); + $tests['Literal block chomping clip with embedded blank line inside unindented collection'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: | + one + two +bar: | + one + two +EOF; + $expected = array( + 'foo' => "one\ntwo\n", + 'bar' => "one\ntwo", + ); + $tests['Literal block chomping clip without trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: |+ + one + two +bar: |+ + one + two + +EOF; + $expected = array( + 'foo' => "one\ntwo\n", + 'bar' => "one\ntwo\n", + ); + $tests['Literal block chomping keep with single trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: |+ + one + two + +bar: |+ + one + two + + +EOF; + $expected = array( + 'foo' => "one\ntwo\n\n", + 'bar' => "one\ntwo\n\n", + ); + $tests['Literal block chomping keep with multiple trailing newlines'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: |+ + one + two +bar: |+ + one + two +EOF; + $expected = array( + 'foo' => "one\ntwo\n", + 'bar' => "one\ntwo", + ); + $tests['Literal block chomping keep without trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: >- + one + two +bar: >- + one + two + +EOF; + $expected = array( + 'foo' => 'one two', + 'bar' => 'one two', + ); + $tests['Folded block chomping strip with single trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: >- + one + two + +bar: >- + one + two + + +EOF; + $expected = array( + 'foo' => 'one two', + 'bar' => 'one two', + ); + $tests['Folded block chomping strip with multiple trailing newlines'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: >- + one + two +bar: >- + one + two +EOF; + $expected = array( + 'foo' => 'one two', + 'bar' => 'one two', + ); + $tests['Folded block chomping strip without trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: > + one + two +bar: > + one + two + +EOF; + $expected = array( + 'foo' => "one two\n", + 'bar' => "one two\n", + ); + $tests['Folded block chomping clip with single trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: > + one + two + +bar: > + one + two + + +EOF; + $expected = array( + 'foo' => "one two\n", + 'bar' => "one two\n", + ); + $tests['Folded block chomping clip with multiple trailing newlines'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: > + one + two +bar: > + one + two +EOF; + $expected = array( + 'foo' => "one two\n", + 'bar' => 'one two', + ); + $tests['Folded block chomping clip without trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: >+ + one + two +bar: >+ + one + two + +EOF; + $expected = array( + 'foo' => "one two\n", + 'bar' => "one two\n", + ); + $tests['Folded block chomping keep with single trailing newline'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: >+ + one + two + +bar: >+ + one + two + + +EOF; + $expected = array( + 'foo' => "one two\n\n", + 'bar' => "one two\n\n", + ); + $tests['Folded block chomping keep with multiple trailing newlines'] = array($expected, $yaml); + + $yaml = <<<'EOF' +foo: >+ + one + two +bar: >+ + one + two +EOF; + $expected = array( + 'foo' => "one two\n", + 'bar' => 'one two', + ); + $tests['Folded block chomping keep without trailing newline'] = array($expected, $yaml); + + return $tests; + } + + /** + * @dataProvider getBlockChompingTests + */ + public function testBlockChomping($expected, $yaml) + { + $this->assertSame($expected, $this->parser->parse($yaml)); + } + + /** + * Regression test for issue #7989. + * + * @see https://github.com/symfony/symfony/issues/7989 + */ + public function testBlockLiteralWithLeadingNewlines() + { + $yaml = <<<'EOF' +foo: |- + + + bar + +EOF; + $expected = array( + 'foo' => "\n\nbar", + ); + + $this->assertSame($expected, $this->parser->parse($yaml)); + } + + public function testObjectSupportEnabled() + { + $input = <<<'EOF' +foo: !!php/object:O:30:"Symfony\Component\Yaml\Tests\B":1:{s:1:"b";s:3:"foo";} +bar: 1 +EOF; + $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, false, true), '->parse() is able to parse objects'); + + $input = <<<'EOF' +foo: !php/object:O:30:"Symfony\Component\Yaml\Tests\B":1:{s:1:"b";s:3:"foo";} +bar: 1 +EOF; + $this->assertEquals(array('foo' => new B(), 'bar' => 1), $this->parser->parse($input, false, true), '->parse() is able to parse objects'); + } + + /** + * @dataProvider invalidDumpedObjectProvider + */ + public function testObjectSupportDisabledButNoExceptions($input) + { + $this->assertEquals(array('foo' => null, 'bar' => 1), $this->parser->parse($input), '->parse() does not parse objects'); + } + + /** + * @dataProvider getObjectForMapTests + */ + public function testObjectForMap($yaml, $expected) + { + $this->assertEquals($expected, $this->parser->parse($yaml, false, false, true)); + } + + public function getObjectForMapTests() + { + $tests = array(); + + $yaml = <<<'EOF' +foo: + fiz: [cat] +EOF; + $expected = new \stdClass(); + $expected->foo = new \stdClass(); + $expected->foo->fiz = array('cat'); + $tests['mapping'] = array($yaml, $expected); + + $yaml = '{ "foo": "bar", "fiz": "cat" }'; + $expected = new \stdClass(); + $expected->foo = 'bar'; + $expected->fiz = 'cat'; + $tests['inline-mapping'] = array($yaml, $expected); + + $yaml = "foo: bar\nbaz: foobar"; + $expected = new \stdClass(); + $expected->foo = 'bar'; + $expected->baz = 'foobar'; + $tests['object-for-map-is-applied-after-parsing'] = array($yaml, $expected); + + $yaml = <<<'EOT' +array: + - key: one + - key: two +EOT; + $expected = new \stdClass(); + $expected->array = array(); + $expected->array[0] = new \stdClass(); + $expected->array[0]->key = 'one'; + $expected->array[1] = new \stdClass(); + $expected->array[1]->key = 'two'; + $tests['nest-map-and-sequence'] = array($yaml, $expected); + + $yaml = <<<'YAML' +map: + 1: one + 2: two +YAML; + $expected = new \stdClass(); + $expected->map = new \stdClass(); + $expected->map->{1} = 'one'; + $expected->map->{2} = 'two'; + $tests['numeric-keys'] = array($yaml, $expected); + + $yaml = <<<'YAML' +map: + 0: one + 1: two +YAML; + $expected = new \stdClass(); + $expected->map = new \stdClass(); + $expected->map->{0} = 'one'; + $expected->map->{1} = 'two'; + $tests['zero-indexed-numeric-keys'] = array($yaml, $expected); + + return $tests; + } + + /** + * @dataProvider invalidDumpedObjectProvider + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testObjectsSupportDisabledWithExceptions($yaml) + { + $this->parser->parse($yaml, true, false); + } + + public function invalidDumpedObjectProvider() + { + $yamlTag = <<<'EOF' +foo: !!php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";} +bar: 1 +EOF; + $localTag = <<<'EOF' +foo: !php/object:O:30:"Symfony\Tests\Component\Yaml\B":1:{s:1:"b";s:3:"foo";} +bar: 1 +EOF; + + return array( + 'yaml-tag' => array($yamlTag), + 'local-tag' => array($localTag), + ); + } + + /** + * @requires extension iconv + */ + public function testNonUtf8Exception() + { + $yamls = array( + iconv('UTF-8', 'ISO-8859-1', "foo: 'äöüß'"), + iconv('UTF-8', 'ISO-8859-15', "euro: '€'"), + iconv('UTF-8', 'CP1252', "cp1252: '©ÉÇáñ'"), + ); + + foreach ($yamls as $yaml) { + try { + $this->parser->parse($yaml); + + $this->fail('charsets other than UTF-8 are rejected.'); + } catch (\Exception $e) { + $this->assertInstanceOf('Symfony\Component\Yaml\Exception\ParseException', $e, 'charsets other than UTF-8 are rejected.'); + } + } + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testUnindentedCollectionException() + { + $yaml = <<<'EOF' + +collection: +-item1 +-item2 +-item3 + +EOF; + + $this->parser->parse($yaml); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testShortcutKeyUnindentedCollectionException() + { + $yaml = <<<'EOF' + +collection: +- key: foo + foo: bar + +EOF; + + $this->parser->parse($yaml); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessageRegExp /^Multiple documents are not supported.+/ + */ + public function testMultipleDocumentsNotSupportedException() + { + Yaml::parse(<<<'EOL' +# Ranking of 1998 home runs +--- +- Mark McGwire +- Sammy Sosa +- Ken Griffey + +# Team ranking +--- +- Chicago Cubs +- St Louis Cardinals +EOL + ); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testSequenceInAMapping() + { + Yaml::parse(<<<'EOF' +yaml: + hash: me + - array stuff +EOF + ); + } + + public function testSequenceInMappingStartedBySingleDashLine() + { + $yaml = <<<'EOT' +a: +- + b: + - + bar: baz +- foo +d: e +EOT; + $expected = array( + 'a' => array( + array( + 'b' => array( + array( + 'bar' => 'baz', + ), + ), + ), + 'foo', + ), + 'd' => 'e', + ); + + $this->assertSame($expected, $this->parser->parse($yaml)); + } + + public function testSequenceFollowedByCommentEmbeddedInMapping() + { + $yaml = <<<'EOT' +a: + b: + - c +# comment + d: e +EOT; + $expected = array( + 'a' => array( + 'b' => array('c'), + 'd' => 'e', + ), + ); + + $this->assertSame($expected, $this->parser->parse($yaml)); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + */ + public function testMappingInASequence() + { + Yaml::parse(<<<'EOF' +yaml: + - array stuff + hash: me +EOF + ); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage missing colon + */ + public function testScalarInSequence() + { + Yaml::parse(<<<'EOF' +foo: + - bar +"missing colon" + foo: bar +EOF + ); + } + + /** + * > It is an error for two equal keys to appear in the same mapping node. + * > In such a case the YAML processor may continue, ignoring the second + * > `key: value` pair and issuing an appropriate warning. This strategy + * > preserves a consistent information model for one-pass and random access + * > applications. + * + * @see http://yaml.org/spec/1.2/spec.html#id2759572 + * @see http://yaml.org/spec/1.1/#id932806 + */ + public function testMappingDuplicateKeyBlock() + { + $input = <<<'EOD' +parent: + child: first + child: duplicate +parent: + child: duplicate + child: duplicate +EOD; + $expected = array( + 'parent' => array( + 'child' => 'first', + ), + ); + $this->assertSame($expected, Yaml::parse($input)); + } + + public function testMappingDuplicateKeyFlow() + { + $input = <<<'EOD' +parent: { child: first, child: duplicate } +parent: { child: duplicate, child: duplicate } +EOD; + $expected = array( + 'parent' => array( + 'child' => 'first', + ), + ); + $this->assertSame($expected, Yaml::parse($input)); + } + + public function testEmptyValue() + { + $input = <<<'EOF' +hash: +EOF; + + $this->assertEquals(array('hash' => null), Yaml::parse($input)); + } + + public function testCommentAtTheRootIndent() + { + $this->assertEquals(array( + 'services' => array( + 'app.foo_service' => array( + 'class' => 'Foo', + ), + 'app/bar_service' => array( + 'class' => 'Bar', + ), + ), + ), Yaml::parse(<<<'EOF' +# comment 1 +services: +# comment 2 + # comment 3 + app.foo_service: + class: Foo +# comment 4 + # comment 5 + app/bar_service: + class: Bar +EOF + )); + } + + public function testStringBlockWithComments() + { + $this->assertEquals(array('content' => <<<'EOT' +# comment 1 +header + + # comment 2 + +

title

+ + +footer # comment3 +EOT + ), Yaml::parse(<<<'EOF' +content: | + # comment 1 + header + + # comment 2 + +

title

+ + + footer # comment3 +EOF + )); + } + + public function testFoldedStringBlockWithComments() + { + $this->assertEquals(array(array('content' => <<<'EOT' +# comment 1 +header + + # comment 2 + +

title

+ + +footer # comment3 +EOT + )), Yaml::parse(<<<'EOF' +- + content: | + # comment 1 + header + + # comment 2 + +

title

+ + + footer # comment3 +EOF + )); + } + + public function testNestedFoldedStringBlockWithComments() + { + $this->assertEquals(array(array( + 'title' => 'some title', + 'content' => <<<'EOT' +# comment 1 +header + + # comment 2 + +

title

+ + +footer # comment3 +EOT + )), Yaml::parse(<<<'EOF' +- + title: some title + content: | + # comment 1 + header + + # comment 2 + +

title

+ + + footer # comment3 +EOF + )); + } + + public function testReferenceResolvingInInlineStrings() + { + $this->assertEquals(array( + 'var' => 'var-value', + 'scalar' => 'var-value', + 'list' => array('var-value'), + 'list_in_list' => array(array('var-value')), + 'map_in_list' => array(array('key' => 'var-value')), + 'embedded_mapping' => array(array('key' => 'var-value')), + 'map' => array('key' => 'var-value'), + 'list_in_map' => array('key' => array('var-value')), + 'map_in_map' => array('foo' => array('bar' => 'var-value')), + ), Yaml::parse(<<<'EOF' +var: &var var-value +scalar: *var +list: [ *var ] +list_in_list: [[ *var ]] +map_in_list: [ { key: *var } ] +embedded_mapping: [ key: *var ] +map: { key: *var } +list_in_map: { key: [*var] } +map_in_map: { foo: { bar: *var } } +EOF + )); + } + + public function testYamlDirective() + { + $yaml = <<<'EOF' +%YAML 1.2 +--- +foo: 1 +bar: 2 +EOF; + $this->assertEquals(array('foo' => 1, 'bar' => 2), $this->parser->parse($yaml)); + } + + public function testFloatKeys() + { + $yaml = <<<'EOF' +foo: + 1.2: "bar" + 1.3: "baz" +EOF; + + $expected = array( + 'foo' => array( + '1.2' => 'bar', + '1.3' => 'baz', + ), + ); + + $this->assertEquals($expected, $this->parser->parse($yaml)); + } + + /** + * @group legacy + * @expectedDeprecation Using a colon in the unquoted mapping value "bar: baz" in line 1 is deprecated since Symfony 2.8 and will throw a ParseException in 3.0. + * throw ParseException in Symfony 3.0 + */ + public function testColonInMappingValueException() + { + $yaml = <<<'EOF' +foo: bar: baz +EOF; + + $this->parser->parse($yaml); + } + + public function testColonInMappingValueExceptionNotTriggeredByColonInComment() + { + $yaml = <<<'EOT' +foo: + bar: foobar # Note: a comment after a colon +EOT; + + $this->assertSame(array('foo' => array('bar' => 'foobar')), $this->parser->parse($yaml)); + } + + /** + * @dataProvider getCommentLikeStringInScalarBlockData + */ + public function testCommentLikeStringsAreNotStrippedInBlockScalars($yaml, $expectedParserResult) + { + $this->assertSame($expectedParserResult, $this->parser->parse($yaml)); + } + + public function getCommentLikeStringInScalarBlockData() + { + $tests = array(); + + $yaml = <<<'EOT' +pages: + - + title: some title + content: | + # comment 1 + header + + # comment 2 + +

title

+ + + footer # comment3 +EOT; + $expected = array( + 'pages' => array( + array( + 'title' => 'some title', + 'content' => <<<'EOT' +# comment 1 +header + + # comment 2 + +

title

+ + +footer # comment3 +EOT + , + ), + ), + ); + $tests[] = array($yaml, $expected); + + $yaml = <<<'EOT' +test: | + foo + # bar + baz +collection: + - one: | + foo + # bar + baz + - two: | + foo + # bar + baz +EOT; + $expected = array( + 'test' => <<<'EOT' +foo +# bar +baz + +EOT + , + 'collection' => array( + array( + 'one' => <<<'EOT' +foo +# bar +baz + +EOT + , + ), + array( + 'two' => <<<'EOT' +foo +# bar +baz +EOT + , + ), + ), + ); + $tests[] = array($yaml, $expected); + + $yaml = <<<'EOT' +foo: + bar: + scalar-block: > + line1 + line2> + baz: +# comment + foobar: ~ +EOT; + $expected = array( + 'foo' => array( + 'bar' => array( + 'scalar-block' => "line1 line2>\n", + ), + 'baz' => array( + 'foobar' => null, + ), + ), + ); + $tests[] = array($yaml, $expected); + + $yaml = <<<'EOT' +a: + b: hello +# c: | +# first row +# second row + d: hello +EOT; + $expected = array( + 'a' => array( + 'b' => 'hello', + 'd' => 'hello', + ), + ); + $tests[] = array($yaml, $expected); + + return $tests; + } + + public function testBlankLinesAreParsedAsNewLinesInFoldedBlocks() + { + $yaml = <<<'EOT' +test: > +

A heading

+ +
    +
  • a list
  • +
  • may be a good example
  • +
+EOT; + + $this->assertSame( + array( + 'test' => <<<'EOT' +

A heading

+
  • a list
  • may be a good example
+EOT + , + ), + $this->parser->parse($yaml) + ); + } + + public function testAdditionallyIndentedLinesAreParsedAsNewLinesInFoldedBlocks() + { + $yaml = <<<'EOT' +test: > +

A heading

+ +
    +
  • a list
  • +
  • may be a good example
  • +
+EOT; + + $this->assertSame( + array( + 'test' => <<<'EOT' +

A heading

+
    +
  • a list
  • +
  • may be a good example
  • +
+EOT + , + ), + $this->parser->parse($yaml) + ); + } + + /** + * @param $lineNumber + * @param $yaml + * @dataProvider parserThrowsExceptionWithCorrectLineNumberProvider + */ + public function testParserThrowsExceptionWithCorrectLineNumber($lineNumber, $yaml) + { + if (method_exists($this, 'expectException')) { + $this->expectException('\Symfony\Component\Yaml\Exception\ParseException'); + $this->expectExceptionMessage(sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber)); + } else { + $this->setExpectedException('\Symfony\Component\Yaml\Exception\ParseException', sprintf('Unexpected characters near "," at line %d (near "bar: "123",").', $lineNumber)); + } + + $this->parser->parse($yaml); + } + + public function parserThrowsExceptionWithCorrectLineNumberProvider() + { + return array( + array( + 4, + <<<'YAML' +foo: + - + # bar + bar: "123", +YAML + ), + array( + 5, + <<<'YAML' +foo: + - + # bar + # bar + bar: "123", +YAML + ), + array( + 8, + <<<'YAML' +foo: + - + # foobar + baz: 123 +bar: + - + # bar + bar: "123", +YAML + ), + array( + 10, + <<<'YAML' +foo: + - + # foobar + # foobar + baz: 123 +bar: + - + # bar + # bar + bar: "123", +YAML + ), + ); + } + + public function testCanParseVeryLongValue() + { + $longStringWithSpaces = str_repeat('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ', 20000); + $trickyVal = array('x' => $longStringWithSpaces); + + $yamlString = Yaml::dump($trickyVal); + $arrayFromYaml = $this->parser->parse($yamlString); + + $this->assertEquals($trickyVal, $arrayFromYaml); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage Reference "foo" does not exist at line 2 + */ + public function testParserCleansUpReferencesBetweenRuns() + { + $yaml = <<parser->parse($yaml); + + $yaml = <<parser->parse($yaml); + } + + public function testParseReferencesOnMergeKeys() + { + $yaml = << array( + 'a' => 'foo', + 'b' => 'bar', + 'c' => 'baz', + ), + 'mergekeyderef' => array( + 'd' => 'quux', + 'b' => 'bar', + 'c' => 'baz', + ), + ); + + $this->assertSame($expected, $this->parser->parse($yaml)); + } + + /** + * @expectedException \Symfony\Component\Yaml\Exception\ParseException + * @expectedExceptionMessage Reference "foo" does not exist + */ + public function testEvalRefException() + { + $yaml = <<parser->parse($yaml); + } +} + +class B +{ + public $b = 'foo'; +} diff --git a/vendor/symfony/yaml/Tests/YamlTest.php b/vendor/symfony/yaml/Tests/YamlTest.php new file mode 100644 index 0000000..9e776ca --- /dev/null +++ b/vendor/symfony/yaml/Tests/YamlTest.php @@ -0,0 +1,56 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml\Tests; + +use PHPUnit\Framework\TestCase; +use Symfony\Component\Yaml\Yaml; + +class YamlTest extends TestCase +{ + public function testParseAndDump() + { + $data = array('lorem' => 'ipsum', 'dolor' => 'sit'); + $yml = Yaml::dump($data); + $parsed = Yaml::parse($yml); + $this->assertEquals($data, $parsed); + } + + /** + * @group legacy + */ + public function testLegacyParseFromFile() + { + $filename = __DIR__.'/Fixtures/index.yml'; + $contents = file_get_contents($filename); + $parsedByFilename = Yaml::parse($filename); + $parsedByContents = Yaml::parse($contents); + $this->assertEquals($parsedByFilename, $parsedByContents); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The indentation must be greater than zero + */ + public function testZeroIndentationThrowsException() + { + Yaml::dump(array('lorem' => 'ipsum', 'dolor' => 'sit'), 2, 0); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage The indentation must be greater than zero + */ + public function testNegativeIndentationThrowsException() + { + Yaml::dump(array('lorem' => 'ipsum', 'dolor' => 'sit'), 2, -4); + } +} diff --git a/vendor/symfony/yaml/Unescaper.php b/vendor/symfony/yaml/Unescaper.php new file mode 100644 index 0000000..d0dbcfa --- /dev/null +++ b/vendor/symfony/yaml/Unescaper.php @@ -0,0 +1,156 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml; + +/** + * Unescaper encapsulates unescaping rules for single and double-quoted + * YAML strings. + * + * @author Matthew Lewinski + * + * @internal + */ +class Unescaper +{ + /** + * Parser and Inline assume UTF-8 encoding, so escaped Unicode characters + * must be converted to that encoding. + * + * @deprecated since version 2.5, to be removed in 3.0 + * + * @internal + */ + const ENCODING = 'UTF-8'; + + /** + * Regex fragment that matches an escaped character in a double quoted string. + */ + const REGEX_ESCAPED_CHARACTER = '\\\\(x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)'; + + /** + * Unescapes a single quoted string. + * + * @param string $value A single quoted string + * + * @return string The unescaped string + */ + public function unescapeSingleQuotedString($value) + { + return str_replace('\'\'', '\'', $value); + } + + /** + * Unescapes a double quoted string. + * + * @param string $value A double quoted string + * + * @return string The unescaped string + */ + public function unescapeDoubleQuotedString($value) + { + $self = $this; + $callback = function ($match) use ($self) { + return $self->unescapeCharacter($match[0]); + }; + + // evaluate the string + return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value); + } + + /** + * Unescapes a character that was found in a double-quoted string. + * + * @param string $value An escaped character + * + * @return string The unescaped character + * + * @internal This method is public to be usable as callback. It should not + * be used in user code. Should be changed in 3.0. + */ + public function unescapeCharacter($value) + { + switch ($value[1]) { + case '0': + return "\x0"; + case 'a': + return "\x7"; + case 'b': + return "\x8"; + case 't': + return "\t"; + case "\t": + return "\t"; + case 'n': + return "\n"; + case 'v': + return "\xB"; + case 'f': + return "\xC"; + case 'r': + return "\r"; + case 'e': + return "\x1B"; + case ' ': + return ' '; + case '"': + return '"'; + case '/': + return '/'; + case '\\': + return '\\'; + case 'N': + // U+0085 NEXT LINE + return "\xC2\x85"; + case '_': + // U+00A0 NO-BREAK SPACE + return "\xC2\xA0"; + case 'L': + // U+2028 LINE SEPARATOR + return "\xE2\x80\xA8"; + case 'P': + // U+2029 PARAGRAPH SEPARATOR + return "\xE2\x80\xA9"; + case 'x': + return self::utf8chr(hexdec(substr($value, 2, 2))); + case 'u': + return self::utf8chr(hexdec(substr($value, 2, 4))); + case 'U': + return self::utf8chr(hexdec(substr($value, 2, 8))); + default: + @trigger_error('Not escaping a backslash in a double-quoted string is deprecated since Symfony 2.8 and will throw a ParseException in 3.0.', E_USER_DEPRECATED); + + return $value; + } + } + + /** + * Get the UTF-8 character for the given code point. + * + * @param int $c The unicode code point + * + * @return string The corresponding UTF-8 character + */ + private static function utf8chr($c) + { + if (0x80 > $c %= 0x200000) { + return \chr($c); + } + if (0x800 > $c) { + return \chr(0xC0 | $c >> 6).\chr(0x80 | $c & 0x3F); + } + if (0x10000 > $c) { + return \chr(0xE0 | $c >> 12).\chr(0x80 | $c >> 6 & 0x3F).\chr(0x80 | $c & 0x3F); + } + + return \chr(0xF0 | $c >> 18).\chr(0x80 | $c >> 12 & 0x3F).\chr(0x80 | $c >> 6 & 0x3F).\chr(0x80 | $c & 0x3F); + } +} diff --git a/vendor/symfony/yaml/Yaml.php b/vendor/symfony/yaml/Yaml.php new file mode 100644 index 0000000..3f93cba --- /dev/null +++ b/vendor/symfony/yaml/Yaml.php @@ -0,0 +1,99 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Symfony\Component\Yaml; + +use Symfony\Component\Yaml\Exception\ParseException; + +/** + * Yaml offers convenience methods to load and dump YAML. + * + * @author Fabien Potencier + */ +class Yaml +{ + /** + * Parses YAML into a PHP value. + * + * Usage: + * + * $array = Yaml::parse(file_get_contents('config.yml')); + * print_r($array); + * + * As this method accepts both plain strings and file names as an input, + * you must validate the input before calling this method. Passing a file + * as an input is a deprecated feature and will be removed in 3.0. + * + * Note: the ability to pass file names to the Yaml::parse method is deprecated since Symfony 2.2 and will be removed in 3.0. Pass the YAML contents of the file instead. + * + * @param string $input Path to a YAML file or a string containing YAML + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * @param bool $objectForMap True if maps should return a stdClass instead of array() + * + * @return mixed The YAML converted to a PHP value + * + * @throws ParseException If the YAML is not valid + */ + public static function parse($input, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false) + { + // if input is a file, process it + $file = ''; + if (false === strpos($input, "\n") && is_file($input)) { + @trigger_error('The ability to pass file names to the '.__METHOD__.' method is deprecated since Symfony 2.2 and will be removed in 3.0. Pass the YAML contents of the file instead.', E_USER_DEPRECATED); + + if (false === is_readable($input)) { + throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $input)); + } + + $file = $input; + $input = file_get_contents($file); + } + + $yaml = new Parser(); + + try { + return $yaml->parse($input, $exceptionOnInvalidType, $objectSupport, $objectForMap); + } catch (ParseException $e) { + if ($file) { + $e->setParsedFile($file); + } + + throw $e; + } + } + + /** + * Dumps a PHP value to a YAML string. + * + * The dump method, when supplied with an array, will do its best + * to convert the array into friendly YAML. + * + * @param mixed $input The PHP value + * @param int $inline The level where you switch to inline YAML + * @param int $indent The amount of spaces to use for indentation of nested nodes + * @param bool $exceptionOnInvalidType True if an exception must be thrown on invalid types (a PHP resource or object), false otherwise + * @param bool $objectSupport True if object support is enabled, false otherwise + * + * @return string A YAML string representing the original PHP value + */ + public static function dump($input, $inline = 2, $indent = 4, $exceptionOnInvalidType = false, $objectSupport = false) + { + if ($indent < 1) { + throw new \InvalidArgumentException('The indentation must be greater than zero.'); + } + + $yaml = new Dumper(); + $yaml->setIndentation($indent); + + return $yaml->dump($input, $inline, 0, $exceptionOnInvalidType, $objectSupport); + } +} diff --git a/vendor/symfony/yaml/composer.json b/vendor/symfony/yaml/composer.json new file mode 100644 index 0000000..d073236 --- /dev/null +++ b/vendor/symfony/yaml/composer.json @@ -0,0 +1,34 @@ +{ + "name": "symfony/yaml", + "type": "library", + "description": "Symfony Yaml Component", + "keywords": [], + "homepage": "https://symfony.com", + "license": "MIT", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com" + }, + { + "name": "Symfony Community", + "homepage": "https://symfony.com/contributors" + } + ], + "require": { + "php": ">=5.3.9", + "symfony/polyfill-ctype": "~1.8" + }, + "autoload": { + "psr-4": { "Symfony\\Component\\Yaml\\": "" }, + "exclude-from-classmap": [ + "/Tests/" + ] + }, + "minimum-stability": "dev", + "extra": { + "branch-alias": { + "dev-master": "2.8-dev" + } + } +} diff --git a/vendor/symfony/yaml/phpunit.xml.dist b/vendor/symfony/yaml/phpunit.xml.dist new file mode 100644 index 0000000..b5d4d91 --- /dev/null +++ b/vendor/symfony/yaml/phpunit.xml.dist @@ -0,0 +1,30 @@ + + + + + + + + + + ./Tests/ + + + + + + ./ + + ./Tests + ./vendor + + + + diff --git a/vendor/twig/twig/.editorconfig b/vendor/twig/twig/.editorconfig new file mode 100644 index 0000000..270f1d1 --- /dev/null +++ b/vendor/twig/twig/.editorconfig @@ -0,0 +1,18 @@ +; top-most EditorConfig file +root = true + +; Unix-style newlines +[*] +end_of_line = LF + +[*.php] +indent_style = space +indent_size = 4 + +[*.test] +indent_style = space +indent_size = 4 + +[*.rst] +indent_style = space +indent_size = 4 diff --git a/vendor/twig/twig/.gitignore b/vendor/twig/twig/.gitignore new file mode 100644 index 0000000..3110362 --- /dev/null +++ b/vendor/twig/twig/.gitignore @@ -0,0 +1,5 @@ +/build +/composer.lock +/ext/twig/autom4te.cache/ +/phpunit.xml +/vendor diff --git a/vendor/twig/twig/.php_cs.dist b/vendor/twig/twig/.php_cs.dist new file mode 100644 index 0000000..d249ffb --- /dev/null +++ b/vendor/twig/twig/.php_cs.dist @@ -0,0 +1,16 @@ +setRules(array( + '@Symfony' => true, + '@Symfony:risky' => true, + 'array_syntax' => array('syntax' => 'long'), + 'php_unit_fqcn_annotation' => false, + 'no_unreachable_default_argument_value' => false, + 'braces' => array('allow_single_line_closure' => true), + 'heredoc_to_nowdoc' => false, + 'dir_constant' => false, + )) + ->setRiskyAllowed(true) + ->setFinder(PhpCsFixer\Finder::create()->in(__DIR__)) +; diff --git a/vendor/twig/twig/.travis.yml b/vendor/twig/twig/.travis.yml new file mode 100644 index 0000000..ed77405 --- /dev/null +++ b/vendor/twig/twig/.travis.yml @@ -0,0 +1,50 @@ +language: php + +sudo: false + +cache: + directories: + - vendor + - $HOME/.composer/cache/files + +php: + - 5.4 + - 5.5 + - 5.6 + - 7.0 + - 7.1 + - 7.2 + - 7.3 + - nightly + +env: + - TWIG_EXT=no + +before_install: + # turn off XDebug + - phpenv config-rm xdebug.ini || return 0 + +install: + - travis_retry composer install + +before_script: + - if [ "$TWIG_EXT" == "yes" ]; then sh -c "cd ext/twig && phpize && ./configure --enable-twig && make && make install"; fi + - if [ "$TWIG_EXT" == "yes" ]; then echo "extension=twig.so" >> `php --ini | grep "Loaded Configuration" | sed -e "s|.*:\s*||"`; fi + +script: ./vendor/bin/simple-phpunit + +matrix: + fast_finish: true + include: + - php: 5.3 + dist: precise + env: TWIG_EXT=yes + - php: 5.3 + dist: precise + env: TWIG_EXT=no + - php: 5.4 + env: TWIG_EXT=yes + - php: 5.5 + env: TWIG_EXT=yes + - php: 5.6 + env: TWIG_EXT=yes diff --git a/vendor/twig/twig/CHANGELOG b/vendor/twig/twig/CHANGELOG new file mode 100644 index 0000000..8b765dd --- /dev/null +++ b/vendor/twig/twig/CHANGELOG @@ -0,0 +1,1018 @@ +* 1.36.0 (2018-12-16) + + * made sure twig_include returns a string + * fixed multi-byte UFT-8 in escape('html_attr') + * added the "deprecated" tag + * added support for dynamically named tests + * fixed GlobalsInterface extended class + * fixed filesystem loader throwing an exception instead of returning false + +* 1.35.4 (2018-07-13) + + * ensured that syntax errors are triggered with the right line + * added the Symfony ctype polyfill as a dependency + * "js" filter now produces valid JSON + +* 1.35.3 (2018-03-20) + + * fixed block names unicity + * fixed counting children of SimpleXMLElement objects + * added missing else clause to avoid infinite loops + * fixed .. (range operator) in sandbox policy + +* 1.35.2 (2018-03-03) + + * fixed a regression in the way the profiler is registered in templates + +* 1.35.1 (2018-03-02) + + * added an exception when using "===" instead of "same as" + * fixed possible array to string conversion concealing actual error + * made variable names deterministic in compiled templates + * fixed length filter when passing an instance of IteratorAggregate + * fixed Environment::resolveTemplate to accept instances of TemplateWrapper + +* 1.35.0 (2017-09-27) + + * added Twig_Profiler_Profile::reset() + * fixed use TokenParser to return an empty Node + * added RuntimeExtensionInterface + * added circular reference detection when loading templates + +* 1.34.4 (2017-07-04) + + * added support for runtime loaders in IntegrationTestCase + * fixed deprecation when using Twig_Profiler_Dumper_Html + +* 1.34.3 (2017-06-07) + + * fixed namespaces introduction + +* 1.34.2 (2017-06-05) + + * fixed namespaces introduction + +* 1.34.1 (2017-06-05) + + * fixed namespaces introduction + +* 1.34.0 (2017-06-05) + + * added support for PHPUnit 6 when testing extensions + * fixed PHP 7.2 compatibility + * fixed template name generation in Twig_Environment::createTemplate() + * removed final tag on Twig_TokenParser_Include + * added namespaced aliases for all (non-deprecated) classes and interfaces + * dropped HHVM support + * dropped PHP 5.2 support + +* 1.33.2 (2017-04-20) + + * fixed edge case in the method cache for Twig attributes + +* 1.33.1 (2017-04-18) + + * fixed the empty() test + +* 1.33.0 (2017-03-22) + + * fixed a race condition handling when writing cache files + * "length" filter now returns string length when applied to an object that does + not implement \Countable but provides __toString() + * "empty" test will now consider the return value of the __toString() method for + objects implement __toString() but not \Countable + * fixed JS escaping for unicode characters with higher code points + +* 1.32.0 (2017-02-26) + + * fixed deprecation notice in Twig_Util_DeprecationCollector + * added a PSR-11 compatible runtime loader + * added `side` argument to `trim` to allow left or right trimming only. + +* 1.31.0 (2017-01-11) + + * added Twig_NodeCaptureInterface for nodes that capture all output + * fixed marking the environment as initialized too early + * fixed C89 compat for the C extension + * turned fatal error into exception when a previously generated cache is corrupted + * fixed offline cache warm-ups for embedded templates + +* 1.30.0 (2016-12-23) + + * added Twig_FactoryRuntimeLoader + * deprecated function/test/filter/tag overriding + * deprecated the "disable_c_ext" attribute on Twig_Node_Expression_GetAttr + +* 1.29.0 (2016-12-13) + + * fixed sandbox being left enabled if an exception is thrown while rendering + * marked some classes as being final (via @final) + * made Twig_Error report real source path when possible + * added support for {{ _self }} to provide an upgrade path from 1.x to 2.0 (replaces {{ _self.templateName }}) + * deprecated silent display of undefined blocks + * deprecated support for mbstring.func_overload != 0 + +* 1.28.2 (2016-11-23) + + * fixed precedence between getFoo() and isFoo() in Twig_Template::getAttribute() + * improved a deprecation message + +* 1.28.1 (2016-11-18) + + * fixed block() function when used with a template argument + +* 1.28.0 (2016-11-17) + + * added support for the PHP 7 null coalescing operator for the ?? Twig implementation + * exposed a way to access template data and methods in a portable way + * changed context access to use the PHP 7 null coalescing operator when available + * added the "with" tag + * added support for a custom template on the block() function + * added "is defined" support for block() and constant() + * optimized the way attributes are fetched + +* 1.27.0 (2016-10-25) + + * deprecated Twig_Parser::getEnvironment() + * deprecated Twig_Parser::addHandler() and Twig_Parser::addNodeVisitor() + * deprecated Twig_Compiler::addIndentation() + * fixed regression when registering two extensions having the same class name + * deprecated Twig_LoaderInterface::getSource() (implement Twig_SourceContextLoaderInterface instead) + * fixed the filesystem loader with relative paths + * deprecated Twig_Node::getLine() in favor of Twig_Node::getTemplateLine() + * deprecated Twig_Template::getSource() in favor of Twig_Template::getSourceContext() + * deprecated Twig_Node::getFilename() in favor of Twig_Node::getTemplateName() + * deprecated the "filename" escaping strategy (use "name" instead) + * added Twig_Source to hold information about the original template + * deprecated Twig_Error::getTemplateFile() and Twig_Error::setTemplateFile() in favor of Twig_Error::getTemplateName() and Twig_Error::setTemplateName() + * deprecated Parser::getFilename() + * fixed template paths when a template name contains a protocol like vfs:// + * improved debugging with Twig_Sandbox_SecurityError exceptions for disallowed methods and properties + +* 1.26.1 (2016-10-05) + + * removed template source code from generated template classes when debug is disabled + * fixed default implementation of Twig_Template::getDebugInfo() for better BC + * fixed regression on static calls for functions/filters/tests + +* 1.26.0 (2016-10-02) + + * added template cache invalidation based on more environment options + * added a missing deprecation notice + * fixed template paths when a template is stored in a PHAR file + * allowed filters/functions/tests implementation to use a different class than the extension they belong to + * deprecated Twig_ExtensionInterface::getName() + +* 1.25.0 (2016-09-21) + + * changed the way we store template source in template classes + * removed usage of realpath in cache keys + * fixed Twig cache sharing when used with different versions of PHP + * removed embed parent workaround for simple use cases + * deprecated the ability to store non Node instances in Node::$nodes + * deprecated Twig_Environment::getLexer(), Twig_Environment::getParser(), Twig_Environment::getCompiler() + * deprecated Twig_Compiler::getFilename() + +* 1.24.2 (2016-09-01) + + * fixed static callables + * fixed a potential PHP warning when loading the cache + * fixed a case where the autoescaping does not work as expected + +* 1.24.1 (2016-05-30) + + * fixed reserved keywords (forbids true, false, null and none keywords for variables names) + * fixed support for PHP7 (Throwable support) + * marked the following methods as being internals on Twig_Environment: + getFunctions(), getFilters(), getTests(), getFunction(), getFilter(), getTest(), + getTokenParsers(), getTags(), getNodeVisitors(), getUnaryOperators(), getBinaryOperators(), + getFunctions(), getFilters(), getGlobals(), initGlobals(), initExtensions(), and initExtension() + +* 1.24.0 (2016-01-25) + + * adding support for the ?? operator + * fixed the defined test when used on a constant, a map, or a sequence + * undeprecated _self (should only be used to get the template name, not the template instance) + * fixed parsing on PHP7 + +* 1.23.3 (2016-01-11) + + * fixed typo + +* 1.23.2 (2015-01-11) + + * added versions in deprecated messages + * made file cache tolerant for trailing (back)slashes on directory configuration + * deprecated unused Twig_Node_Expression_ExtensionReference class + +* 1.23.1 (2015-11-05) + + * fixed some exception messages which triggered PHP warnings + * fixed BC on Twig_Test_NodeTestCase + +* 1.23.0 (2015-10-29) + + * deprecated the possibility to override an extension by registering another one with the same name + * deprecated Twig_ExtensionInterface::getGlobals() (added Twig_Extension_GlobalsInterface for BC) + * deprecated Twig_ExtensionInterface::initRuntime() (added Twig_Extension_InitRuntimeInterface for BC) + * deprecated Twig_Environment::computeAlternatives() + +* 1.22.3 (2015-10-13) + + * fixed regression when using null as a cache strategy + * improved performance when checking template freshness + * fixed warnings when loaded templates do not exist + * fixed template class name generation to prevent possible collisions + * fixed logic for custom escapers to call them even on integers and null values + * changed template cache names to take into account the Twig C extension + +* 1.22.2 (2015-09-22) + + * fixed a race condition in template loading + +* 1.22.1 (2015-09-15) + + * fixed regression in template_from_string + +* 1.22.0 (2015-09-13) + + * made Twig_Test_IntegrationTestCase more flexible + * added an option to force PHP bytecode invalidation when writing a compiled template into the cache + * fixed the profiler duration for the root node + * changed template cache names to take into account enabled extensions + * deprecated Twig_Environment::clearCacheFiles(), Twig_Environment::getCacheFilename(), + Twig_Environment::writeCacheFile(), and Twig_Environment::getTemplateClassPrefix() + * added a way to override the filesystem template cache system + * added a way to get the original template source from Twig_Template + +* 1.21.2 (2015-09-09) + + * fixed variable names for the deprecation triggering code + * fixed escaping strategy detection based on filename + * added Traversable support for replace, merge, and sort + * deprecated support for character by character replacement for the "replace" filter + +* 1.21.1 (2015-08-26) + + * fixed regression when using the deprecated Twig_Test_* classes + +* 1.21.0 (2015-08-24) + + * added deprecation notices for deprecated features + * added a deprecation "framework" for filters/functions/tests and test fixtures + +* 1.20.0 (2015-08-12) + + * forbid access to the Twig environment from templates and internal parts of Twig_Template + * fixed limited RCEs when in sandbox mode + * deprecated Twig_Template::getEnvironment() + * deprecated the _self variable for usage outside of the from and import tags + * added Twig_BaseNodeVisitor to ease the compatibility of node visitors + between 1.x and 2.x + +* 1.19.0 (2015-07-31) + + * fixed wrong error message when including an undefined template in a child template + * added support for variadic filters, functions, and tests + * added support for extra positional arguments in macros + * added ignore_missing flag to the source function + * fixed batch filter with zero items + * deprecated Twig_Environment::clearTemplateCache() + * fixed sandbox disabling when using the include function + +* 1.18.2 (2015-06-06) + + * fixed template/line guessing in exceptions for nested templates + * optimized the number of inodes and the size of realpath cache when using the cache + +* 1.18.1 (2015-04-19) + + * fixed memory leaks in the C extension + * deprecated Twig_Loader_String + * fixed the slice filter when used with a SimpleXMLElement object + * fixed filesystem loader when trying to load non-files (like directories) + +* 1.18.0 (2015-01-25) + + * fixed some error messages where the line was wrong (unknown variables or argument names) + * added a new way to customize the main Module node (via empty nodes) + * added Twig_Environment::createTemplate() to create a template from a string + * added a profiler + * fixed filesystem loader cache when different file paths are used for the same template + +* 1.17.0 (2015-01-14) + + * added a 'filename' autoescaping strategy, which dynamically chooses the + autoescaping strategy for a template based on template file extension. + +* 1.16.3 (2014-12-25) + + * fixed regression for dynamic parent templates + * fixed cache management with statcache + * fixed a regression in the slice filter + +* 1.16.2 (2014-10-17) + + * fixed timezone on dates as strings + * fixed 2-words test names when a custom node class is not used + * fixed macros when using an argument named like a PHP super global (like GET or POST) + * fixed date_modify when working with DateTimeImmutable + * optimized for loops + * fixed multi-byte characters handling in the split filter + * fixed a regression in the in operator + * fixed a regression in the slice filter + +* 1.16.1 (2014-10-10) + + * improved error reporting in a sandboxed template + * fixed missing error file/line information under certain circumstances + * fixed wrong error line number in some error messages + * fixed the in operator to use strict comparisons + * sped up the slice filter + * fixed for mb function overload mb_substr acting different + * fixed the attribute() function when passing a variable for the arguments + +* 1.16.0 (2014-07-05) + + * changed url_encode to always encode according to RFC 3986 + * fixed inheritance in a 'use'-hierarchy + * removed the __toString policy check when the sandbox is disabled + * fixed recursively calling blocks in templates with inheritance + +* 1.15.1 (2014-02-13) + + * fixed the conversion of the special '0000-00-00 00:00' date + * added an error message when trying to import an undefined block from a trait + * fixed a C extension crash when accessing defined but uninitialized property. + +* 1.15.0 (2013-12-06) + + * made ignoreStrictCheck in Template::getAttribute() works with __call() methods throwing BadMethodCallException + * added min and max functions + * added the round filter + * fixed a bug that prevented the optimizers to be enabled/disabled selectively + * fixed first and last filters for UTF-8 strings + * added a source function to include the content of a template without rendering it + * fixed the C extension sandbox behavior when get or set is prepend to method name + +* 1.14.2 (2013-10-30) + + * fixed error filename/line when an error occurs in an included file + * allowed operators that contain whitespaces to have more than one whitespace + * allowed tests to be made of 1 or 2 words (like "same as" or "divisible by") + +* 1.14.1 (2013-10-15) + + * made it possible to use named operators as variables + * fixed the possibility to have a variable named 'matches' + * added support for PHP 5.5 DateTimeInterface + +* 1.14.0 (2013-10-03) + + * fixed usage of the html_attr escaping strategy to avoid double-escaping with the html strategy + * added new operators: ends with, starts with, and matches + * fixed some compatibility issues with HHVM + * added a way to add custom escaping strategies + * fixed the C extension compilation on Windows + * fixed the batch filter when using a fill argument with an exact match of elements to batch + * fixed the filesystem loader cache when a template name exists in several namespaces + * fixed template_from_string when the template includes or extends other ones + * fixed a crash of the C extension on an edge case + +* 1.13.2 (2013-08-03) + + * fixed the error line number for an error occurs in and embedded template + * fixed crashes of the C extension on some edge cases + +* 1.13.1 (2013-06-06) + + * added the possibility to ignore the filesystem constructor argument in Twig_Loader_Filesystem + * fixed Twig_Loader_Chain::exists() for a loader which implements Twig_ExistsLoaderInterface + * adjusted backtrace call to reduce memory usage when an error occurs + * added support for object instances as the second argument of the constant test + * fixed the include function when used in an assignment + +* 1.13.0 (2013-05-10) + + * fixed getting a numeric-like item on a variable ('09' for instance) + * fixed getting a boolean or float key on an array, so it is consistent with PHP's array access: + `{{ array[false] }}` behaves the same as `echo $array[false];` (equals `$array[0]`) + * made the escape filter 20% faster for happy path (escaping string for html with UTF-8) + * changed ☃ to § in tests + * enforced usage of named arguments after positional ones + +* 1.12.3 (2013-04-08) + + * fixed a security issue in the filesystem loader where it was possible to include a template one + level above the configured path + * fixed fatal error that should be an exception when adding a filter/function/test too late + * added a batch filter + * added support for encoding an array as query string in the url_encode filter + +* 1.12.2 (2013-02-09) + + * fixed the timezone used by the date filter and function when the given date contains a timezone (like 2010-01-28T15:00:00+02:00) + * fixed globals when getGlobals is called early on + * added the first and last filter + +* 1.12.1 (2013-01-15) + + * added support for object instances as the second argument of the constant function + * relaxed globals management to avoid a BC break + * added support for {{ some_string[:2] }} + +* 1.12.0 (2013-01-08) + + * added verbatim as an alias for the raw tag to avoid confusion with the raw filter + * fixed registration of tests and functions as anonymous functions + * fixed globals management + +* 1.12.0-RC1 (2012-12-29) + + * added an include function (does the same as the include tag but in a more flexible way) + * added the ability to use any PHP callable to define filters, functions, and tests + * added a syntax error when using a loop variable that is not defined + * added the ability to set default values for macro arguments + * added support for named arguments for filters, tests, and functions + * moved filters/functions/tests syntax errors to the parser + * added support for extended ternary operator syntaxes + +* 1.11.1 (2012-11-11) + + * fixed debug info line numbering (was off by 2) + * fixed escaping when calling a macro inside another one (regression introduced in 1.9.1) + * optimized variable access on PHP 5.4 + * fixed a crash of the C extension when an exception was thrown from a macro called without being imported (using _self.XXX) + +* 1.11.0 (2012-11-07) + + * fixed macro compilation when a variable name is a PHP reserved keyword + * changed the date filter behavior to always apply the default timezone, except if false is passed as the timezone + * fixed bitwise operator precedences + * added the template_from_string function + * fixed default timezone usage for the date function + * optimized the way Twig exceptions are managed (to make them faster) + * added Twig_ExistsLoaderInterface (implementing this interface in your loader make the chain loader much faster) + +* 1.10.3 (2012-10-19) + + * fixed wrong template location in some error messages + * reverted a BC break introduced in 1.10.2 + * added a split filter + +* 1.10.2 (2012-10-15) + + * fixed macro calls on PHP 5.4 + +* 1.10.1 (2012-10-15) + + * made a speed optimization to macro calls when imported via the "import" tag + * fixed C extension compilation on Windows + * fixed a segfault in the C extension when using DateTime objects + +* 1.10.0 (2012-09-28) + + * extracted functional tests framework to make it reusable for third-party extensions + * added namespaced templates support in Twig_Loader_Filesystem + * added Twig_Loader_Filesystem::prependPath() + * fixed an error when a token parser pass a closure as a test to the subparse() method + +* 1.9.2 (2012-08-25) + + * fixed the in operator for objects that contain circular references + * fixed the C extension when accessing a public property of an object implementing the \ArrayAccess interface + +* 1.9.1 (2012-07-22) + + * optimized macro calls when auto-escaping is on + * fixed wrong parent class for Twig_Function_Node + * made Twig_Loader_Chain more explicit about problems + +* 1.9.0 (2012-07-13) + + * made the parsing independent of the template loaders + * fixed exception trace when an error occurs when rendering a child template + * added escaping strategies for CSS, URL, and HTML attributes + * fixed nested embed tag calls + * added the date_modify filter + +* 1.8.3 (2012-06-17) + + * fixed paths in the filesystem loader when passing a path that ends with a slash or a backslash + * fixed escaping when a project defines a function named html or js + * fixed chmod mode to apply the umask correctly + +* 1.8.2 (2012-05-30) + + * added the abs filter + * fixed a regression when using a number in template attributes + * fixed compiler when mbstring.func_overload is set to 2 + * fixed DateTimeZone support in date filter + +* 1.8.1 (2012-05-17) + + * fixed a regression when dealing with SimpleXMLElement instances in templates + * fixed "is_safe" value for the "dump" function when "html_errors" is not defined in php.ini + * switched to use mbstring whenever possible instead of iconv (you might need to update your encoding as mbstring and iconv encoding names sometimes differ) + +* 1.8.0 (2012-05-08) + + * enforced interface when adding tests, filters, functions, and node visitors from extensions + * fixed a side-effect of the date filter where the timezone might be changed + * simplified usage of the autoescape tag; the only (optional) argument is now the escaping strategy or false (with a BC layer) + * added a way to dynamically change the auto-escaping strategy according to the template "filename" + * changed the autoescape option to also accept a supported escaping strategy (for BC, true is equivalent to html) + * added an embed tag + +* 1.7.0 (2012-04-24) + + * fixed a PHP warning when using CIFS + * fixed template line number in some exceptions + * added an iterable test + * added an error when defining two blocks with the same name in a template + * added the preserves_safety option for filters + * fixed a PHP notice when trying to access a key on a non-object/array variable + * enhanced error reporting when the template file is an instance of SplFileInfo + * added Twig_Environment::mergeGlobals() + * added compilation checks to avoid misuses of the sandbox tag + * fixed filesystem loader freshness logic for high traffic websites + * fixed random function when charset is null + +* 1.6.5 (2012-04-11) + + * fixed a regression when a template only extends another one without defining any blocks + +* 1.6.4 (2012-04-02) + + * fixed PHP notice in Twig_Error::guessTemplateLine() introduced in 1.6.3 + * fixed performance when compiling large files + * optimized parent template creation when the template does not use dynamic inheritance + +* 1.6.3 (2012-03-22) + + * fixed usage of Z_ADDREF_P for PHP 5.2 in the C extension + * fixed compilation of numeric values used in templates when using a locale where the decimal separator is not a dot + * made the strategy used to guess the real template file name and line number in exception messages much faster and more accurate + +* 1.6.2 (2012-03-18) + + * fixed sandbox mode when used with inheritance + * added preserveKeys support for the slice filter + * fixed the date filter when a DateTime instance is passed with a specific timezone + * added a trim filter + +* 1.6.1 (2012-02-29) + + * fixed Twig C extension + * removed the creation of Twig_Markup instances when not needed + * added a way to set the default global timezone for dates + * fixed the slice filter on strings when the length is not specified + * fixed the creation of the cache directory in case of a race condition + +* 1.6.0 (2012-02-04) + + * fixed raw blocks when used with the whitespace trim option + * made a speed optimization to macro calls when imported via the "from" tag + * fixed globals, parsers, visitors, filters, tests, and functions management in Twig_Environment when a new one or new extension is added + * fixed the attribute function when passing arguments + * added slice notation support for the [] operator (syntactic sugar for the slice operator) + * added a slice filter + * added string support for the reverse filter + * fixed the empty test and the length filter for Twig_Markup instances + * added a date function to ease date comparison + * fixed unary operators precedence + * added recursive parsing support in the parser + * added string and integer handling for the random function + +* 1.5.1 (2012-01-05) + + * fixed a regression when parsing strings + +* 1.5.0 (2012-01-04) + + * added Traversable objects support for the join filter + +* 1.5.0-RC2 (2011-12-30) + + * added a way to set the default global date interval format + * fixed the date filter for DateInterval instances (setTimezone() does not exist for them) + * refactored Twig_Template::display() to ease its extension + * added a number_format filter + +* 1.5.0-RC1 (2011-12-26) + + * removed the need to quote hash keys + * allowed hash keys to be any expression + * added a do tag + * added a flush tag + * added support for dynamically named filters and functions + * added a dump function to help debugging templates + * added a nl2br filter + * added a random function + * added a way to change the default format for the date filter + * fixed the lexer when an operator ending with a letter ends a line + * added string interpolation support + * enhanced exceptions for unknown filters, functions, tests, and tags + +* 1.4.0 (2011-12-07) + + * fixed lexer when using big numbers (> PHP_INT_MAX) + * added missing preserveKeys argument to the reverse filter + * fixed macros containing filter tag calls + +* 1.4.0-RC2 (2011-11-27) + + * removed usage of Reflection in Twig_Template::getAttribute() + * added a C extension that can optionally replace Twig_Template::getAttribute() + * added negative timestamp support to the date filter + +* 1.4.0-RC1 (2011-11-20) + + * optimized variable access when using PHP 5.4 + * changed the precedence of the .. operator to be more consistent with languages that implements such a feature like Ruby + * added an Exception to Twig_Loader_Array::isFresh() method when the template does not exist to be consistent with other loaders + * added Twig_Function_Node to allow more complex functions to have their own Node class + * added Twig_Filter_Node to allow more complex filters to have their own Node class + * added Twig_Test_Node to allow more complex tests to have their own Node class + * added a better error message when a template is empty but contain a BOM + * fixed "in" operator for empty strings + * fixed the "defined" test and the "default" filter (now works with more than one call (foo.bar.foo) and for both values of the strict_variables option) + * changed the way extensions are loaded (addFilter/addFunction/addGlobal/addTest/addNodeVisitor/addTokenParser/addExtension can now be called in any order) + * added Twig_Environment::display() + * made the escape filter smarter when the encoding is not supported by PHP + * added a convert_encoding filter + * moved all node manipulations outside the compile() Node method + * made several speed optimizations + +* 1.3.0 (2011-10-08) + +no changes + +* 1.3.0-RC1 (2011-10-04) + + * added an optimization for the parent() function + * added cache reloading when auto_reload is true and an extension has been modified + * added the possibility to force the escaping of a string already marked as safe (instance of Twig_Markup) + * allowed empty templates to be used as traits + * added traits support for the "parent" function + +* 1.2.0 (2011-09-13) + +no changes + +* 1.2.0-RC1 (2011-09-10) + + * enhanced the exception when a tag remains unclosed + * added support for empty Countable objects for the "empty" test + * fixed algorithm that determines if a template using inheritance is valid (no output between block definitions) + * added better support for encoding problems when escaping a string (available as of PHP 5.4) + * added a way to ignore a missing template when using the "include" tag ({% include "foo" ignore missing %}) + * added support for an array of templates to the "include" and "extends" tags ({% include ['foo', 'bar'] %}) + * added support for bitwise operators in expressions + * added the "attribute" function to allow getting dynamic attributes on variables + * added Twig_Loader_Chain + * added Twig_Loader_Array::setTemplate() + * added an optimization for the set tag when used to capture a large chunk of static text + * changed name regex to match PHP one "[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" (works for blocks, tags, functions, filters, and macros) + * removed the possibility to use the "extends" tag from a block + * added "if" modifier support to "for" loops + +* 1.1.2 (2011-07-30) + + * fixed json_encode filter on PHP 5.2 + * fixed regression introduced in 1.1.1 ({{ block(foo|lower) }}) + * fixed inheritance when using conditional parents + * fixed compilation of templates when the body of a child template is not empty + * fixed output when a macro throws an exception + * fixed a parsing problem when a large chunk of text is enclosed in a comment tag + * added PHPDoc for all Token parsers and Core extension functions + +* 1.1.1 (2011-07-17) + + * added a performance optimization in the Optimizer (also helps to lower the number of nested level calls) + * made some performance improvement for some edge cases + +* 1.1.0 (2011-06-28) + + * fixed json_encode filter + +* 1.1.0-RC3 (2011-06-24) + + * fixed method case-sensitivity when using the sandbox mode + * added timezone support for the date filter + * fixed possible security problems with NUL bytes + +* 1.1.0-RC2 (2011-06-16) + + * added an exception when the template passed to "use" is not a string + * made 'a.b is defined' not throw an exception if a is not defined (in strict mode) + * added {% line \d+ %} directive + +* 1.1.0-RC1 (2011-05-28) + +Flush your cache after upgrading. + + * fixed date filter when using a timestamp + * fixed the defined test for some cases + * fixed a parsing problem when a large chunk of text is enclosed in a raw tag + * added support for horizontal reuse of template blocks (see docs for more information) + * added whitespace control modifier to all tags (see docs for more information) + * added null as an alias for none (the null test is also an alias for the none test now) + * made TRUE, FALSE, NONE equivalent to their lowercase counterparts + * wrapped all compilation and runtime exceptions with Twig_Error_Runtime and added logic to guess the template name and line + * moved display() method to Twig_Template (generated templates should now use doDisplay() instead) + +* 1.0.0 (2011-03-27) + + * fixed output when using mbstring + * fixed duplicate call of methods when using the sandbox + * made the charset configurable for the escape filter + +* 1.0.0-RC2 (2011-02-21) + + * changed the way {% set %} works when capturing (the content is now marked as safe) + * added support for macro name in the endmacro tag + * make Twig_Error compatible with PHP 5.3.0 > + * fixed an infinite loop on some Windows configurations + * fixed the "length" filter for numbers + * fixed Template::getAttribute() as properties in PHP are case sensitive + * removed coupling between Twig_Node and Twig_Template + * fixed the ternary operator precedence rule + +* 1.0.0-RC1 (2011-01-09) + +Backward incompatibilities: + + * the "items" filter, which has been deprecated for quite a long time now, has been removed + * the "range" filter has been converted to a function: 0|range(10) -> range(0, 10) + * the "constant" filter has been converted to a function: {{ some_date|date('DATE_W3C'|constant) }} -> {{ some_date|date(constant('DATE_W3C')) }} + * the "cycle" filter has been converted to a function: {{ ['odd', 'even']|cycle(i) }} -> {{ cycle(['odd', 'even'], i) }} + * the "for" tag does not support "joined by" anymore + * the "autoescape" first argument is now "true"/"false" (instead of "on"/"off") + * the "parent" tag has been replaced by a "parent" function ({{ parent() }} instead of {% parent %}) + * the "display" tag has been replaced by a "block" function ({{ block('title') }} instead of {% display title %}) + * removed the grammar and simple token parser (moved to the Twig Extensions repository) + +Changes: + + * added "needs_context" option for filters and functions (the context is then passed as a first argument) + * added global variables support + * made macros return their value instead of echoing directly (fixes calling a macro in sandbox mode) + * added the "from" tag to import macros as functions + * added support for functions (a function is just syntactic sugar for a getAttribute() call) + * made macros callable when sandbox mode is enabled + * added an exception when a macro uses a reserved name + * the "default" filter now uses the "empty" test instead of just checking for null + * added the "empty" test + +* 0.9.10 (2010-12-16) + +Backward incompatibilities: + + * The Escaper extension is enabled by default, which means that all displayed + variables are now automatically escaped. You can revert to the previous + behavior by removing the extension via $env->removeExtension('escaper') + or just set the 'autoescape' option to 'false'. + * removed the "without loop" attribute for the "for" tag (not needed anymore + as the Optimizer take care of that for most cases) + * arrays and hashes have now a different syntax + * arrays keep the same syntax with square brackets: [1, 2] + * hashes now use curly braces (["a": "b"] should now be written as {"a": "b"}) + * support for "arrays with keys" and "hashes without keys" is not supported anymore ([1, "foo": "bar"] or {"foo": "bar", 1}) + * the i18n extension is now part of the Twig Extensions repository + +Changes: + + * added the merge filter + * removed 'is_escaper' option for filters (a left over from the previous version) -- you must use 'is_safe' now instead + * fixed usage of operators as method names (like is, in, and not) + * changed the order of execution for node visitors + * fixed default() filter behavior when used with strict_variables set to on + * fixed filesystem loader compatibility with PHAR files + * enhanced error messages when an unexpected token is parsed in an expression + * fixed filename not being added to syntax error messages + * added the autoescape option to enable/disable autoescaping + * removed the newline after a comment (mimics PHP behavior) + * added a syntax error exception when parent block is used on a template that does not extend another one + * made the Escaper extension enabled by default + * fixed sandbox extension when used with auto output escaping + * fixed escaper when wrapping a Twig_Node_Print (the original class must be preserved) + * added an Optimizer extension (enabled by default; optimizes "for" loops and "raw" filters) + * added priority to node visitors + +* 0.9.9 (2010-11-28) + +Backward incompatibilities: + * the self special variable has been renamed to _self + * the odd and even filters are now tests: + {{ foo|odd }} must now be written {{ foo is odd }} + * the "safe" filter has been renamed to "raw" + * in Node classes, + sub-nodes are now accessed via getNode() (instead of property access) + attributes via getAttribute() (instead of array access) + * the urlencode filter had been renamed to url_encode + * the include tag now merges the passed variables with the current context by default + (the old behavior is still possible by adding the "only" keyword) + * moved Exceptions to Twig_Error_* (Twig_SyntaxError/Twig_RuntimeError are now Twig_Error_Syntax/Twig_Error_Runtime) + * removed support for {{ 1 < i < 3 }} (use {{ i > 1 and i < 3 }} instead) + * the "in" filter has been removed ({{ a|in(b) }} should now be written {{ a in b }}) + +Changes: + * added file and line to Twig_Error_Runtime exceptions thrown from Twig_Template + * changed trans tag to accept any variable for the plural count + * fixed sandbox mode (__toString() method check was not enforced if called implicitly from complex statements) + * added the ** (power) operator + * changed the algorithm used for parsing expressions + * added the spaceless tag + * removed trim_blocks option + * added support for is*() methods for attributes (foo.bar now looks for foo->getBar() or foo->isBar()) + * changed all exceptions to extend Twig_Error + * fixed unary expressions ({{ not(1 or 0) }}) + * fixed child templates (with an extend tag) that uses one or more imports + * added support for {{ 1 not in [2, 3] }} (more readable than the current {{ not (1 in [2, 3]) }}) + * escaping has been rewritten + * the implementation of template inheritance has been rewritten + (blocks can now be called individually and still work with inheritance) + * fixed error handling for if tag when a syntax error occurs within a subparse process + * added a way to implement custom logic for resolving token parsers given a tag name + * fixed js escaper to be stricter (now uses a whilelist-based js escaper) + * added the following filers: "constant", "trans", "replace", "json_encode" + * added a "constant" test + * fixed objects with __toString() not being autoescaped + * fixed subscript expressions when calling __call() (methods now keep the case) + * added "test" feature (accessible via the "is" operator) + * removed the debug tag (should be done in an extension) + * fixed trans tag when no vars are used in plural form + * fixed race condition when writing template cache + * added the special _charset variable to reference the current charset + * added the special _context variable to reference the current context + * renamed self to _self (to avoid conflict) + * fixed Twig_Template::getAttribute() for protected properties + +* 0.9.8 (2010-06-28) + +Backward incompatibilities: + * the trans tag plural count is now attached to the plural tag: + old: `{% trans count %}...{% plural %}...{% endtrans %}` + new: `{% trans %}...{% plural count %}...{% endtrans %}` + + * added a way to translate strings coming from a variable ({% trans var %}) + * fixed trans tag when used with the Escaper extension + * fixed default cache umask + * removed Twig_Template instances from the debug tag output + * fixed objects with __isset() defined + * fixed set tag when used with a capture + * fixed type hinting for Twig_Environment::addFilter() method + +* 0.9.7 (2010-06-12) + +Backward incompatibilities: + * changed 'as' to '=' for the set tag ({% set title as "Title" %} must now be {% set title = "Title" %}) + * removed the sandboxed attribute of the include tag (use the new sandbox tag instead) + * refactored the Node system (if you have custom nodes, you will have to update them to use the new API) + + * added self as a special variable that refers to the current template (useful for importing macros from the current template) + * added Twig_Template instance support to the include tag + * added support for dynamic and conditional inheritance ({% extends some_var %} and {% extends standalone ? "minimum" : "base" %}) + * added a grammar sub-framework to ease the creation of custom tags + * fixed the for tag for large arrays (some loop variables are now only available for arrays and objects that implement the Countable interface) + * removed the Twig_Resource::resolveMissingFilter() method + * fixed the filter tag which did not apply filtering to included files + * added a bunch of unit tests + * added a bunch of phpdoc + * added a sandbox tag in the sandbox extension + * changed the date filter to support any date format supported by DateTime + * added strict_variable setting to throw an exception when an invalid variable is used in a template (disabled by default) + * added the lexer, parser, and compiler as arguments to the Twig_Environment constructor + * changed the cache option to only accepts an explicit path to a cache directory or false + * added a way to add token parsers, filters, and visitors without creating an extension + * added three interfaces: Twig_NodeInterface, Twig_TokenParserInterface, and Twig_FilterInterface + * changed the generated code to match the new coding standards + * fixed sandbox mode (__toString() method check was not enforced if called implicitly from a simple statement like {{ article }}) + * added an exception when a child template has a non-empty body (as it is always ignored when rendering) + +* 0.9.6 (2010-05-12) + + * fixed variables defined outside a loop and for which the value changes in a for loop + * fixed the test suite for PHP 5.2 and older versions of PHPUnit + * added support for __call() in expression resolution + * fixed node visiting for macros (macros are now visited by visitors as any other node) + * fixed nested block definitions with a parent call (rarely useful but nonetheless supported now) + * added the cycle filter + * fixed the Lexer when mbstring.func_overload is used with an mbstring.internal_encoding different from ASCII + * added a long-syntax for the set tag ({% set foo %}...{% endset %}) + * unit tests are now powered by PHPUnit + * added support for gettext via the `i18n` extension + * fixed twig_capitalize_string_filter() and fixed twig_length_filter() when used with UTF-8 values + * added a more useful exception if an if tag is not closed properly + * added support for escaping strategy in the autoescape tag + * fixed lexer when a template has a big chunk of text between/in a block + +* 0.9.5 (2010-01-20) + +As for any new release, don't forget to remove all cached templates after +upgrading. + +If you have defined custom filters, you MUST upgrade them for this release. To +upgrade, replace "array" with "new Twig_Filter_Function", and replace the +environment constant by the "needs_environment" option: + + // before + 'even' => array('twig_is_even_filter', false), + 'escape' => array('twig_escape_filter', true), + + // after + 'even' => new Twig_Filter_Function('twig_is_even_filter'), + 'escape' => new Twig_Filter_Function('twig_escape_filter', array('needs_environment' => true)), + +If you have created NodeTransformer classes, you will need to upgrade them to +the new interface (please note that the interface is not yet considered +stable). + + * fixed list nodes that did not extend the Twig_NodeListInterface + * added the "without loop" option to the for tag (it disables the generation of the loop variable) + * refactored node transformers to node visitors + * fixed automatic-escaping for blocks + * added a way to specify variables to pass to an included template + * changed the automatic-escaping rules to be more sensible and more configurable in custom filters (the documentation lists all the rules) + * improved the filter system to allow object methods to be used as filters + * changed the Array and String loaders to actually make use of the cache mechanism + * included the default filter function definitions in the extension class files directly (Core, Escaper) + * added the // operator (like the floor() PHP function) + * added the .. operator (as a syntactic sugar for the range filter when the step is 1) + * added the in operator (as a syntactic sugar for the in filter) + * added the following filters in the Core extension: in, range + * added support for arrays (same behavior as in PHP, a mix between lists and dictionaries, arrays and hashes) + * enhanced some error messages to provide better feedback in case of parsing errors + +* 0.9.4 (2009-12-02) + +If you have custom loaders, you MUST upgrade them for this release: The +Twig_Loader base class has been removed, and the Twig_LoaderInterface has also +been changed (see the source code for more information or the documentation). + + * added support for DateTime instances for the date filter + * fixed loop.last when the array only has one item + * made it possible to insert newlines in tag and variable blocks + * fixed a bug when a literal '\n' were present in a template text + * fixed bug when the filename of a template contains */ + * refactored loaders + +* 0.9.3 (2009-11-11) + +This release is NOT backward compatible with the previous releases. + + The loaders do not take the cache and autoReload arguments anymore. Instead, + the Twig_Environment class has two new options: cache and auto_reload. + Upgrading your code means changing this kind of code: + + $loader = new Twig_Loader_Filesystem('/path/to/templates', '/path/to/compilation_cache', true); + $twig = new Twig_Environment($loader); + + to something like this: + + $loader = new Twig_Loader_Filesystem('/path/to/templates'); + $twig = new Twig_Environment($loader, array( + 'cache' => '/path/to/compilation_cache', + 'auto_reload' => true, + )); + + * deprecated the "items" filter as it is not needed anymore + * made cache and auto_reload options of Twig_Environment instead of arguments of Twig_Loader + * optimized template loading speed + * removed output when an error occurs in a template and render() is used + * made major speed improvements for loops (up to 300% on even the smallest loops) + * added properties as part of the sandbox mode + * added public properties support (obj.item can now be the item property on the obj object) + * extended set tag to support expression as value ({% set foo as 'foo' ~ 'bar' %} ) + * fixed bug when \ was used in HTML + +* 0.9.2 (2009-10-29) + + * made some speed optimizations + * changed the cache extension to .php + * added a js escaping strategy + * added support for short block tag + * changed the filter tag to allow chained filters + * made lexer more flexible as you can now change the default delimiters + * added set tag + * changed default directory permission when cache dir does not exist (more secure) + * added macro support + * changed filters first optional argument to be a Twig_Environment instance instead of a Twig_Template instance + * made Twig_Autoloader::autoload() a static method + * avoid writing template file if an error occurs + * added $ escaping when outputting raw strings + * enhanced some error messages to ease debugging + * fixed empty cache files when the template contains an error + +* 0.9.1 (2009-10-14) + + * fixed a bug in PHP 5.2.6 + * fixed numbers with one than one decimal + * added support for method calls with arguments ({{ foo.bar('a', 43) }}) + * made small speed optimizations + * made minor tweaks to allow better extensibility and flexibility + +* 0.9.0 (2009-10-12) + + * Initial release diff --git a/vendor/twig/twig/LICENSE b/vendor/twig/twig/LICENSE new file mode 100644 index 0000000..e401cb9 --- /dev/null +++ b/vendor/twig/twig/LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2009-2018 by the Twig Team. + +Some rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * The names of the contributors may not be used to endorse or + promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/twig/twig/README.rst b/vendor/twig/twig/README.rst new file mode 100644 index 0000000..f33ea33 --- /dev/null +++ b/vendor/twig/twig/README.rst @@ -0,0 +1,15 @@ +Twig, the flexible, fast, and secure template language for PHP +============================================================== + +Twig is a template language for PHP, released under the new BSD license (code +and documentation). + +Twig uses a syntax similar to the Django and Jinja template languages which +inspired the Twig runtime environment. + +More Information +---------------- + +Read the `documentation`_ for more information. + +.. _documentation: https://twig.symfony.com/documentation diff --git a/vendor/twig/twig/composer.json b/vendor/twig/twig/composer.json new file mode 100644 index 0000000..d1256eb --- /dev/null +++ b/vendor/twig/twig/composer.json @@ -0,0 +1,51 @@ +{ + "name": "twig/twig", + "type": "library", + "description": "Twig, the flexible, fast, and secure template language for PHP", + "keywords": ["templating"], + "homepage": "https://twig.symfony.com", + "license": "BSD-3-Clause", + "authors": [ + { + "name": "Fabien Potencier", + "email": "fabien@symfony.com", + "homepage": "http://fabien.potencier.org", + "role": "Lead Developer" + }, + { + "name": "Twig Team", + "homepage": "https://twig.symfony.com/contributors", + "role": "Contributors" + }, + { + "name": "Armin Ronacher", + "email": "armin.ronacher@active-4.com", + "role": "Project Founder" + } + ], + "support": { + "forum": "https://groups.google.com/forum/#!forum/twig-users" + }, + "require": { + "php": ">=5.3.3", + "symfony/polyfill-ctype": "^1.8" + }, + "require-dev": { + "symfony/phpunit-bridge": "^3.4.19|^4.1.8", + "symfony/debug": "^2.7", + "psr/container": "^1.0" + }, + "autoload": { + "psr-0" : { + "Twig_" : "lib/" + }, + "psr-4" : { + "Twig\\" : "src/" + } + }, + "extra": { + "branch-alias": { + "dev-master": "1.36-dev" + } + } +} diff --git a/vendor/twig/twig/doc/advanced.rst b/vendor/twig/twig/doc/advanced.rst new file mode 100644 index 0000000..75f69f6 --- /dev/null +++ b/vendor/twig/twig/doc/advanced.rst @@ -0,0 +1,965 @@ +Extending Twig +============== + +.. caution:: + + This section describes how to extend Twig as of **Twig 1.12**. If you are + using an older version, read the :doc:`legacy` chapter + instead. + +Twig can be extended in many ways; you can add extra tags, filters, tests, +operators, global variables, and functions. You can even extend the parser +itself with node visitors. + +.. note:: + + The first section of this chapter describes how to extend Twig easily. If + you want to reuse your changes in different projects or if you want to + share them with others, you should then create an extension as described + in the following section. + +.. caution:: + + When extending Twig without creating an extension, Twig won't be able to + recompile your templates when the PHP code is updated. To see your changes + in real-time, either disable template caching or package your code into an + extension (see the next section of this chapter). + +Before extending Twig, you must understand the differences between all the +different possible extension points and when to use them. + +First, remember that Twig has two main language constructs: + +* ``{{ }}``: used to print the result of an expression evaluation; + +* ``{% %}``: used to execute statements. + +To understand why Twig exposes so many extension points, let's see how to +implement a *Lorem ipsum* generator (it needs to know the number of words to +generate). + +You can use a ``lipsum`` *tag*: + +.. code-block:: jinja + + {% lipsum 40 %} + +That works, but using a tag for ``lipsum`` is not a good idea for at least +three main reasons: + +* ``lipsum`` is not a language construct; +* The tag outputs something; +* The tag is not flexible as you cannot use it in an expression: + + .. code-block:: jinja + + {{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }} + +In fact, you rarely need to create tags; and that's good news because tags are +the most complex extension point of Twig. + +Now, let's use a ``lipsum`` *filter*: + +.. code-block:: jinja + + {{ 40|lipsum }} + +Again, it works, but it looks weird. A filter transforms the passed value to +something else but here we use the value to indicate the number of words to +generate (so, ``40`` is an argument of the filter, not the value we want to +transform). + +Next, let's use a ``lipsum`` *function*: + +.. code-block:: jinja + + {{ lipsum(40) }} + +Here we go. For this specific example, the creation of a function is the +extension point to use. And you can use it anywhere an expression is accepted: + +.. code-block:: jinja + + {{ 'some text' ~ lipsum(40) ~ 'some more text' }} + + {% set lipsum = lipsum(40) %} + +Last but not the least, you can also use a *global* object with a method able +to generate lorem ipsum text: + +.. code-block:: jinja + + {{ text.lipsum(40) }} + +As a rule of thumb, use functions for frequently used features and global +objects for everything else. + +Keep in mind the following when you want to extend Twig: + +========== ========================== ========== ========================= +What? Implementation difficulty? How often? When? +========== ========================== ========== ========================= +*macro* trivial frequent Content generation +*global* trivial frequent Helper object +*function* trivial frequent Content generation +*filter* trivial frequent Value transformation +*tag* complex rare DSL language construct +*test* trivial rare Boolean decision +*operator* trivial rare Values transformation +========== ========================== ========== ========================= + +Globals +------- + +A global variable is like any other template variable, except that it's +available in all templates and macros:: + + $twig = new Twig_Environment($loader); + $twig->addGlobal('text', new Text()); + +You can then use the ``text`` variable anywhere in a template: + +.. code-block:: jinja + + {{ text.lipsum(40) }} + +Filters +------- + +Creating a filter is as simple as associating a name with a PHP callable:: + + // an anonymous function + $filter = new Twig_SimpleFilter('rot13', function ($string) { + return str_rot13($string); + }); + + // or a simple PHP function + $filter = new Twig_SimpleFilter('rot13', 'str_rot13'); + + // or a class static method + $filter = new Twig_SimpleFilter('rot13', array('SomeClass', 'rot13Filter')); + $filter = new Twig_SimpleFilter('rot13', 'SomeClass::rot13Filter'); + + // or a class method + $filter = new Twig_SimpleFilter('rot13', array($this, 'rot13Filter')); + // the one below needs a runtime implementation (see below for more information) + $filter = new Twig_SimpleFilter('rot13', array('SomeClass', 'rot13Filter')); + +The first argument passed to the ``Twig_SimpleFilter`` constructor is the name +of the filter you will use in templates and the second one is the PHP callable +to associate with it. + +Then, add the filter to your Twig environment:: + + $twig = new Twig_Environment($loader); + $twig->addFilter($filter); + +And here is how to use it in a template: + +.. code-block:: jinja + + {{ 'Twig'|rot13 }} + + {# will output Gjvt #} + +When called by Twig, the PHP callable receives the left side of the filter +(before the pipe ``|``) as the first argument and the extra arguments passed +to the filter (within parentheses ``()``) as extra arguments. + +For instance, the following code: + +.. code-block:: jinja + + {{ 'TWIG'|lower }} + {{ now|date('d/m/Y') }} + +is compiled to something like the following:: + + + + +The ``Twig_SimpleFilter`` class takes an array of options as its last +argument:: + + $filter = new Twig_SimpleFilter('rot13', 'str_rot13', $options); + +Environment-aware Filters +~~~~~~~~~~~~~~~~~~~~~~~~~ + +If you want to access the current environment instance in your filter, set the +``needs_environment`` option to ``true``; Twig will pass the current +environment as the first argument to the filter call:: + + $filter = new Twig_SimpleFilter('rot13', function (Twig_Environment $env, $string) { + // get the current charset for instance + $charset = $env->getCharset(); + + return str_rot13($string); + }, array('needs_environment' => true)); + +Context-aware Filters +~~~~~~~~~~~~~~~~~~~~~ + +If you want to access the current context in your filter, set the +``needs_context`` option to ``true``; Twig will pass the current context as +the first argument to the filter call (or the second one if +``needs_environment`` is also set to ``true``):: + + $filter = new Twig_SimpleFilter('rot13', function ($context, $string) { + // ... + }, array('needs_context' => true)); + + $filter = new Twig_SimpleFilter('rot13', function (Twig_Environment $env, $context, $string) { + // ... + }, array('needs_context' => true, 'needs_environment' => true)); + +Automatic Escaping +~~~~~~~~~~~~~~~~~~ + +If automatic escaping is enabled, the output of the filter may be escaped +before printing. If your filter acts as an escaper (or explicitly outputs HTML +or JavaScript code), you will want the raw output to be printed. In such a +case, set the ``is_safe`` option:: + + $filter = new Twig_SimpleFilter('nl2br', 'nl2br', array('is_safe' => array('html'))); + +Some filters may need to work on input that is already escaped or safe, for +example when adding (safe) HTML tags to originally unsafe output. In such a +case, set the ``pre_escape`` option to escape the input data before it is run +through your filter:: + + $filter = new Twig_SimpleFilter('somefilter', 'somefilter', array('pre_escape' => 'html', 'is_safe' => array('html'))); + +Variadic Filters +~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.19 + Support for variadic filters was added in Twig 1.19. + +When a filter should accept an arbitrary number of arguments, set the +``is_variadic`` option to ``true``; Twig will pass the extra arguments as the +last argument to the filter call as an array:: + + $filter = new Twig_SimpleFilter('thumbnail', function ($file, array $options = array()) { + // ... + }, array('is_variadic' => true)); + +Be warned that named arguments passed to a variadic filter cannot be checked +for validity as they will automatically end up in the option array. + +Dynamic Filters +~~~~~~~~~~~~~~~ + +A filter name containing the special ``*`` character is a dynamic filter as +the ``*`` can be any string:: + + $filter = new Twig_SimpleFilter('*_path', function ($name, $arguments) { + // ... + }); + +The following filters will be matched by the above defined dynamic filter: + +* ``product_path`` +* ``category_path`` + +A dynamic filter can define more than one dynamic parts:: + + $filter = new Twig_SimpleFilter('*_path_*', function ($name, $suffix, $arguments) { + // ... + }); + +The filter will receive all dynamic part values before the normal filter +arguments, but after the environment and the context. For instance, a call to +``'foo'|a_path_b()`` will result in the following arguments to be passed to +the filter: ``('a', 'b', 'foo')``. + +Deprecated Filters +~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.21 + Support for deprecated filters was added in Twig 1.21. + +You can mark a filter as being deprecated by setting the ``deprecated`` option +to ``true``. You can also give an alternative filter that replaces the +deprecated one when that makes sense:: + + $filter = new Twig_SimpleFilter('obsolete', function () { + // ... + }, array('deprecated' => true, 'alternative' => 'new_one')); + +When a filter is deprecated, Twig emits a deprecation notice when compiling a +template using it. See :ref:`deprecation-notices` for more information. + +Functions +--------- + +Functions are defined in the exact same way as filters, but you need to create +an instance of ``Twig_SimpleFunction``:: + + $twig = new Twig_Environment($loader); + $function = new Twig_SimpleFunction('function_name', function () { + // ... + }); + $twig->addFunction($function); + +Functions support the same features as filters, except for the ``pre_escape`` +and ``preserves_safety`` options. + +Tests +----- + +Tests are defined in the exact same way as filters and functions, but you need +to create an instance of ``Twig_SimpleTest``:: + + $twig = new Twig_Environment($loader); + $test = new Twig_SimpleTest('test_name', function () { + // ... + }); + $twig->addTest($test); + +Tests allow you to create custom application specific logic for evaluating +boolean conditions. As a simple example, let's create a Twig test that checks if +objects are 'red':: + + $twig = new Twig_Environment($loader); + $test = new Twig_SimpleTest('red', function ($value) { + if (isset($value->color) && $value->color == 'red') { + return true; + } + if (isset($value->paint) && $value->paint == 'red') { + return true; + } + return false; + }); + $twig->addTest($test); + +Test functions should always return true/false. + +When creating tests you can use the ``node_class`` option to provide custom test +compilation. This is useful if your test can be compiled into PHP primitives. +This is used by many of the tests built into Twig:: + + $twig = new Twig_Environment($loader); + $test = new Twig_SimpleTest( + 'odd', + null, + array('node_class' => 'Twig_Node_Expression_Test_Odd')); + $twig->addTest($test); + + class Twig_Node_Expression_Test_Odd extends Twig_Node_Expression_Test + { + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('(') + ->subcompile($this->getNode('node')) + ->raw(' % 2 == 1') + ->raw(')') + ; + } + } + +The above example shows how you can create tests that use a node class. The +node class has access to one sub-node called 'node'. This sub-node contains the +value that is being tested. When the ``odd`` filter is used in code such as: + +.. code-block:: jinja + + {% if my_value is odd %} + +The ``node`` sub-node will contain an expression of ``my_value``. Node-based +tests also have access to the ``arguments`` node. This node will contain the +various other arguments that have been provided to your test. + +.. versionadded:: 1.36 + Dynamic tests support was added in Twig 1.36. + +If you want to pass a variable number of positional or named arguments to the +test, set the ``is_variadic`` option to ``true``. Tests support dynamic +names (see dynamic filters and functions for the syntax). + +Tags +---- + +One of the most exciting features of a template engine like Twig is the +possibility to define new language constructs. This is also the most complex +feature as you need to understand how Twig's internals work. + +Let's create a simple ``set`` tag that allows the definition of simple +variables from within a template. The tag can be used like follows: + +.. code-block:: jinja + + {% set name = "value" %} + + {{ name }} + + {# should output value #} + +.. note:: + + The ``set`` tag is part of the Core extension and as such is always + available. The built-in version is slightly more powerful and supports + multiple assignments by default (cf. the template designers chapter for + more information). + +Three steps are needed to define a new tag: + +* Defining a Token Parser class (responsible for parsing the template code); + +* Defining a Node class (responsible for converting the parsed code to PHP); + +* Registering the tag. + +Registering a new tag +~~~~~~~~~~~~~~~~~~~~~ + +Adding a tag is as simple as calling the ``addTokenParser`` method on the +``Twig_Environment`` instance:: + + $twig = new Twig_Environment($loader); + $twig->addTokenParser(new Project_Set_TokenParser()); + +Defining a Token Parser +~~~~~~~~~~~~~~~~~~~~~~~ + +Now, let's see the actual code of this class:: + + class Project_Set_TokenParser extends Twig_TokenParser + { + public function parse(Twig_Token $token) + { + $parser = $this->parser; + $stream = $parser->getStream(); + + $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + $stream->expect(Twig_Token::OPERATOR_TYPE, '='); + $value = $parser->getExpressionParser()->parseExpression(); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + return new Project_Set_Node($name, $value, $token->getLine(), $this->getTag()); + } + + public function getTag() + { + return 'set'; + } + } + +The ``getTag()`` method must return the tag we want to parse, here ``set``. + +The ``parse()`` method is invoked whenever the parser encounters a ``set`` +tag. It should return a ``Twig_Node`` instance that represents the node (the +``Project_Set_Node`` calls creating is explained in the next section). + +The parsing process is simplified thanks to a bunch of methods you can call +from the token stream (``$this->parser->getStream()``): + +* ``getCurrent()``: Gets the current token in the stream. + +* ``next()``: Moves to the next token in the stream, *but returns the old one*. + +* ``test($type)``, ``test($value)`` or ``test($type, $value)``: Determines whether + the current token is of a particular type or value (or both). The value may be an + array of several possible values. + +* ``expect($type[, $value[, $message]])``: If the current token isn't of the given + type/value a syntax error is thrown. Otherwise, if the type and value are correct, + the token is returned and the stream moves to the next token. + +* ``look()``: Looks at the next token without consuming it. + +Parsing expressions is done by calling the ``parseExpression()`` like we did for +the ``set`` tag. + +.. tip:: + + Reading the existing ``TokenParser`` classes is the best way to learn all + the nitty-gritty details of the parsing process. + +Defining a Node +~~~~~~~~~~~~~~~ + +The ``Project_Set_Node`` class itself is rather simple:: + + class Project_Set_Node extends Twig_Node + { + public function __construct($name, Twig_Node_Expression $value, $line, $tag = null) + { + parent::__construct(array('value' => $value), array('name' => $name), $line, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('$context[\''.$this->getAttribute('name').'\'] = ') + ->subcompile($this->getNode('value')) + ->raw(";\n") + ; + } + } + +The compiler implements a fluid interface and provides methods that helps the +developer generate beautiful and readable PHP code: + +* ``subcompile()``: Compiles a node. + +* ``raw()``: Writes the given string as is. + +* ``write()``: Writes the given string by adding indentation at the beginning + of each line. + +* ``string()``: Writes a quoted string. + +* ``repr()``: Writes a PHP representation of a given value (see + ``Twig_Node_For`` for a usage example). + +* ``addDebugInfo()``: Adds the line of the original template file related to + the current node as a comment. + +* ``indent()``: Indents the generated code (see ``Twig_Node_Block`` for a + usage example). + +* ``outdent()``: Outdents the generated code (see ``Twig_Node_Block`` for a + usage example). + +.. _creating_extensions: + +Creating an Extension +--------------------- + +The main motivation for writing an extension is to move often used code into a +reusable class like adding support for internationalization. An extension can +define tags, filters, tests, operators, global variables, functions, and node +visitors. + +Most of the time, it is useful to create a single extension for your project, +to host all the specific tags and filters you want to add to Twig. + +.. tip:: + + When packaging your code into an extension, Twig is smart enough to + recompile your templates whenever you make a change to it (when + ``auto_reload`` is enabled). + +.. note:: + + Before writing your own extensions, have a look at the Twig official + extension repository: https://github.com/twigphp/Twig-extensions. + +An extension is a class that implements the following interface:: + + interface Twig_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 + */ + function initRuntime(Twig_Environment $environment); + + /** + * Returns the token parser instances to add to the existing list. + * + * @return (Twig_TokenParserInterface|Twig_TokenParserBrokerInterface)[] + */ + function getTokenParsers(); + + /** + * Returns the node visitor instances to add to the existing list. + * + * @return Twig_NodeVisitorInterface[] + */ + function getNodeVisitors(); + + /** + * Returns a list of filters to add to the existing list. + * + * @return Twig_SimpleFilter[] + */ + function getFilters(); + + /** + * Returns a list of tests to add to the existing list. + * + * @return Twig_SimpleTest[] + */ + function getTests(); + + /** + * Returns a list of functions to add to the existing list. + * + * @return Twig_SimpleFunction[] + */ + 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 + */ + 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 + */ + 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 + */ + function getName(); + } + +To keep your extension class clean and lean, inherit from the built-in +``Twig_Extension`` class instead of implementing the interface as it provides +empty implementations for all methods: + + class Project_Twig_Extension extends Twig_Extension + { + } + +Of course, this extension does nothing for now. We will customize it in the +next sections. + +.. note:: + + Prior to Twig 1.26, you must implement the ``getName()`` method which must + return a unique identifier for the extension. + +Twig does not care where you save your extension on the filesystem, as all +extensions must be registered explicitly to be available in your templates. + +You can register an extension by using the ``addExtension()`` method on your +main ``Environment`` object:: + + $twig = new Twig_Environment($loader); + $twig->addExtension(new Project_Twig_Extension()); + +.. tip:: + + The Twig core extensions are great examples of how extensions work. + +Globals +~~~~~~~ + +Global variables can be registered in an extension via the ``getGlobals()`` +method:: + + class Project_Twig_Extension extends Twig_Extension implements Twig_Extension_GlobalsInterface + { + public function getGlobals() + { + return array( + 'text' => new Text(), + ); + } + + // ... + } + +Functions +~~~~~~~~~ + +Functions can be registered in an extension via the ``getFunctions()`` +method:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getFunctions() + { + return array( + new Twig_SimpleFunction('lipsum', 'generate_lipsum'), + ); + } + + // ... + } + +Filters +~~~~~~~ + +To add a filter to an extension, you need to override the ``getFilters()`` +method. This method must return an array of filters to add to the Twig +environment:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getFilters() + { + return array( + new Twig_SimpleFilter('rot13', 'str_rot13'), + ); + } + + // ... + } + +Tags +~~~~ + +Adding a tag in an extension can be done by overriding the +``getTokenParsers()`` method. This method must return an array of tags to add +to the Twig environment:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getTokenParsers() + { + return array(new Project_Set_TokenParser()); + } + + // ... + } + +In the above code, we have added a single new tag, defined by the +``Project_Set_TokenParser`` class. The ``Project_Set_TokenParser`` class is +responsible for parsing the tag and compiling it to PHP. + +Operators +~~~~~~~~~ + +The ``getOperators()`` methods lets you add new operators. Here is how to add +``!``, ``||``, and ``&&`` operators:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getOperators() + { + return array( + array( + '!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'), + ), + array( + '||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + ), + ); + } + + // ... + } + +Tests +~~~~~ + +The ``getTests()`` method lets you add new test functions:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getTests() + { + return array( + new Twig_SimpleTest('even', 'twig_test_even'), + ); + } + + // ... + } + +Definition vs Runtime +~~~~~~~~~~~~~~~~~~~~~ + +Twig filters, functions, and tests runtime implementations can be defined as +any valid PHP callable: + +* **functions/static methods**: Simple to implement and fast (used by all Twig + core extensions); but it is hard for the runtime to depend on external + objects; + +* **closures**: Simple to implement; + +* **object methods**: More flexible and required if your runtime code depends + on external objects. + +The simplest way to use methods is to define them on the extension itself:: + + class Project_Twig_Extension extends Twig_Extension + { + private $rot13Provider; + + public function __construct($rot13Provider) + { + $this->rot13Provider = $rot13Provider; + } + + public function getFunctions() + { + return array( + new Twig_SimpleFunction('rot13', array($this, 'rot13')), + ); + } + + public function rot13($value) + { + return $this->rot13Provider->rot13($value); + } + } + +This is very convenient but not recommended as it makes template compilation +depend on runtime dependencies even if they are not needed (think for instance +as a dependency that connects to a database engine). + +As of Twig 1.26, you can easily decouple the extension definitions from their +runtime implementations by registering a ``Twig_RuntimeLoaderInterface`` +instance on the environment that knows how to instantiate such runtime classes +(runtime classes must be autoload-able):: + + class RuntimeLoader implements Twig_RuntimeLoaderInterface + { + public function load($class) + { + // implement the logic to create an instance of $class + // and inject its dependencies + // most of the time, it means using your dependency injection container + if ('Project_Twig_RuntimeExtension' === $class) { + return new $class(new Rot13Provider()); + } else { + // ... + } + } + } + + $twig->addRuntimeLoader(new RuntimeLoader()); + +.. note:: + + As of Twig 1.32, Twig comes with a PSR-11 compatible runtime loader + (``Twig_ContainerRuntimeLoader``) that works on PHP 5.3+. + +It is now possible to move the runtime logic to a new +``Project_Twig_RuntimeExtension`` class and use it directly in the extension:: + + class Project_Twig_RuntimeExtension + { + private $rot13Provider; + + public function __construct($rot13Provider) + { + $this->rot13Provider = $rot13Provider; + } + + public function rot13($value) + { + return $this->rot13Provider->rot13($value); + } + } + + class Project_Twig_Extension extends Twig_Extension + { + public function getFunctions() + { + return array( + new Twig_SimpleFunction('rot13', array('Project_Twig_RuntimeExtension', 'rot13')), + // or + new Twig_SimpleFunction('rot13', 'Project_Twig_RuntimeExtension::rot13'), + ); + } + } + +Overloading +----------- + +To overload an already defined filter, test, operator, global variable, or +function, re-define it in an extension and register it **as late as +possible** (order matters):: + + class MyCoreExtension extends Twig_Extension + { + public function getFilters() + { + return array( + new Twig_SimpleFilter('date', array($this, 'dateFilter')), + ); + } + + public function dateFilter($timestamp, $format = 'F j, Y H:i') + { + // do something different from the built-in date filter + } + } + + $twig = new Twig_Environment($loader); + $twig->addExtension(new MyCoreExtension()); + +Here, we have overloaded the built-in ``date`` filter with a custom one. + +If you do the same on the ``Twig_Environment`` itself, beware that it takes +precedence over any other registered extensions:: + + $twig = new Twig_Environment($loader); + $twig->addFilter(new Twig_SimpleFilter('date', function ($timestamp, $format = 'F j, Y H:i') { + // do something different from the built-in date filter + })); + // the date filter will come from the above registration, not + // from the registered extension below + $twig->addExtension(new MyCoreExtension()); + +.. caution:: + + Note that overloading the built-in Twig elements is not recommended as it + might be confusing. + +Testing an Extension +-------------------- + +Functional Tests +~~~~~~~~~~~~~~~~ + +You can create functional tests for extensions simply by creating the +following file structure in your test directory:: + + Fixtures/ + filters/ + foo.test + bar.test + functions/ + foo.test + bar.test + tags/ + foo.test + bar.test + IntegrationTest.php + +The ``IntegrationTest.php`` file should look like this:: + + class Project_Tests_IntegrationTest extends Twig_Test_IntegrationTestCase + { + public function getExtensions() + { + return array( + new Project_Twig_Extension1(), + new Project_Twig_Extension2(), + ); + } + + public function getFixturesDir() + { + return dirname(__FILE__).'/Fixtures/'; + } + } + +Fixtures examples can be found within the Twig repository +`tests/Twig/Fixtures`_ directory. + +Node Tests +~~~~~~~~~~ + +Testing the node visitors can be complex, so extend your test cases from +``Twig_Test_NodeTestCase``. Examples can be found in the Twig repository +`tests/Twig/Node`_ directory. + +.. _`rot13`: https://secure.php.net/manual/en/function.str-rot13.php +.. _`tests/Twig/Fixtures`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Fixtures +.. _`tests/Twig/Node`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node diff --git a/vendor/twig/twig/doc/advanced_legacy.rst b/vendor/twig/twig/doc/advanced_legacy.rst new file mode 100644 index 0000000..857fe4f --- /dev/null +++ b/vendor/twig/twig/doc/advanced_legacy.rst @@ -0,0 +1,885 @@ +Extending Twig +============== + +.. caution:: + + This section describes how to extends Twig for versions **older than + 1.12**. If you are using a newer version, read the :doc:`newer` + chapter instead. + +Twig can be extended in many ways; you can add extra tags, filters, tests, +operators, global variables, and functions. You can even extend the parser +itself with node visitors. + +.. note:: + + The first section of this chapter describes how to extend Twig easily. If + you want to reuse your changes in different projects or if you want to + share them with others, you should then create an extension as described + in the following section. + +.. caution:: + + When extending Twig by calling methods on the Twig environment instance, + Twig won't be able to recompile your templates when the PHP code is + updated. To see your changes in real-time, either disable template caching + or package your code into an extension (see the next section of this + chapter). + +Before extending Twig, you must understand the differences between all the +different possible extension points and when to use them. + +First, remember that Twig has two main language constructs: + +* ``{{ }}``: used to print the result of an expression evaluation; + +* ``{% %}``: used to execute statements. + +To understand why Twig exposes so many extension points, let's see how to +implement a *Lorem ipsum* generator (it needs to know the number of words to +generate). + +You can use a ``lipsum`` *tag*: + +.. code-block:: jinja + + {% lipsum 40 %} + +That works, but using a tag for ``lipsum`` is not a good idea for at least +three main reasons: + +* ``lipsum`` is not a language construct; +* The tag outputs something; +* The tag is not flexible as you cannot use it in an expression: + + .. code-block:: jinja + + {{ 'some text' ~ {% lipsum 40 %} ~ 'some more text' }} + +In fact, you rarely need to create tags; and that's good news because tags are +the most complex extension point of Twig. + +Now, let's use a ``lipsum`` *filter*: + +.. code-block:: jinja + + {{ 40|lipsum }} + +Again, it works, but it looks weird. A filter transforms the passed value to +something else but here we use the value to indicate the number of words to +generate (so, ``40`` is an argument of the filter, not the value we want to +transform). + +Next, let's use a ``lipsum`` *function*: + +.. code-block:: jinja + + {{ lipsum(40) }} + +Here we go. For this specific example, the creation of a function is the +extension point to use. And you can use it anywhere an expression is accepted: + +.. code-block:: jinja + + {{ 'some text' ~ ipsum(40) ~ 'some more text' }} + + {% set ipsum = ipsum(40) %} + +Last but not the least, you can also use a *global* object with a method able +to generate lorem ipsum text: + +.. code-block:: jinja + + {{ text.lipsum(40) }} + +As a rule of thumb, use functions for frequently used features and global +objects for everything else. + +Keep in mind the following when you want to extend Twig: + +========== ========================== ========== ========================= +What? Implementation difficulty? How often? When? +========== ========================== ========== ========================= +*macro* trivial frequent Content generation +*global* trivial frequent Helper object +*function* trivial frequent Content generation +*filter* trivial frequent Value transformation +*tag* complex rare DSL language construct +*test* trivial rare Boolean decision +*operator* trivial rare Values transformation +========== ========================== ========== ========================= + +Globals +------- + +A global variable is like any other template variable, except that it's +available in all templates and macros:: + + $twig = new Twig_Environment($loader); + $twig->addGlobal('text', new Text()); + +You can then use the ``text`` variable anywhere in a template: + +.. code-block:: jinja + + {{ text.lipsum(40) }} + +Filters +------- + +A filter is a regular PHP function or an object method that takes the left +side of the filter (before the pipe ``|``) as first argument and the extra +arguments passed to the filter (within parentheses ``()``) as extra arguments. + +Defining a filter is as easy as associating the filter name with a PHP +callable. For instance, let's say you have the following code in a template: + +.. code-block:: jinja + + {{ 'TWIG'|lower }} + +When compiling this template to PHP, Twig looks for the PHP callable +associated with the ``lower`` filter. The ``lower`` filter is a built-in Twig +filter, and it is simply mapped to the PHP ``strtolower()`` function. After +compilation, the generated PHP code is roughly equivalent to: + +.. code-block:: html+php + + + +As you can see, the ``'TWIG'`` string is passed as a first argument to the PHP +function. + +A filter can also take extra arguments like in the following example: + +.. code-block:: jinja + + {{ now|date('d/m/Y') }} + +In this case, the extra arguments are passed to the function after the main +argument, and the compiled code is equivalent to: + +.. code-block:: html+php + + + +Let's see how to create a new filter. + +In this section, we will create a ``rot13`` filter, which should return the +`rot13`_ transformation of a string. Here is an example of its usage and the +expected output: + +.. code-block:: jinja + + {{ "Twig"|rot13 }} + + {# should displays Gjvt #} + +Adding a filter is as simple as calling the ``addFilter()`` method on the +``Twig_Environment`` instance:: + + $twig = new Twig_Environment($loader); + $twig->addFilter('rot13', new Twig_Filter_Function('str_rot13')); + +The second argument of ``addFilter()`` is an instance of ``Twig_Filter``. +Here, we use ``Twig_Filter_Function`` as the filter is a PHP function. The +first argument passed to the ``Twig_Filter_Function`` constructor is the name +of the PHP function to call, here ``str_rot13``, a native PHP function. + +Let's say I now want to be able to add a prefix before the converted string: + +.. code-block:: jinja + + {{ "Twig"|rot13('prefix_') }} + + {# should displays prefix_Gjvt #} + +As the PHP ``str_rot13()`` function does not support this requirement, let's +create a new PHP function:: + + function project_compute_rot13($string, $prefix = '') + { + return $prefix.str_rot13($string); + } + +As you can see, the ``prefix`` argument of the filter is passed as an extra +argument to the ``project_compute_rot13()`` function. + +Adding this filter is as easy as before:: + + $twig->addFilter('rot13', new Twig_Filter_Function('project_compute_rot13')); + +For better encapsulation, a filter can also be defined as a static method of a +class. The ``Twig_Filter_Function`` class can also be used to register such +static methods as filters:: + + $twig->addFilter('rot13', new Twig_Filter_Function('SomeClass::rot13Filter')); + +.. tip:: + + In an extension, you can also define a filter as a static method of the + extension class. + +Environment aware Filters +~~~~~~~~~~~~~~~~~~~~~~~~~ + +The ``Twig_Filter`` classes take options as their last argument. For instance, +if you want access to the current environment instance in your filter, set the +``needs_environment`` option to ``true``:: + + $filter = new Twig_Filter_Function('str_rot13', array('needs_environment' => true)); + +Twig will then pass the current environment as the first argument to the +filter call:: + + function twig_compute_rot13(Twig_Environment $env, $string) + { + // get the current charset for instance + $charset = $env->getCharset(); + + return str_rot13($string); + } + +Automatic Escaping +~~~~~~~~~~~~~~~~~~ + +If automatic escaping is enabled, the output of the filter may be escaped +before printing. If your filter acts as an escaper (or explicitly outputs HTML +or JavaScript code), you will want the raw output to be printed. In such a +case, set the ``is_safe`` option:: + + $filter = new Twig_Filter_Function('nl2br', array('is_safe' => array('html'))); + +Some filters may need to work on input that is already escaped or safe, for +example when adding (safe) HTML tags to originally unsafe output. In such a +case, set the ``pre_escape`` option to escape the input data before it is run +through your filter:: + + $filter = new Twig_Filter_Function('somefilter', array('pre_escape' => 'html', 'is_safe' => array('html'))); + +Dynamic Filters +~~~~~~~~~~~~~~~ + +.. versionadded:: 1.5 + Dynamic filters support was added in Twig 1.5. + +A filter name containing the special ``*`` character is a dynamic filter as +the ``*`` can be any string:: + + $twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path')); + + function twig_path($name, $arguments) + { + // ... + } + +The following filters will be matched by the above defined dynamic filter: + +* ``product_path`` +* ``category_path`` + +A dynamic filter can define more than one dynamic parts:: + + $twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path')); + + function twig_path($name, $suffix, $arguments) + { + // ... + } + +The filter will receive all dynamic part values before the normal filters +arguments. For instance, a call to ``'foo'|a_path_b()`` will result in the +following PHP call: ``twig_path('a', 'b', 'foo')``. + +Functions +--------- + +A function is a regular PHP function or an object method that can be called from +templates. + +.. code-block:: jinja + + {{ constant("DATE_W3C") }} + +When compiling this template to PHP, Twig looks for the PHP callable +associated with the ``constant`` function. The ``constant`` function is a built-in Twig +function, and it is simply mapped to the PHP ``constant()`` function. After +compilation, the generated PHP code is roughly equivalent to: + +.. code-block:: html+php + + + +Adding a function is similar to adding a filter. This can be done by calling the +``addFunction()`` method on the ``Twig_Environment`` instance:: + + $twig = new Twig_Environment($loader); + $twig->addFunction('functionName', new Twig_Function_Function('someFunction')); + +You can also expose extension methods as functions in your templates:: + + // $this is an object that implements Twig_ExtensionInterface. + $twig = new Twig_Environment($loader); + $twig->addFunction('otherFunction', new Twig_Function_Method($this, 'someMethod')); + +Functions also support ``needs_environment`` and ``is_safe`` parameters. + +Dynamic Functions +~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.5 + Dynamic functions support was added in Twig 1.5. + +A function name containing the special ``*`` character is a dynamic function +as the ``*`` can be any string:: + + $twig->addFunction('*_path', new Twig_Function_Function('twig_path')); + + function twig_path($name, $arguments) + { + // ... + } + +The following functions will be matched by the above defined dynamic function: + +* ``product_path`` +* ``category_path`` + +A dynamic function can define more than one dynamic parts:: + + $twig->addFilter('*_path_*', new Twig_Filter_Function('twig_path')); + + function twig_path($name, $suffix, $arguments) + { + // ... + } + +The function will receive all dynamic part values before the normal functions +arguments. For instance, a call to ``a_path_b('foo')`` will result in the +following PHP call: ``twig_path('a', 'b', 'foo')``. + +Tags +---- + +One of the most exciting feature of a template engine like Twig is the +possibility to define new language constructs. This is also the most complex +feature as you need to understand how Twig's internals work. + +Let's create a simple ``set`` tag that allows the definition of simple +variables from within a template. The tag can be used like follows: + +.. code-block:: jinja + + {% set name = "value" %} + + {{ name }} + + {# should output value #} + +.. note:: + + The ``set`` tag is part of the Core extension and as such is always + available. The built-in version is slightly more powerful and supports + multiple assignments by default (cf. the template designers chapter for + more information). + +Three steps are needed to define a new tag: + +* Defining a Token Parser class (responsible for parsing the template code); + +* Defining a Node class (responsible for converting the parsed code to PHP); + +* Registering the tag. + +Registering a new tag +~~~~~~~~~~~~~~~~~~~~~ + +Adding a tag is as simple as calling the ``addTokenParser`` method on the +``Twig_Environment`` instance:: + + $twig = new Twig_Environment($loader); + $twig->addTokenParser(new Project_Set_TokenParser()); + +Defining a Token Parser +~~~~~~~~~~~~~~~~~~~~~~~ + +Now, let's see the actual code of this class:: + + class Project_Set_TokenParser extends Twig_TokenParser + { + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + $name = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue(); + $this->parser->getStream()->expect(Twig_Token::OPERATOR_TYPE, '='); + $value = $this->parser->getExpressionParser()->parseExpression(); + + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + return new Project_Set_Node($name, $value, $lineno, $this->getTag()); + } + + public function getTag() + { + return 'set'; + } + } + +The ``getTag()`` method must return the tag we want to parse, here ``set``. + +The ``parse()`` method is invoked whenever the parser encounters a ``set`` +tag. It should return a ``Twig_Node`` instance that represents the node (the +``Project_Set_Node`` calls creating is explained in the next section). + +The parsing process is simplified thanks to a bunch of methods you can call +from the token stream (``$this->parser->getStream()``): + +* ``getCurrent()``: Gets the current token in the stream. + +* ``next()``: Moves to the next token in the stream, *but returns the old one*. + +* ``test($type)``, ``test($value)`` or ``test($type, $value)``: Determines whether + the current token is of a particular type or value (or both). The value may be an + array of several possible values. + +* ``expect($type[, $value[, $message]])``: If the current token isn't of the given + type/value a syntax error is thrown. Otherwise, if the type and value are correct, + the token is returned and the stream moves to the next token. + +* ``look()``: Looks a the next token without consuming it. + +Parsing expressions is done by calling the ``parseExpression()`` like we did for +the ``set`` tag. + +.. tip:: + + Reading the existing ``TokenParser`` classes is the best way to learn all + the nitty-gritty details of the parsing process. + +Defining a Node +~~~~~~~~~~~~~~~ + +The ``Project_Set_Node`` class itself is rather simple:: + + class Project_Set_Node extends Twig_Node + { + public function __construct($name, Twig_Node_Expression $value, $lineno, $tag = null) + { + parent::__construct(array('value' => $value), array('name' => $name), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('$context[\''.$this->getAttribute('name').'\'] = ') + ->subcompile($this->getNode('value')) + ->raw(";\n") + ; + } + } + +The compiler implements a fluid interface and provides methods that helps the +developer generate beautiful and readable PHP code: + +* ``subcompile()``: Compiles a node. + +* ``raw()``: Writes the given string as is. + +* ``write()``: Writes the given string by adding indentation at the beginning + of each line. + +* ``string()``: Writes a quoted string. + +* ``repr()``: Writes a PHP representation of a given value (see + ``Twig_Node_For`` for a usage example). + +* ``addDebugInfo()``: Adds the line of the original template file related to + the current node as a comment. + +* ``indent()``: Indents the generated code (see ``Twig_Node_Block`` for a + usage example). + +* ``outdent()``: Outdents the generated code (see ``Twig_Node_Block`` for a + usage example). + +.. _creating_extensions: + +Creating an Extension +--------------------- + +The main motivation for writing an extension is to move often used code into a +reusable class like adding support for internationalization. An extension can +define tags, filters, tests, operators, global variables, functions, and node +visitors. + +Creating an extension also makes for a better separation of code that is +executed at compilation time and code needed at runtime. As such, it makes +your code faster. + +Most of the time, it is useful to create a single extension for your project, +to host all the specific tags and filters you want to add to Twig. + +.. tip:: + + When packaging your code into an extension, Twig is smart enough to + recompile your templates whenever you make a change to it (when the + ``auto_reload`` is enabled). + +.. note:: + + Before writing your own extensions, have a look at the Twig official + extension repository: https://github.com/twigphp/Twig-extensions. + +An extension is a class that implements the following interface:: + + interface Twig_ExtensionInterface + { + /** + * Initializes the runtime environment. + * + * This is where you can load some file that contains filter functions for instance. + */ + function initRuntime(Twig_Environment $environment); + + /** + * Returns the token parser instances to add to the existing list. + * + * @return (Twig_TokenParserInterface|Twig_TokenParserBrokerInterface)[] + */ + function getTokenParsers(); + + /** + * Returns the node visitor instances to add to the existing list. + * + * @return Twig_NodeVisitorInterface[] + */ + function getNodeVisitors(); + + /** + * Returns a list of filters to add to the existing list. + * + * @return Twig_SimpleFilter[] + */ + function getFilters(); + + /** + * Returns a list of tests to add to the existing list. + * + * @return Twig_SimpleTest[] + */ + function getTests(); + + /** + * Returns a list of functions to add to the existing list. + * + * @return Twig_SimpleFunction[] + */ + 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 + */ + function getOperators(); + + /** + * Returns a list of global variables to add to the existing list. + * + * @return array An array of global variables + */ + function getGlobals(); + + /** + * Returns the name of the extension. + * + * @return string The extension name + */ + function getName(); + } + +To keep your extension class clean and lean, it can inherit from the built-in +``Twig_Extension`` class instead of implementing the whole interface. That +way, you just need to implement the ``getName()`` method as the +``Twig_Extension`` provides empty implementations for all other methods. + +The ``getName()`` method must return a unique identifier for your extension. + +Now, with this information in mind, let's create the most basic extension +possible:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getName() + { + return 'project'; + } + } + +.. note:: + + Of course, this extension does nothing for now. We will customize it in + the next sections. + +Twig does not care where you save your extension on the filesystem, as all +extensions must be registered explicitly to be available in your templates. + +You can register an extension by using the ``addExtension()`` method on your +main ``Environment`` object:: + + $twig = new Twig_Environment($loader); + $twig->addExtension(new Project_Twig_Extension()); + +Of course, you need to first load the extension file by either using +``require_once()`` or by using an autoloader (see `spl_autoload_register()`_). + +.. tip:: + + The bundled extensions are great examples of how extensions work. + +Globals +~~~~~~~ + +Global variables can be registered in an extension via the ``getGlobals()`` +method:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getGlobals() + { + return array( + 'text' => new Text(), + ); + } + + // ... + } + +Functions +~~~~~~~~~ + +Functions can be registered in an extension via the ``getFunctions()`` +method:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getFunctions() + { + return array( + 'lipsum' => new Twig_Function_Function('generate_lipsum'), + ); + } + + // ... + } + +Filters +~~~~~~~ + +To add a filter to an extension, you need to override the ``getFilters()`` +method. This method must return an array of filters to add to the Twig +environment:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getFilters() + { + return array( + 'rot13' => new Twig_Filter_Function('str_rot13'), + ); + } + + // ... + } + +As you can see in the above code, the ``getFilters()`` method returns an array +where keys are the name of the filters (``rot13``) and the values the +definition of the filter (``new Twig_Filter_Function('str_rot13')``). + +As seen in the previous chapter, you can also define filters as static methods +on the extension class:: + +$twig->addFilter('rot13', new Twig_Filter_Function('Project_Twig_Extension::rot13Filter')); + +You can also use ``Twig_Filter_Method`` instead of ``Twig_Filter_Function`` +when defining a filter to use a method:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getFilters() + { + return array( + 'rot13' => new Twig_Filter_Method($this, 'rot13Filter'), + ); + } + + public function rot13Filter($string) + { + return str_rot13($string); + } + + // ... + } + +The first argument of the ``Twig_Filter_Method`` constructor is always +``$this``, the current extension object. The second one is the name of the +method to call. + +Using methods for filters is a great way to package your filter without +polluting the global namespace. This also gives the developer more flexibility +at the cost of a small overhead. + +Overriding default Filters +.......................... + +If some default core filters do not suit your needs, you can easily override +them by creating your own extension. Just use the same names as the one you +want to override:: + + class MyCoreExtension extends Twig_Extension + { + public function getFilters() + { + return array( + 'date' => new Twig_Filter_Method($this, 'dateFilter'), + // ... + ); + } + + public function dateFilter($timestamp, $format = 'F j, Y H:i') + { + return '...'.twig_date_format_filter($timestamp, $format); + } + + public function getName() + { + return 'project'; + } + } + +Here, we override the ``date`` filter with a custom one. Using this extension +is as simple as registering the ``MyCoreExtension`` extension by calling the +``addExtension()`` method on the environment instance:: + + $twig = new Twig_Environment($loader); + $twig->addExtension(new MyCoreExtension()); + +Tags +~~~~ + +Adding a tag in an extension can be done by overriding the +``getTokenParsers()`` method. This method must return an array of tags to add +to the Twig environment:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getTokenParsers() + { + return array(new Project_Set_TokenParser()); + } + + // ... + } + +In the above code, we have added a single new tag, defined by the +``Project_Set_TokenParser`` class. The ``Project_Set_TokenParser`` class is +responsible for parsing the tag and compiling it to PHP. + +Operators +~~~~~~~~~ + +The ``getOperators()`` methods allows to add new operators. Here is how to add +``!``, ``||``, and ``&&`` operators:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getOperators() + { + return array( + array( + '!' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'), + ), + array( + '||' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '&&' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + ), + ); + } + + // ... + } + +Tests +~~~~~ + +The ``getTests()`` methods allows to add new test functions:: + + class Project_Twig_Extension extends Twig_Extension + { + public function getTests() + { + return array( + 'even' => new Twig_Test_Function('twig_test_even'), + ); + } + + // ... + } + +Testing an Extension +-------------------- + +.. versionadded:: 1.10 + Support for functional tests was added in Twig 1.10. + +Functional Tests +~~~~~~~~~~~~~~~~ + +You can create functional tests for extensions simply by creating the +following file structure in your test directory:: + + Fixtures/ + filters/ + foo.test + bar.test + functions/ + foo.test + bar.test + tags/ + foo.test + bar.test + IntegrationTest.php + +The ``IntegrationTest.php`` file should look like this:: + + class Project_Tests_IntegrationTest extends Twig_Test_IntegrationTestCase + { + public function getExtensions() + { + return array( + new Project_Twig_Extension1(), + new Project_Twig_Extension2(), + ); + } + + public function getFixturesDir() + { + return dirname(__FILE__).'/Fixtures/'; + } + } + +Fixtures examples can be found within the Twig repository +`tests/Twig/Fixtures`_ directory. + +Node Tests +~~~~~~~~~~ + +Testing the node visitors can be complex, so extend your test cases from +``Twig_Test_NodeTestCase``. Examples can be found in the Twig repository +`tests/Twig/Node`_ directory. + +.. _`spl_autoload_register()`: https://secure.php.net/spl_autoload_register +.. _`rot13`: https://secure.php.net/manual/en/function.str-rot13.php +.. _`tests/Twig/Fixtures`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Fixtures +.. _`tests/Twig/Node`: https://github.com/twigphp/Twig/tree/master/test/Twig/Tests/Node diff --git a/vendor/twig/twig/doc/api.rst b/vendor/twig/twig/doc/api.rst new file mode 100644 index 0000000..8be2b8a --- /dev/null +++ b/vendor/twig/twig/doc/api.rst @@ -0,0 +1,590 @@ +Twig for Developers +=================== + +This chapter describes the API to Twig and not the template language. It will +be most useful as reference to those implementing the template interface to +the application and not those who are creating Twig templates. + +Basics +------ + +Twig uses a central object called the **environment** (of class +``Twig_Environment``). Instances of this class are used to store the +configuration and extensions, and are used to load templates from the file +system or other locations. + +Most applications will create one ``Twig_Environment`` object on application +initialization and use that to load templates. In some cases it's however +useful to have multiple environments side by side, if different configurations +are in use. + +The simplest way to configure Twig to load templates for your application +looks roughly like this:: + + require_once '/path/to/lib/Twig/Autoloader.php'; + Twig_Autoloader::register(); + + $loader = new Twig_Loader_Filesystem('/path/to/templates'); + $twig = new Twig_Environment($loader, array( + 'cache' => '/path/to/compilation_cache', + )); + +This will create a template environment with the default settings and a loader +that looks up the templates in the ``/path/to/templates/`` folder. Different +loaders are available and you can also write your own if you want to load +templates from a database or other resources. + +.. note:: + + Notice that the second argument of the environment is an array of options. + The ``cache`` option is a compilation cache directory, where Twig caches + the compiled templates to avoid the parsing phase for sub-sequent + requests. It is very different from the cache you might want to add for + the evaluated templates. For such a need, you can use any available PHP + cache library. + +Rendering Templates +------------------- + +To load a template from a Twig environment, call the ``load()`` method which +returns a ``Twig_TemplateWrapper`` instance:: + + $template = $twig->load('index.html'); + +.. note:: + + Before Twig 1.28, you should use ``loadTemplate()`` instead which returns a + ``Twig_Template`` instance. + +To render the template with some variables, call the ``render()`` method:: + + echo $template->render(array('the' => 'variables', 'go' => 'here')); + +.. note:: + + The ``display()`` method is a shortcut to output the template directly. + +You can also load and render the template in one fell swoop:: + + echo $twig->render('index.html', array('the' => 'variables', 'go' => 'here')); + +.. versionadded:: 1.28 + The possibility to render blocks from the API was added in Twig 1.28. + +If a template defines blocks, they can be rendered individually via the +``renderBlock()`` call:: + + echo $template->renderBlock('block_name', array('the' => 'variables', 'go' => 'here')); + +.. _environment_options: + +Environment Options +------------------- + +When creating a new ``Twig_Environment`` instance, you can pass an array of +options as the constructor second argument:: + + $twig = new Twig_Environment($loader, array('debug' => true)); + +The following options are available: + +* ``debug`` *boolean* + + When set to ``true``, the generated templates have a + ``__toString()`` method that you can use to display the generated nodes + (default to ``false``). + +* ``charset`` *string* (defaults to ``utf-8``) + + The charset used by the templates. + +* ``base_template_class`` *string* (defaults to ``Twig_Template``) + + The base template class to use for generated + templates. + +* ``cache`` *string* or ``false`` + + An absolute path where to store the compiled templates, or + ``false`` to disable caching (which is the default). + +* ``auto_reload`` *boolean* + + When developing with Twig, it's useful to recompile the + template whenever the source code changes. If you don't provide a value for + the ``auto_reload`` option, it will be determined automatically based on the + ``debug`` value. + +* ``strict_variables`` *boolean* + + If set to ``false``, Twig will silently ignore invalid + variables (variables and or attributes/methods that do not exist) and + replace them with a ``null`` value. When set to ``true``, Twig throws an + exception instead (default to ``false``). + +* ``autoescape`` *string* or *boolean* + + If set to ``true``, HTML auto-escaping will be enabled by + default for all templates (default to ``true``). + + As of Twig 1.8, you can set the escaping strategy to use (``html``, ``js``, + ``false`` to disable). + + As of Twig 1.9, you can set the escaping strategy to use (``css``, ``url``, + ``html_attr``, or a PHP callback that takes the template name and must + return the escaping strategy to use -- the callback cannot be a function name + to avoid collision with built-in escaping strategies). + + As of Twig 1.17, the ``filename`` escaping strategy (renamed to ``name`` as + of Twig 1.27) determines the escaping strategy to use for a template based on + the template filename extension (this strategy does not incur any overhead at + runtime as auto-escaping is done at compilation time.) + +* ``optimizations`` *integer* + + A flag that indicates which optimizations to apply + (default to ``-1`` -- all optimizations are enabled; set it to ``0`` to + disable). + +Loaders +------- + +Loaders are responsible for loading templates from a resource such as the file +system. + +Compilation Cache +~~~~~~~~~~~~~~~~~ + +All template loaders can cache the compiled templates on the filesystem for +future reuse. It speeds up Twig a lot as templates are only compiled once; and +the performance boost is even larger if you use a PHP accelerator such as APC. +See the ``cache`` and ``auto_reload`` options of ``Twig_Environment`` above +for more information. + +Built-in Loaders +~~~~~~~~~~~~~~~~ + +Here is a list of the built-in loaders Twig provides: + +``Twig_Loader_Filesystem`` +.......................... + +.. versionadded:: 1.10 + The ``prependPath()`` and support for namespaces were added in Twig 1.10. + +.. versionadded:: 1.27 + Relative paths support was added in Twig 1.27. + +``Twig_Loader_Filesystem`` loads templates from the file system. This loader +can find templates in folders on the file system and is the preferred way to +load them:: + + $loader = new Twig_Loader_Filesystem($templateDir); + +It can also look for templates in an array of directories:: + + $loader = new Twig_Loader_Filesystem(array($templateDir1, $templateDir2)); + +With such a configuration, Twig will first look for templates in +``$templateDir1`` and if they do not exist, it will fallback to look for them +in the ``$templateDir2``. + +You can add or prepend paths via the ``addPath()`` and ``prependPath()`` +methods:: + + $loader->addPath($templateDir3); + $loader->prependPath($templateDir4); + +The filesystem loader also supports namespaced templates. This allows to group +your templates under different namespaces which have their own template paths. + +When using the ``setPaths()``, ``addPath()``, and ``prependPath()`` methods, +specify the namespace as the second argument (when not specified, these +methods act on the "main" namespace):: + + $loader->addPath($templateDir, 'admin'); + +Namespaced templates can be accessed via the special +``@namespace_name/template_path`` notation:: + + $twig->render('@admin/index.html', array()); + +``Twig_Loader_Filesystem`` support absolute and relative paths. Using relative +paths is preferred as it makes the cache keys independent of the project root +directory (for instance, it allows warming the cache from a build server where +the directory might be different from the one used on production servers):: + + $loader = new Twig_Loader_Filesystem('templates', getcwd().'/..'); + +.. note:: + + When not passing the root path as a second argument, Twig uses ``getcwd()`` + for relative paths. + +``Twig_Loader_Array`` +..................... + +``Twig_Loader_Array`` loads a template from a PHP array. It's passed an array +of strings bound to template names:: + + $loader = new Twig_Loader_Array(array( + 'index.html' => 'Hello {{ name }}!', + )); + $twig = new Twig_Environment($loader); + + echo $twig->render('index.html', array('name' => 'Fabien')); + +This loader is very useful for unit testing. It can also be used for small +projects where storing all templates in a single PHP file might make sense. + +.. tip:: + + When using the ``Array`` or ``String`` loaders with a cache mechanism, you + should know that a new cache key is generated each time a template content + "changes" (the cache key being the source code of the template). If you + don't want to see your cache grows out of control, you need to take care + of clearing the old cache file by yourself. + +``Twig_Loader_Chain`` +..................... + +``Twig_Loader_Chain`` delegates the loading of templates to other loaders:: + + $loader1 = new Twig_Loader_Array(array( + 'base.html' => '{% block content %}{% endblock %}', + )); + $loader2 = new Twig_Loader_Array(array( + 'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}', + 'base.html' => 'Will never be loaded', + )); + + $loader = new Twig_Loader_Chain(array($loader1, $loader2)); + + $twig = new Twig_Environment($loader); + +When looking for a template, Twig will try each loader in turn and it will +return as soon as the template is found. When rendering the ``index.html`` +template from the above example, Twig will load it with ``$loader2`` but the +``base.html`` template will be loaded from ``$loader1``. + +``Twig_Loader_Chain`` accepts any loader that implements +``Twig_LoaderInterface``. + +.. note:: + + You can also add loaders via the ``addLoader()`` method. + +Create your own Loader +~~~~~~~~~~~~~~~~~~~~~~ + +All loaders implement the ``Twig_LoaderInterface``:: + + interface Twig_LoaderInterface + { + /** + * Gets the source code of a template, given its name. + * + * @param string $name string The name of the template to load + * + * @return string The template source code + * + * @deprecated since 1.27 (to be removed in 2.0), implement Twig_SourceContextLoaderInterface + */ + function getSource($name); + + /** + * Gets the cache key to use for the cache for a given template name. + * + * @param string $name string The name of the template to load + * + * @return string The cache key + */ + function getCacheKey($name); + + /** + * Returns true if the template is still fresh. + * + * @param string $name The template name + * @param timestamp $time The last modification time of the cached template + */ + function isFresh($name, $time); + } + +The ``isFresh()`` method must return ``true`` if the current cached template +is still fresh, given the last modification time, or ``false`` otherwise. + +.. note:: + + As of Twig 1.27, you should also implement + ``Twig_SourceContextLoaderInterface`` to avoid deprecation notices. + +.. tip:: + + As of Twig 1.11.0, you can also implement ``Twig_ExistsLoaderInterface`` + to make your loader faster when used with the chain loader. + +Using Extensions +---------------- + +Twig extensions are packages that add new features to Twig. Using an +extension is as simple as using the ``addExtension()`` method:: + + $twig->addExtension(new Twig_Extension_Sandbox()); + +Twig comes bundled with the following extensions: + +* *Twig_Extension_Core*: Defines all the core features of Twig. + +* *Twig_Extension_Escaper*: Adds automatic output-escaping and the possibility + to escape/unescape blocks of code. + +* *Twig_Extension_Sandbox*: Adds a sandbox mode to the default Twig + environment, making it safe to evaluate untrusted code. + +* *Twig_Extension_Profiler*: Enabled the built-in Twig profiler (as of Twig + 1.18). + +* *Twig_Extension_Optimizer*: Optimizes the node tree before compilation. + +The core, escaper, and optimizer extensions do not need to be added to the +Twig environment, as they are registered by default. + +Built-in Extensions +------------------- + +This section describes the features added by the built-in extensions. + +.. tip:: + + Read the chapter about extending Twig to learn how to create your own + extensions. + +Core Extension +~~~~~~~~~~~~~~ + +The ``core`` extension defines all the core features of Twig: + +* :doc:`Tags `; +* :doc:`Filters `; +* :doc:`Functions `; +* :doc:`Tests `. + +Escaper Extension +~~~~~~~~~~~~~~~~~ + +The ``escaper`` extension adds automatic output escaping to Twig. It defines a +tag, ``autoescape``, and a filter, ``raw``. + +When creating the escaper extension, you can switch on or off the global +output escaping strategy:: + + $escaper = new Twig_Extension_Escaper('html'); + $twig->addExtension($escaper); + +If set to ``html``, all variables in templates are escaped (using the ``html`` +escaping strategy), except those using the ``raw`` filter: + +.. code-block:: jinja + + {{ article.to_html|raw }} + +You can also change the escaping mode locally by using the ``autoescape`` tag +(see the :doc:`autoescape` doc for the syntax used before +Twig 1.8): + +.. code-block:: jinja + + {% autoescape 'html' %} + {{ var }} + {{ var|raw }} {# var won't be escaped #} + {{ var|escape }} {# var won't be double-escaped #} + {% endautoescape %} + +.. warning:: + + The ``autoescape`` tag has no effect on included files. + +The escaping rules are implemented as follows: + +* Literals (integers, booleans, arrays, ...) used in the template directly as + variables or filter arguments are never automatically escaped: + + .. code-block:: jinja + + {{ "Twig
" }} {# won't be escaped #} + + {% set text = "Twig
" %} + {{ text }} {# will be escaped #} + +* Expressions which the result is always a literal or a variable marked safe + are never automatically escaped: + + .. code-block:: jinja + + {{ foo ? "Twig
" : "
Twig" }} {# won't be escaped #} + + {% set text = "Twig
" %} + {{ foo ? text : "
Twig" }} {# will be escaped #} + + {% set text = "Twig
" %} + {{ foo ? text|raw : "
Twig" }} {# won't be escaped #} + + {% set text = "Twig
" %} + {{ foo ? text|escape : "
Twig" }} {# the result of the expression won't be escaped #} + +* Escaping is applied before printing, after any other filter is applied: + + .. code-block:: jinja + + {{ var|upper }} {# is equivalent to {{ var|upper|escape }} #} + +* The `raw` filter should only be used at the end of the filter chain: + + .. code-block:: jinja + + {{ var|raw|upper }} {# will be escaped #} + + {{ var|upper|raw }} {# won't be escaped #} + +* Automatic escaping is not applied if the last filter in the chain is marked + safe for the current context (e.g. ``html`` or ``js``). ``escape`` and + ``escape('html')`` are marked safe for HTML, ``escape('js')`` is marked + safe for JavaScript, ``raw`` is marked safe for everything. + + .. code-block:: jinja + + {% autoescape 'js' %} + {{ var|escape('html') }} {# will be escaped for HTML and JavaScript #} + {{ var }} {# will be escaped for JavaScript #} + {{ var|escape('js') }} {# won't be double-escaped #} + {% endautoescape %} + +.. note:: + + Note that autoescaping has some limitations as escaping is applied on + expressions after evaluation. For instance, when working with + concatenation, ``{{ foo|raw ~ bar }}`` won't give the expected result as + escaping is applied on the result of the concatenation, not on the + individual variables (so, the ``raw`` filter won't have any effect here). + +Sandbox Extension +~~~~~~~~~~~~~~~~~ + +The ``sandbox`` extension can be used to evaluate untrusted code. Access to +unsafe attributes and methods is prohibited. The sandbox security is managed +by a policy instance. By default, Twig comes with one policy class: +``Twig_Sandbox_SecurityPolicy``. This class allows you to white-list some +tags, filters, properties, and methods:: + + $tags = array('if'); + $filters = array('upper'); + $methods = array( + 'Article' => array('getTitle', 'getBody'), + ); + $properties = array( + 'Article' => array('title', 'body'), + ); + $functions = array('range'); + $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions); + +With the previous configuration, the security policy will only allow usage of +the ``if`` tag, and the ``upper`` filter. Moreover, the templates will only be +able to call the ``getTitle()`` and ``getBody()`` methods on ``Article`` +objects, and the ``title`` and ``body`` public properties. Everything else +won't be allowed and will generate a ``Twig_Sandbox_SecurityError`` exception. + +The policy object is the first argument of the sandbox constructor:: + + $sandbox = new Twig_Extension_Sandbox($policy); + $twig->addExtension($sandbox); + +By default, the sandbox mode is disabled and should be enabled when including +untrusted template code by using the ``sandbox`` tag: + +.. code-block:: jinja + + {% sandbox %} + {% include 'user.html' %} + {% endsandbox %} + +You can sandbox all templates by passing ``true`` as the second argument of +the extension constructor:: + + $sandbox = new Twig_Extension_Sandbox($policy, true); + +Profiler Extension +~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.18 + The Profile extension was added in Twig 1.18. + +The ``profiler`` extension enables a profiler for Twig templates; it should +only be used on your development machines as it adds some overhead:: + + $profile = new Twig_Profiler_Profile(); + $twig->addExtension(new Twig_Extension_Profiler($profile)); + + $dumper = new Twig_Profiler_Dumper_Text(); + echo $dumper->dump($profile); + +A profile contains information about time and memory consumption for template, +block, and macro executions. + +You can also dump the data in a `Blackfire.io `_ +compatible format:: + + $dumper = new Twig_Profiler_Dumper_Blackfire(); + file_put_contents('/path/to/profile.prof', $dumper->dump($profile)); + +Upload the profile to visualize it (create a `free account +`_ first): + +.. code-block:: sh + + blackfire --slot=7 upload /path/to/profile.prof + +Optimizer Extension +~~~~~~~~~~~~~~~~~~~ + +The ``optimizer`` extension optimizes the node tree before compilation:: + + $twig->addExtension(new Twig_Extension_Optimizer()); + +By default, all optimizations are turned on. You can select the ones you want +to enable by passing them to the constructor:: + + $optimizer = new Twig_Extension_Optimizer(Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR); + + $twig->addExtension($optimizer); + +Twig supports the following optimizations: + +* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_ALL``, enables all optimizations + (this is the default value). +* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_NONE``, disables all optimizations. + This reduces the compilation time, but it can increase the execution time + and the consumed memory. +* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_FOR``, optimizes the ``for`` tag by + removing the ``loop`` variable creation whenever possible. +* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_RAW_FILTER``, removes the ``raw`` + filter whenever possible. +* ``Twig_NodeVisitor_Optimizer::OPTIMIZE_VAR_ACCESS``, simplifies the creation + and access of variables in the compiled templates whenever possible. + +Exceptions +---------- + +Twig can throw exceptions: + +* ``Twig_Error``: The base exception for all errors. + +* ``Twig_Error_Syntax``: Thrown to tell the user that there is a problem with + the template syntax. + +* ``Twig_Error_Runtime``: Thrown when an error occurs at runtime (when a filter + does not exist for instance). + +* ``Twig_Error_Loader``: Thrown when an error occurs during template loading. + +* ``Twig_Sandbox_SecurityError``: Thrown when an unallowed tag, filter, or + method is called in a sandboxed template. diff --git a/vendor/twig/twig/doc/coding_standards.rst b/vendor/twig/twig/doc/coding_standards.rst new file mode 100644 index 0000000..bf8ea91 --- /dev/null +++ b/vendor/twig/twig/doc/coding_standards.rst @@ -0,0 +1,101 @@ +Coding Standards +================ + +When writing Twig templates, we recommend you to follow these official coding +standards: + +* Put one (and only one) space after the start of a delimiter (``{{``, ``{%``, + and ``{#``) and before the end of a delimiter (``}}``, ``%}``, and ``#}``): + + .. code-block:: jinja + + {{ foo }} + {# comment #} + {% if foo %}{% endif %} + + When using the whitespace control character, do not put any spaces between + it and the delimiter: + + .. code-block:: jinja + + {{- foo -}} + {#- comment -#} + {%- if foo -%}{%- endif -%} + +* Put one (and only one) space before and after the following operators: + comparison operators (``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``), math + operators (``+``, ``-``, ``/``, ``*``, ``%``, ``//``, ``**``), logic + operators (``not``, ``and``, ``or``), ``~``, ``is``, ``in``, and the ternary + operator (``?:``): + + .. code-block:: jinja + + {{ 1 + 2 }} + {{ foo ~ bar }} + {{ true ? true : false }} + +* Put one (and only one) space after the ``:`` sign in hashes and ``,`` in + arrays and hashes: + + .. code-block:: jinja + + {{ [1, 2, 3] }} + {{ {'foo': 'bar'} }} + +* Do not put any spaces after an opening parenthesis and before a closing + parenthesis in expressions: + + .. code-block:: jinja + + {{ 1 + (2 * 3) }} + +* Do not put any spaces before and after string delimiters: + + .. code-block:: jinja + + {{ 'foo' }} + {{ "foo" }} + +* Do not put any spaces before and after the following operators: ``|``, + ``.``, ``..``, ``[]``: + + .. code-block:: jinja + + {{ foo|upper|lower }} + {{ user.name }} + {{ user[name] }} + {% for i in 1..12 %}{% endfor %} + +* Do not put any spaces before and after the parenthesis used for filter and + function calls: + + .. code-block:: jinja + + {{ foo|default('foo') }} + {{ range(1..10) }} + +* Do not put any spaces before and after the opening and the closing of arrays + and hashes: + + .. code-block:: jinja + + {{ [1, 2, 3] }} + {{ {'foo': 'bar'} }} + +* Use lower cased and underscored variable names: + + .. code-block:: jinja + + {% set foo = 'foo' %} + {% set foo_bar = 'foo' %} + +* Indent your code inside tags (use the same indentation as the one used for + the target language of the rendered template): + + .. code-block:: jinja + + {% block foo %} + {% if true %} + true + {% endif %} + {% endblock %} diff --git a/vendor/twig/twig/doc/deprecated.rst b/vendor/twig/twig/doc/deprecated.rst new file mode 100644 index 0000000..8b25cc4 --- /dev/null +++ b/vendor/twig/twig/doc/deprecated.rst @@ -0,0 +1,224 @@ +Deprecated Features +=================== + +This document lists all deprecated features in Twig. Deprecated features are +kept for backward compatibility and removed in the next major release (a +feature that was deprecated in Twig 1.x is removed in Twig 2.0). + +Deprecation Notices +------------------- + +As of Twig 1.21, Twig generates deprecation notices when a template uses +deprecated features. See :ref:`deprecation-notices` for more information. + +Macros +------ + +As of Twig 2.0, macros imported in a file are not available in child templates +anymore (via an ``include`` call for instance). You need to import macros +explicitly in each file where you are using them. + +Token Parsers +------------- + +* As of Twig 1.x, the token parser broker sub-system is deprecated. The + following class and interface will be removed in 2.0: + + * ``Twig_TokenParserBrokerInterface`` + * ``Twig_TokenParserBroker`` + +* As of Twig 1.27, ``Twig_Parser::getFilename()`` is deprecated. From a token + parser, use ``$this->parser->getStream()->getSourceContext()->getPath()`` instead. + +* As of Twig 1.27, ``Twig_Parser::getEnvironment()`` is deprecated. + +Extensions +---------- + +* As of Twig 1.x, the ability to remove an extension is deprecated and the + ``Twig_Environment::removeExtension()`` method will be removed in 2.0. + +* As of Twig 1.23, the ``Twig_ExtensionInterface::initRuntime()`` method is + deprecated. You have two options to avoid the deprecation notice: if you + implement this method to store the environment for your custom filters, + functions, or tests, use the ``needs_environment`` option instead; if you + have more complex needs, explicitly implement + ``Twig_Extension_InitRuntimeInterface`` (not recommended). + +* As of Twig 1.23, the ``Twig_ExtensionInterface::getGlobals()`` method is + deprecated. Implement ``Twig_Extension_GlobalsInterface`` to avoid + deprecation notices. + +* As of Twig 1.26, the ``Twig_ExtensionInterface::getName()`` method is + deprecated and it is not used internally anymore. + +PEAR +---- + +PEAR support has been discontinued in Twig 1.15.1, and no PEAR packages are +provided anymore. Use Composer instead. + +Filters +------- + +* As of Twig 1.x, use ``Twig_SimpleFilter`` to add a filter. The following + classes and interfaces will be removed in 2.0: + + * ``Twig_FilterInterface`` + * ``Twig_FilterCallableInterface`` + * ``Twig_Filter`` + * ``Twig_Filter_Function`` + * ``Twig_Filter_Method`` + * ``Twig_Filter_Node`` + +* As of Twig 2.x, the ``Twig_SimpleFilter`` class is deprecated and will be + removed in Twig 3.x (use ``Twig_Filter`` instead). In Twig 2.x, + ``Twig_SimpleFilter`` is just an alias for ``Twig_Filter``. + +Functions +--------- + +* As of Twig 1.x, use ``Twig_SimpleFunction`` to add a function. The following + classes and interfaces will be removed in 2.0: + + * ``Twig_FunctionInterface`` + * ``Twig_FunctionCallableInterface`` + * ``Twig_Function`` + * ``Twig_Function_Function`` + * ``Twig_Function_Method`` + * ``Twig_Function_Node`` + +* As of Twig 2.x, the ``Twig_SimpleFunction`` class is deprecated and will be + removed in Twig 3.x (use ``Twig_Function`` instead). In Twig 2.x, + ``Twig_SimpleFunction`` is just an alias for ``Twig_Function``. + +Tests +----- + +* As of Twig 1.x, use ``Twig_SimpleTest`` to add a test. The following classes + and interfaces will be removed in 2.0: + + * ``Twig_TestInterface`` + * ``Twig_TestCallableInterface`` + * ``Twig_Test`` + * ``Twig_Test_Function`` + * ``Twig_Test_Method`` + * ``Twig_Test_Node`` + +* As of Twig 2.x, the ``Twig_SimpleTest`` class is deprecated and will be + removed in Twig 3.x (use ``Twig_Test`` instead). In Twig 2.x, + ``Twig_SimpleTest`` is just an alias for ``Twig_Test``. + +* The ``sameas`` and ``divisibleby`` tests are deprecated in favor of ``same + as`` and ``divisible by`` respectively. + +Tags +---- + +* As of Twig 1.x, the ``raw`` tag is deprecated. You should use ``verbatim`` + instead. + +Nodes +----- + +* As of Twig 1.x, ``Node::toXml()`` is deprecated and will be removed in Twig + 2.0. + +* As of Twig 1.26, ``Node::$nodes`` should only contains ``Twig_Node`` + instances, storing a ``null`` value is deprecated and won't be possible in + Twig 2.x. + +* As of Twig 1.27, the ``filename`` attribute on ``Twig_Node_Module`` is + deprecated. Use ``getName()`` instead. + +* As of Twig 1.27, the ``Twig_Node::getFilename()/Twig_Node::getLine()`` + methods are deprecated, use + ``Twig_Node::getTemplateName()/Twig_Node::getTemplateLine()`` instead. + +Interfaces +---------- + +* As of Twig 2.x, the following interfaces are deprecated and empty (they will + be removed in Twig 3.0): + +* ``Twig_CompilerInterface`` (use ``Twig_Compiler`` instead) +* ``Twig_LexerInterface`` (use ``Twig_Lexer`` instead) +* ``Twig_NodeInterface`` (use ``Twig_Node`` instead) +* ``Twig_ParserInterface`` (use ``Twig_Parser`` instead) +* ``Twig_ExistsLoaderInterface`` (merged with ``Twig_LoaderInterface``) +* ``Twig_SourceContextLoaderInterface`` (merged with ``Twig_LoaderInterface``) +* ``Twig_TemplateInterface`` (use ``Twig_Template`` instead, and use + those constants Twig_Template::ANY_CALL, Twig_Template::ARRAY_CALL, + Twig_Template::METHOD_CALL) + +Compiler +-------- + +* As of Twig 1.26, the ``Twig_Compiler::getFilename()`` has been deprecated. + You should not use it anyway as its values is not reliable. + +* As of Twig 1.27, the ``Twig_Compiler::addIndentation()`` has been deprecated. + Use ``Twig_Compiler::write('')`` instead. + +Loaders +------- + +* As of Twig 1.x, ``Twig_Loader_String`` is deprecated and will be removed in + 2.0. You can render a string via ``Twig_Environment::createTemplate()``. + +* As of Twig 1.27, ``Twig_LoaderInterface::getSource()`` is deprecated. + Implement ``Twig_SourceContextLoaderInterface`` instead and use + ``getSourceContext()``. + +Node Visitors +------------- + +* Because of the removal of ``Twig_NodeInterface`` in 2.0, you need to extend + ``Twig_BaseNodeVisitor`` instead of implementing ``Twig_NodeVisitorInterface`` + directly to make your node visitors compatible with both Twig 1.x and 2.x. + +Globals +------- + +* As of Twig 2.x, the ability to register a global variable after the runtime + or the extensions have been initialized is not possible anymore (but + changing the value of an already registered global is possible). + +* As of Twig 1.x, using the ``_self`` global variable to get access to the + current ``Twig_Template`` instance is deprecated; most usages only need the + current template name, which will continue to work in Twig 2.0. In Twig 2.0, + ``_self`` returns the current template name instead of the current + ``Twig_Template`` instance. If you are using ``{{ _self.templateName }}``, + just replace it with ``{{ _self }}``. + +Miscellaneous +------------- + +* As of Twig 1.x, ``Twig_Environment::clearTemplateCache()``, + ``Twig_Environment::writeCacheFile()``, + ``Twig_Environment::clearCacheFiles()``, + ``Twig_Environment::getCacheFilename()``, + ``Twig_Environment::getTemplateClassPrefix()``, + ``Twig_Environment::getLexer()``, ``Twig_Environment::getParser()``, and + ``Twig_Environment::getCompiler()`` are deprecated and will be removed in 2.0. + +* As of Twig 1.x, ``Twig_Template::getEnvironment()`` and + ``Twig_TemplateInterface::getEnvironment()`` are deprecated and will be + removed in 2.0. + +* As of Twig 1.21, setting the environment option ``autoescape`` to ``true`` is + deprecated and will be removed in 2.0. Use ``"html"`` instead. + +* As of Twig 1.27, ``Twig_Error::getTemplateFile()`` and + ``Twig_Error::setTemplateFile()`` are deprecated. Use + ``Twig_Error::getTemplateName()`` and ``Twig_Error::setTemplateName()`` + instead. + +* As of Twig 1.27, ``Twig_Template::getSource()`` is deprecated. Use + ``Twig_Template::getSourceContext()`` instead. + +* As of Twig 1.27, ``Twig_Parser::addHandler()`` and + ``Twig_Parser::addNodeVisitor()`` are deprecated and will be removed in 2.0. + +* As of Twig 1.29, some classes are marked as being final via the `@final` + annotation. Those classes will be marked as final in 2.0. diff --git a/vendor/twig/twig/doc/filters/abs.rst b/vendor/twig/twig/doc/filters/abs.rst new file mode 100644 index 0000000..5c13f49 --- /dev/null +++ b/vendor/twig/twig/doc/filters/abs.rst @@ -0,0 +1,18 @@ +``abs`` +======= + +The ``abs`` filter returns the absolute value. + +.. code-block:: jinja + + {# number = -5 #} + + {{ number|abs }} + + {# outputs 5 #} + +.. note:: + + Internally, Twig uses the PHP `abs`_ function. + +.. _`abs`: https://secure.php.net/abs diff --git a/vendor/twig/twig/doc/filters/batch.rst b/vendor/twig/twig/doc/filters/batch.rst new file mode 100644 index 0000000..f8b6fa9 --- /dev/null +++ b/vendor/twig/twig/doc/filters/batch.rst @@ -0,0 +1,51 @@ +``batch`` +========= + +.. versionadded:: 1.12.3 + The ``batch`` filter was added in Twig 1.12.3. + +The ``batch`` filter "batches" items by returning a list of lists with the +given number of items. A second parameter can be provided and used to fill in +missing items: + +.. code-block:: jinja + + {% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %} + + + {% for row in items|batch(3, 'No item') %} + + {% for column in row %} + + {% endfor %} + + {% endfor %} +
{{ column }}
+ +The above example will be rendered as: + +.. code-block:: jinja + + + + + + + + + + + + + + + + + +
abc
def
gNo itemNo item
+ +Arguments +--------- + +* ``size``: The size of the batch; fractional numbers will be rounded up +* ``fill``: Used to fill in missing items diff --git a/vendor/twig/twig/doc/filters/capitalize.rst b/vendor/twig/twig/doc/filters/capitalize.rst new file mode 100644 index 0000000..10546a1 --- /dev/null +++ b/vendor/twig/twig/doc/filters/capitalize.rst @@ -0,0 +1,11 @@ +``capitalize`` +============== + +The ``capitalize`` filter capitalizes a value. The first character will be +uppercase, all others lowercase: + +.. code-block:: jinja + + {{ 'my first car'|capitalize }} + + {# outputs 'My first car' #} diff --git a/vendor/twig/twig/doc/filters/convert_encoding.rst b/vendor/twig/twig/doc/filters/convert_encoding.rst new file mode 100644 index 0000000..43bf031 --- /dev/null +++ b/vendor/twig/twig/doc/filters/convert_encoding.rst @@ -0,0 +1,28 @@ +``convert_encoding`` +==================== + +.. versionadded:: 1.4 + The ``convert_encoding`` filter was added in Twig 1.4. + +The ``convert_encoding`` filter converts a string from one encoding to +another. The first argument is the expected output charset and the second one +is the input charset: + +.. code-block:: jinja + + {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} + +.. note:: + + This filter relies on the `iconv`_ or `mbstring`_ extension, so one of + them must be installed. In case both are installed, `mbstring`_ is used by + default (Twig before 1.8.1 uses `iconv`_ by default). + +Arguments +--------- + +* ``to``: The output charset +* ``from``: The input charset + +.. _`iconv`: https://secure.php.net/iconv +.. _`mbstring`: https://secure.php.net/mbstring diff --git a/vendor/twig/twig/doc/filters/date.rst b/vendor/twig/twig/doc/filters/date.rst new file mode 100644 index 0000000..811fd41 --- /dev/null +++ b/vendor/twig/twig/doc/filters/date.rst @@ -0,0 +1,100 @@ +``date`` +======== + +.. versionadded:: 1.1 + The timezone support has been added in Twig 1.1. + +.. versionadded:: 1.5 + The default date format support has been added in Twig 1.5. + +.. versionadded:: 1.6.1 + The default timezone support has been added in Twig 1.6.1. + +.. versionadded:: 1.11.0 + The introduction of the false value for the timezone was introduced in Twig 1.11.0 + +The ``date`` filter formats a date to a given format: + +.. code-block:: jinja + + {{ post.published_at|date("m/d/Y") }} + +The format specifier is the same as supported by `date`_, +except when the filtered data is of type `DateInterval`_, when the format must conform to +`DateInterval::format`_ instead. + +The ``date`` filter accepts strings (it must be in a format supported by the +`strtotime`_ function), `DateTime`_ instances, or `DateInterval`_ instances. For +instance, to display the current date, filter the word "now": + +.. code-block:: jinja + + {{ "now"|date("m/d/Y") }} + +To escape words and characters in the date format use ``\\`` in front of each +character: + +.. code-block:: jinja + + {{ post.published_at|date("F jS \\a\\t g:ia") }} + +If the value passed to the ``date`` filter is ``null``, it will return the +current date by default. If an empty string is desired instead of the current +date, use a ternary operator: + +.. code-block:: jinja + + {{ post.published_at is empty ? "" : post.published_at|date("m/d/Y") }} + +If no format is provided, Twig will use the default one: ``F j, Y H:i``. This +default can be easily changed by calling the ``setDateFormat()`` method on the +``core`` extension instance. The first argument is the default format for +dates and the second one is the default format for date intervals: + +.. code-block:: php + + $twig = new Twig_Environment($loader); + $twig->getExtension('Twig_Extension_Core')->setDateFormat('d/m/Y', '%d days'); + + // before Twig 1.26 + $twig->getExtension('core')->setDateFormat('d/m/Y', '%d days'); + +Timezone +-------- + +By default, the date is displayed by applying the default timezone (the one +specified in php.ini or declared in Twig -- see below), but you can override +it by explicitly specifying a timezone: + +.. code-block:: jinja + + {{ post.published_at|date("m/d/Y", "Europe/Paris") }} + +If the date is already a DateTime object, and if you want to keep its current +timezone, pass ``false`` as the timezone value: + +.. code-block:: jinja + + {{ post.published_at|date("m/d/Y", false) }} + +The default timezone can also be set globally by calling ``setTimezone()``: + +.. code-block:: php + + $twig = new Twig_Environment($loader); + $twig->getExtension('Twig_Extension_Core')->setTimezone('Europe/Paris'); + + // before Twig 1.26 + $twig->getExtension('core')->setTimezone('Europe/Paris'); + +Arguments +--------- + +* ``format``: The date format +* ``timezone``: The date timezone + +.. _`strtotime`: https://secure.php.net/strtotime +.. _`DateTime`: https://secure.php.net/DateTime +.. _`DateInterval`: https://secure.php.net/DateInterval +.. _`date`: https://secure.php.net/date +.. _`DateInterval::format`: https://secure.php.net/DateInterval.format diff --git a/vendor/twig/twig/doc/filters/date_modify.rst b/vendor/twig/twig/doc/filters/date_modify.rst new file mode 100644 index 0000000..8a41dd0 --- /dev/null +++ b/vendor/twig/twig/doc/filters/date_modify.rst @@ -0,0 +1,23 @@ +``date_modify`` +=============== + +.. versionadded:: 1.9.0 + The date_modify filter has been added in Twig 1.9.0. + +The ``date_modify`` filter modifies a date with a given modifier string: + +.. code-block:: jinja + + {{ post.published_at|date_modify("+1 day")|date("m/d/Y") }} + +The ``date_modify`` filter accepts strings (it must be in a format supported +by the `strtotime`_ function) or `DateTime`_ instances. You can easily combine +it with the :doc:`date` filter for formatting. + +Arguments +--------- + +* ``modifier``: The modifier + +.. _`strtotime`: https://secure.php.net/strtotime +.. _`DateTime`: https://secure.php.net/DateTime diff --git a/vendor/twig/twig/doc/filters/default.rst b/vendor/twig/twig/doc/filters/default.rst new file mode 100644 index 0000000..641ac6e --- /dev/null +++ b/vendor/twig/twig/doc/filters/default.rst @@ -0,0 +1,33 @@ +``default`` +=========== + +The ``default`` filter returns the passed default value if the value is +undefined or empty, otherwise the value of the variable: + +.. code-block:: jinja + + {{ var|default('var is not defined') }} + + {{ var.foo|default('foo item on var is not defined') }} + + {{ var['foo']|default('foo item on var is not defined') }} + + {{ ''|default('passed var is empty') }} + +When using the ``default`` filter on an expression that uses variables in some +method calls, be sure to use the ``default`` filter whenever a variable can be +undefined: + +.. code-block:: jinja + + {{ var.method(foo|default('foo'))|default('foo') }} + +.. note:: + + Read the documentation for the :doc:`defined<../tests/defined>` and + :doc:`empty<../tests/empty>` tests to learn more about their semantics. + +Arguments +--------- + +* ``default``: The default value diff --git a/vendor/twig/twig/doc/filters/escape.rst b/vendor/twig/twig/doc/filters/escape.rst new file mode 100644 index 0000000..6d6f40e --- /dev/null +++ b/vendor/twig/twig/doc/filters/escape.rst @@ -0,0 +1,119 @@ +``escape`` +========== + +.. versionadded:: 1.9.0 + The ``css``, ``url``, and ``html_attr`` strategies were added in Twig + 1.9.0. + +.. versionadded:: 1.14.0 + The ability to define custom escapers was added in Twig 1.14.0. + +The ``escape`` filter escapes a string for safe insertion into the final +output. It supports different escaping strategies depending on the template +context. + +By default, it uses the HTML escaping strategy: + +.. code-block:: jinja + + {{ user.username|escape }} + +For convenience, the ``e`` filter is defined as an alias: + +.. code-block:: jinja + + {{ user.username|e }} + +The ``escape`` filter can also be used in other contexts than HTML thanks to +an optional argument which defines the escaping strategy to use: + +.. code-block:: jinja + + {{ user.username|e }} + {# is equivalent to #} + {{ user.username|e('html') }} + +And here is how to escape variables included in JavaScript code: + +.. code-block:: jinja + + {{ user.username|escape('js') }} + {{ user.username|e('js') }} + +The ``escape`` filter supports the following escaping strategies: + +* ``html``: escapes a string for the **HTML body** context. + +* ``js``: escapes a string for the **JavaScript context**. + +* ``css``: escapes a string for the **CSS context**. CSS escaping can be + applied to any string being inserted into CSS and escapes everything except + alphanumerics. + +* ``url``: escapes a string for the **URI or parameter contexts**. This should + not be used to escape an entire URI; only a subcomponent being inserted. + +* ``html_attr``: escapes a string for the **HTML attribute** context. + +.. note:: + + Internally, ``escape`` uses the PHP native `htmlspecialchars`_ function + for the HTML escaping strategy. + +.. caution:: + + When using automatic escaping, Twig tries to not double-escape a variable + when the automatic escaping strategy is the same as the one applied by the + escape filter; but that does not work when using a variable as the + escaping strategy: + + .. code-block:: jinja + + {% set strategy = 'html' %} + + {% autoescape 'html' %} + {{ var|escape('html') }} {# won't be double-escaped #} + {{ var|escape(strategy) }} {# will be double-escaped #} + {% endautoescape %} + + When using a variable as the escaping strategy, you should disable + automatic escaping: + + .. code-block:: jinja + + {% set strategy = 'html' %} + + {% autoescape 'html' %} + {{ var|escape(strategy)|raw }} {# won't be double-escaped #} + {% endautoescape %} + +Custom Escapers +--------------- + +You can define custom escapers by calling the ``setEscaper()`` method on the +``core`` extension instance. The first argument is the escaper name (to be +used in the ``escape`` call) and the second one must be a valid PHP callable: + +.. code-block:: php + + $twig = new Twig_Environment($loader); + $twig->getExtension('Twig_Extension_Core')->setEscaper('csv', 'csv_escaper'); + + // before Twig 1.26 + $twig->getExtension('core')->setEscaper('csv', 'csv_escaper'); + +When called by Twig, the callable receives the Twig environment instance, the +string to escape, and the charset. + +.. note:: + + Built-in escapers cannot be overridden mainly they should be considered as + the final implementation and also for better performance. + +Arguments +--------- + +* ``strategy``: The escaping strategy +* ``charset``: The string charset + +.. _`htmlspecialchars`: https://secure.php.net/htmlspecialchars diff --git a/vendor/twig/twig/doc/filters/first.rst b/vendor/twig/twig/doc/filters/first.rst new file mode 100644 index 0000000..da2c2ee --- /dev/null +++ b/vendor/twig/twig/doc/filters/first.rst @@ -0,0 +1,25 @@ +``first`` +========= + +.. versionadded:: 1.12.2 + The ``first`` filter was added in Twig 1.12.2. + +The ``first`` filter returns the first "element" of a sequence, a mapping, or +a string: + +.. code-block:: jinja + + {{ [1, 2, 3, 4]|first }} + {# outputs 1 #} + + {{ { a: 1, b: 2, c: 3, d: 4 }|first }} + {# outputs 1 #} + + {{ '1234'|first }} + {# outputs 1 #} + +.. note:: + + It also works with objects implementing the `Traversable`_ interface. + +.. _`Traversable`: https://secure.php.net/manual/en/class.traversable.php diff --git a/vendor/twig/twig/doc/filters/format.rst b/vendor/twig/twig/doc/filters/format.rst new file mode 100644 index 0000000..c600edb --- /dev/null +++ b/vendor/twig/twig/doc/filters/format.rst @@ -0,0 +1,16 @@ +``format`` +========== + +The ``format`` filter formats a given string by replacing the placeholders +(placeholders follows the `sprintf`_ notation): + +.. code-block:: jinja + + {{ "I like %s and %s."|format(foo, "bar") }} + + {# outputs I like foo and bar + if the foo parameter equals to the foo string. #} + +.. _`sprintf`: https://secure.php.net/sprintf + +.. seealso:: :doc:`replace` diff --git a/vendor/twig/twig/doc/filters/index.rst b/vendor/twig/twig/doc/filters/index.rst new file mode 100644 index 0000000..8daa961 --- /dev/null +++ b/vendor/twig/twig/doc/filters/index.rst @@ -0,0 +1,37 @@ +Filters +======= + +.. toctree:: + :maxdepth: 1 + + abs + batch + capitalize + convert_encoding + date + date_modify + default + escape + first + format + join + json_encode + keys + last + length + lower + merge + nl2br + number_format + raw + replace + reverse + round + slice + sort + split + striptags + title + trim + upper + url_encode diff --git a/vendor/twig/twig/doc/filters/join.rst b/vendor/twig/twig/doc/filters/join.rst new file mode 100644 index 0000000..2fab945 --- /dev/null +++ b/vendor/twig/twig/doc/filters/join.rst @@ -0,0 +1,23 @@ +``join`` +======== + +The ``join`` filter returns a string which is the concatenation of the items +of a sequence: + +.. code-block:: jinja + + {{ [1, 2, 3]|join }} + {# returns 123 #} + +The separator between elements is an empty string per default, but you can +define it with the optional first parameter: + +.. code-block:: jinja + + {{ [1, 2, 3]|join('|') }} + {# outputs 1|2|3 #} + +Arguments +--------- + +* ``glue``: The separator diff --git a/vendor/twig/twig/doc/filters/json_encode.rst b/vendor/twig/twig/doc/filters/json_encode.rst new file mode 100644 index 0000000..f02a7a8 --- /dev/null +++ b/vendor/twig/twig/doc/filters/json_encode.rst @@ -0,0 +1,23 @@ +``json_encode`` +=============== + +The ``json_encode`` filter returns the JSON representation of a value: + +.. code-block:: jinja + + {{ data|json_encode() }} + +.. note:: + + Internally, Twig uses the PHP `json_encode`_ function. + +Arguments +--------- + +* ``options``: A bitmask of `json_encode options`_: ``{{ + data|json_encode(constant('JSON_PRETTY_PRINT')) }}``. + Combine constants using :ref:`bitwise operators`: + ``{{ data|json_encode(constant('JSON_PRETTY_PRINT') b-or constant('JSON_HEX_QUOT') }}`` + +.. _`json_encode`: https://secure.php.net/json_encode +.. _`json_encode options`: https://secure.php.net/manual/en/json.constants.php diff --git a/vendor/twig/twig/doc/filters/keys.rst b/vendor/twig/twig/doc/filters/keys.rst new file mode 100644 index 0000000..e4f090c --- /dev/null +++ b/vendor/twig/twig/doc/filters/keys.rst @@ -0,0 +1,11 @@ +``keys`` +======== + +The ``keys`` filter returns the keys of an array. It is useful when you want to +iterate over the keys of an array: + +.. code-block:: jinja + + {% for key in array|keys %} + ... + {% endfor %} diff --git a/vendor/twig/twig/doc/filters/last.rst b/vendor/twig/twig/doc/filters/last.rst new file mode 100644 index 0000000..c59ba3f --- /dev/null +++ b/vendor/twig/twig/doc/filters/last.rst @@ -0,0 +1,25 @@ +``last`` +======== + +.. versionadded:: 1.12.2 + The ``last`` filter was added in Twig 1.12.2. + +The ``last`` filter returns the last "element" of a sequence, a mapping, or +a string: + +.. code-block:: jinja + + {{ [1, 2, 3, 4]|last }} + {# outputs 4 #} + + {{ { a: 1, b: 2, c: 3, d: 4 }|last }} + {# outputs 4 #} + + {{ '1234'|last }} + {# outputs 4 #} + +.. note:: + + It also works with objects implementing the `Traversable`_ interface. + +.. _`Traversable`: https://secure.php.net/manual/en/class.traversable.php diff --git a/vendor/twig/twig/doc/filters/length.rst b/vendor/twig/twig/doc/filters/length.rst new file mode 100644 index 0000000..e177b7b --- /dev/null +++ b/vendor/twig/twig/doc/filters/length.rst @@ -0,0 +1,23 @@ +``length`` +========== + +.. versionadded:: 1.33 + + Support for the ``__toString()`` magic method has been added in Twig 1.33. + +The ``length`` filter returns the number of items of a sequence or mapping, or +the length of a string. + +For objects that implement the ``Countable`` interface, ``length`` will use the +return value of the ``count()`` method. + +For objects that implement the ``__toString()`` magic method (and not ``Countable``), +it will return the length of the string provided by that method. + +For objects that implement the ``IteratorAggregate`` interface, ``length`` will use the return value of the ``iterator_count()`` method. + +.. code-block:: jinja + + {% if users|length > 10 %} + ... + {% endif %} diff --git a/vendor/twig/twig/doc/filters/lower.rst b/vendor/twig/twig/doc/filters/lower.rst new file mode 100644 index 0000000..ef9faa9 --- /dev/null +++ b/vendor/twig/twig/doc/filters/lower.rst @@ -0,0 +1,10 @@ +``lower`` +========= + +The ``lower`` filter converts a value to lowercase: + +.. code-block:: jinja + + {{ 'WELCOME'|lower }} + + {# outputs 'welcome' #} diff --git a/vendor/twig/twig/doc/filters/merge.rst b/vendor/twig/twig/doc/filters/merge.rst new file mode 100644 index 0000000..b0571f0 --- /dev/null +++ b/vendor/twig/twig/doc/filters/merge.rst @@ -0,0 +1,48 @@ +``merge`` +========= + +The ``merge`` filter merges an array with another array: + +.. code-block:: jinja + + {% set values = [1, 2] %} + + {% set values = values|merge(['apple', 'orange']) %} + + {# values now contains [1, 2, 'apple', 'orange'] #} + +New values are added at the end of the existing ones. + +The ``merge`` filter also works on hashes: + +.. code-block:: jinja + + {% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %} + + {% set items = items|merge({ 'peugeot': 'car', 'renault': 'car' }) %} + + {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car', 'renault': 'car' } #} + +For hashes, the merging process occurs on the keys: if the key does not +already exist, it is added but if the key already exists, its value is +overridden. + +.. tip:: + + If you want to ensure that some values are defined in an array (by given + default values), reverse the two elements in the call: + + .. code-block:: jinja + + {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %} + + {% set items = { 'apple': 'unknown' }|merge(items) %} + + {# items now contains { 'apple': 'fruit', 'orange': 'fruit' } #} + +.. note:: + + Internally, Twig uses the PHP `array_merge`_ function. It supports + Traversable objects by transforming those to arrays. + +.. _`array_merge`: https://secure.php.net/array_merge diff --git a/vendor/twig/twig/doc/filters/nl2br.rst b/vendor/twig/twig/doc/filters/nl2br.rst new file mode 100644 index 0000000..5c923e1 --- /dev/null +++ b/vendor/twig/twig/doc/filters/nl2br.rst @@ -0,0 +1,22 @@ +``nl2br`` +========= + +.. versionadded:: 1.5 + The ``nl2br`` filter was added in Twig 1.5. + +The ``nl2br`` filter inserts HTML line breaks before all newlines in a string: + +.. code-block:: jinja + + {{ "I like Twig.\nYou will like it too."|nl2br }} + {# outputs + + I like Twig.
+ You will like it too. + + #} + +.. note:: + + The ``nl2br`` filter pre-escapes the input before applying the + transformation. diff --git a/vendor/twig/twig/doc/filters/number_format.rst b/vendor/twig/twig/doc/filters/number_format.rst new file mode 100644 index 0000000..4db1ec9 --- /dev/null +++ b/vendor/twig/twig/doc/filters/number_format.rst @@ -0,0 +1,56 @@ +``number_format`` +================= + +.. versionadded:: 1.5 + The ``number_format`` filter was added in Twig 1.5 + +The ``number_format`` filter formats numbers. It is a wrapper around PHP's +`number_format`_ function: + +.. code-block:: jinja + + {{ 200.35|number_format }} + +You can control the number of decimal places, decimal point, and thousands +separator using the additional arguments: + +.. code-block:: jinja + + {{ 9800.333|number_format(2, '.', ',') }} + +To format negative numbers, wrap the number with parentheses (needed because of +Twig's :ref:`precedence of operators `: + +.. code-block:: jinja + + {{ -9800.333|number_format(2, '.', ',') }} {# outputs : -9 #} + {{ (-9800.333)|number_format(2, '.', ',') }} {# outputs : -9,800.33 #} + +If no formatting options are provided then Twig will use the default formatting +options of: + +* 0 decimal places. +* ``.`` as the decimal point. +* ``,`` as the thousands separator. + +These defaults can be easily changed through the core extension: + +.. code-block:: php + + $twig = new Twig_Environment($loader); + $twig->getExtension('Twig_Extension_Core')->setNumberFormat(3, '.', ','); + + // before Twig 1.26 + $twig->getExtension('core')->setNumberFormat(3, '.', ','); + +The defaults set for ``number_format`` can be over-ridden upon each call using the +additional parameters. + +Arguments +--------- + +* ``decimal``: The number of decimal points to display +* ``decimal_point``: The character(s) to use for the decimal point +* ``thousand_sep``: The character(s) to use for the thousands separator + +.. _`number_format`: https://secure.php.net/number_format diff --git a/vendor/twig/twig/doc/filters/raw.rst b/vendor/twig/twig/doc/filters/raw.rst new file mode 100644 index 0000000..e5e5b12 --- /dev/null +++ b/vendor/twig/twig/doc/filters/raw.rst @@ -0,0 +1,36 @@ +``raw`` +======= + +The ``raw`` filter marks the value as being "safe", which means that in an +environment with automatic escaping enabled this variable will not be escaped +if ``raw`` is the last filter applied to it: + +.. code-block:: jinja + + {% autoescape %} + {{ var|raw }} {# var won't be escaped #} + {% endautoescape %} + +.. note:: + + Be careful when using the ``raw`` filter inside expressions: + + .. code-block:: jinja + + {% autoescape %} + {% set hello = 'Hello' %} + {% set hola = 'Hola' %} + + {{ false ? 'Hola' : hello|raw }} + does not render the same as + {{ false ? hola : hello|raw }} + but renders the same as + {{ (false ? hola : hello)|raw }} + {% endautoescape %} + + The first ternary statement is not escaped: ``hello`` is marked as being + safe and Twig does not escape static values (see + :doc:`escape<../tags/autoescape>`). In the second ternary statement, even + if ``hello`` is marked as safe, ``hola`` remains unsafe and so is the whole + expression. The third ternary statement is marked as safe and the result is + not escaped. diff --git a/vendor/twig/twig/doc/filters/replace.rst b/vendor/twig/twig/doc/filters/replace.rst new file mode 100644 index 0000000..31392f3 --- /dev/null +++ b/vendor/twig/twig/doc/filters/replace.rst @@ -0,0 +1,25 @@ +``replace`` +=========== + +The ``replace`` filter formats a given string by replacing the placeholders +(placeholders are free-form): + +.. code-block:: jinja + + {{ "I like %this% and %that%."|replace({'%this%': foo, '%that%': "bar"}) }} + + {# outputs I like foo and bar + if the foo parameter equals to the foo string. #} + + {# using % as a delimiter is purely conventional and optional #} + + {{ "I like this and --that--."|replace({'this': foo, '--that--': "bar"}) }} + + {# outputs I like foo and bar #} + +Arguments +--------- + +* ``from``: The placeholder values + +.. seealso:: :doc:`format` diff --git a/vendor/twig/twig/doc/filters/reverse.rst b/vendor/twig/twig/doc/filters/reverse.rst new file mode 100644 index 0000000..8e1d967 --- /dev/null +++ b/vendor/twig/twig/doc/filters/reverse.rst @@ -0,0 +1,47 @@ +``reverse`` +=========== + +.. versionadded:: 1.6 + Support for strings has been added in Twig 1.6. + +The ``reverse`` filter reverses a sequence, a mapping, or a string: + +.. code-block:: jinja + + {% for user in users|reverse %} + ... + {% endfor %} + + {{ '1234'|reverse }} + + {# outputs 4321 #} + +.. tip:: + + For sequences and mappings, numeric keys are not preserved. To reverse + them as well, pass ``true`` as an argument to the ``reverse`` filter: + + .. code-block:: jinja + + {% for key, value in {1: "a", 2: "b", 3: "c"}|reverse %} + {{ key }}: {{ value }} + {%- endfor %} + + {# output: 0: c 1: b 2: a #} + + {% for key, value in {1: "a", 2: "b", 3: "c"}|reverse(true) %} + {{ key }}: {{ value }} + {%- endfor %} + + {# output: 3: c 2: b 1: a #} + +.. note:: + + It also works with objects implementing the `Traversable`_ interface. + +Arguments +--------- + +* ``preserve_keys``: Preserve keys when reversing a mapping or a sequence. + +.. _`Traversable`: https://secure.php.net/Traversable diff --git a/vendor/twig/twig/doc/filters/round.rst b/vendor/twig/twig/doc/filters/round.rst new file mode 100644 index 0000000..2521cf1 --- /dev/null +++ b/vendor/twig/twig/doc/filters/round.rst @@ -0,0 +1,37 @@ +``round`` +========= + +.. versionadded:: 1.15.0 + The ``round`` filter was added in Twig 1.15.0. + +The ``round`` filter rounds a number to a given precision: + +.. code-block:: jinja + + {{ 42.55|round }} + {# outputs 43 #} + + {{ 42.55|round(1, 'floor') }} + {# outputs 42.5 #} + +The ``round`` filter takes two optional arguments; the first one specifies the +precision (default is ``0``) and the second the rounding method (default is +``common``): + +* ``common`` rounds either up or down (rounds the value up to precision decimal + places away from zero, when it is half way there -- making 1.5 into 2 and + -1.5 into -2); + +* ``ceil`` always rounds up; + +* ``floor`` always rounds down. + +.. note:: + + The ``//`` operator is equivalent to ``|round(0, 'floor')``. + +Arguments +--------- + +* ``precision``: The rounding precision +* ``method``: The rounding method diff --git a/vendor/twig/twig/doc/filters/slice.rst b/vendor/twig/twig/doc/filters/slice.rst new file mode 100644 index 0000000..defe7a0 --- /dev/null +++ b/vendor/twig/twig/doc/filters/slice.rst @@ -0,0 +1,71 @@ +``slice`` +=========== + +.. versionadded:: 1.6 + The ``slice`` filter was added in Twig 1.6. + +The ``slice`` filter extracts a slice of a sequence, a mapping, or a string: + +.. code-block:: jinja + + {% for i in [1, 2, 3, 4, 5]|slice(1, 2) %} + {# will iterate over 2 and 3 #} + {% endfor %} + + {{ '12345'|slice(1, 2) }} + + {# outputs 23 #} + +You can use any valid expression for both the start and the length: + +.. code-block:: jinja + + {% for i in [1, 2, 3, 4, 5]|slice(start, length) %} + {# ... #} + {% endfor %} + +As syntactic sugar, you can also use the ``[]`` notation: + +.. code-block:: jinja + + {% for i in [1, 2, 3, 4, 5][start:length] %} + {# ... #} + {% endfor %} + + {{ '12345'[1:2] }} {# will display "23" #} + + {# you can omit the first argument -- which is the same as 0 #} + {{ '12345'[:2] }} {# will display "12" #} + + {# you can omit the last argument -- which will select everything till the end #} + {{ '12345'[2:] }} {# will display "345" #} + +The ``slice`` filter works as the `array_slice`_ PHP function for arrays and +`mb_substr`_ for strings with a fallback to `substr`_. + +If the start is non-negative, the sequence will start at that start in the +variable. If start is negative, the sequence will start that far from the end +of the variable. + +If length is given and is positive, then the sequence will have up to that +many elements in it. If the variable is shorter than the length, then only the +available variable elements will be present. If length is given and is +negative then the sequence will stop that many elements from the end of the +variable. If it is omitted, then the sequence will have everything from offset +up until the end of the variable. + +.. note:: + + It also works with objects implementing the `Traversable`_ interface. + +Arguments +--------- + +* ``start``: The start of the slice +* ``length``: The size of the slice +* ``preserve_keys``: Whether to preserve key or not (when the input is an array) + +.. _`Traversable`: https://secure.php.net/manual/en/class.traversable.php +.. _`array_slice`: https://secure.php.net/array_slice +.. _`mb_substr` : https://secure.php.net/mb-substr +.. _`substr`: https://secure.php.net/substr diff --git a/vendor/twig/twig/doc/filters/sort.rst b/vendor/twig/twig/doc/filters/sort.rst new file mode 100644 index 0000000..02f9bdf --- /dev/null +++ b/vendor/twig/twig/doc/filters/sort.rst @@ -0,0 +1,18 @@ +``sort`` +======== + +The ``sort`` filter sorts an array: + +.. code-block:: jinja + + {% for user in users|sort %} + ... + {% endfor %} + +.. note:: + + Internally, Twig uses the PHP `asort`_ function to maintain index + association. It supports Traversable objects by transforming + those to arrays. + +.. _`asort`: https://secure.php.net/asort diff --git a/vendor/twig/twig/doc/filters/split.rst b/vendor/twig/twig/doc/filters/split.rst new file mode 100644 index 0000000..c69dbe1 --- /dev/null +++ b/vendor/twig/twig/doc/filters/split.rst @@ -0,0 +1,53 @@ +``split`` +========= + +.. versionadded:: 1.10.3 + The ``split`` filter was added in Twig 1.10.3. + +The ``split`` filter splits a string by the given delimiter and returns a list +of strings: + +.. code-block:: jinja + + {% set foo = "one,two,three"|split(',') %} + {# foo contains ['one', 'two', 'three'] #} + +You can also pass a ``limit`` argument: + +* If ``limit`` is positive, the returned array will contain a maximum of + limit elements with the last element containing the rest of string; + +* If ``limit`` is negative, all components except the last -limit are + returned; + +* If ``limit`` is zero, then this is treated as 1. + +.. code-block:: jinja + + {% set foo = "one,two,three,four,five"|split(',', 3) %} + {# foo contains ['one', 'two', 'three,four,five'] #} + +If the ``delimiter`` is an empty string, then value will be split by equal +chunks. Length is set by the ``limit`` argument (one character by default). + +.. code-block:: jinja + + {% set foo = "123"|split('') %} + {# foo contains ['1', '2', '3'] #} + + {% set bar = "aabbcc"|split('', 2) %} + {# bar contains ['aa', 'bb', 'cc'] #} + +.. note:: + + Internally, Twig uses the PHP `explode`_ or `str_split`_ (if delimiter is + empty) functions for string splitting. + +Arguments +--------- + +* ``delimiter``: The delimiter +* ``limit``: The limit argument + +.. _`explode`: https://secure.php.net/explode +.. _`str_split`: https://secure.php.net/str_split diff --git a/vendor/twig/twig/doc/filters/striptags.rst b/vendor/twig/twig/doc/filters/striptags.rst new file mode 100644 index 0000000..87e0fbf --- /dev/null +++ b/vendor/twig/twig/doc/filters/striptags.rst @@ -0,0 +1,29 @@ +``striptags`` +============= + +The ``striptags`` filter strips SGML/XML tags and replace adjacent whitespace +by one space: + +.. code-block:: jinja + + {{ some_html|striptags }} + +You can also provide tags which should not be stripped: + +.. code-block:: jinja + + {{ some_html|striptags('

') }} + +In this example, the ``
``, ``
``, ``

``, and ``

`` tags won't be +removed from the string. + +.. note:: + + Internally, Twig uses the PHP `strip_tags`_ function. + +Arguments +--------- + +* ``allowable_tags``: Tags which should not be stripped + +.. _`strip_tags`: https://secure.php.net/strip_tags diff --git a/vendor/twig/twig/doc/filters/title.rst b/vendor/twig/twig/doc/filters/title.rst new file mode 100644 index 0000000..c5a318e --- /dev/null +++ b/vendor/twig/twig/doc/filters/title.rst @@ -0,0 +1,11 @@ +``title`` +========= + +The ``title`` filter returns a titlecased version of the value. Words will +start with uppercase letters, all remaining characters are lowercase: + +.. code-block:: jinja + + {{ 'my first car'|title }} + + {# outputs 'My First Car' #} diff --git a/vendor/twig/twig/doc/filters/trim.rst b/vendor/twig/twig/doc/filters/trim.rst new file mode 100644 index 0000000..dfaf4cf --- /dev/null +++ b/vendor/twig/twig/doc/filters/trim.rst @@ -0,0 +1,45 @@ +``trim`` +======== + +.. versionadded:: 1.32 + The ``side`` argument was added in Twig 1.32. + +.. versionadded:: 1.6.2 + The ``trim`` filter was added in Twig 1.6.2. + +The ``trim`` filter strips whitespace (or other characters) from the beginning +and end of a string: + +.. code-block:: jinja + + {{ ' I like Twig. '|trim }} + + {# outputs 'I like Twig.' #} + + {{ ' I like Twig.'|trim('.') }} + + {# outputs ' I like Twig' #} + + {{ ' I like Twig. '|trim(side='left') }} + + {# outputs 'I like Twig. ' #} + + {{ ' I like Twig. '|trim(' ', 'right') }} + + {# outputs ' I like Twig.' #} + +.. note:: + + Internally, Twig uses the PHP `trim`_, `ltrim`_, and `rtrim`_ functions. + +Arguments +--------- + +* ``character_mask``: The characters to strip + +* ``side``: The default is to strip from the left and the right (`both`) sides, but `left` + and `right` will strip from either the left side or right side only + +.. _`trim`: https://secure.php.net/trim +.. _`ltrim`: https://secure.php.net/ltrim +.. _`rtrim`: https://secure.php.net/rtrim diff --git a/vendor/twig/twig/doc/filters/upper.rst b/vendor/twig/twig/doc/filters/upper.rst new file mode 100644 index 0000000..561cebe --- /dev/null +++ b/vendor/twig/twig/doc/filters/upper.rst @@ -0,0 +1,10 @@ +``upper`` +========= + +The ``upper`` filter converts a value to uppercase: + +.. code-block:: jinja + + {{ 'welcome'|upper }} + + {# outputs 'WELCOME' #} diff --git a/vendor/twig/twig/doc/filters/url_encode.rst b/vendor/twig/twig/doc/filters/url_encode.rst new file mode 100644 index 0000000..4012e55 --- /dev/null +++ b/vendor/twig/twig/doc/filters/url_encode.rst @@ -0,0 +1,34 @@ +``url_encode`` +============== + +.. versionadded:: 1.12.3 + Support for encoding an array as query string was added in Twig 1.12.3. + +.. versionadded:: 1.16.0 + The ``raw`` argument was removed in Twig 1.16.0. Twig now always encodes + according to RFC 3986. + +The ``url_encode`` filter percent encodes a given string as URL segment +or an array as query string: + +.. code-block:: jinja + + {{ "path-seg*ment"|url_encode }} + {# outputs "path-seg%2Ament" #} + + {{ "string with spaces"|url_encode }} + {# outputs "string%20with%20spaces" #} + + {{ {'param': 'value', 'foo': 'bar'}|url_encode }} + {# outputs "param=value&foo=bar" #} + +.. note:: + + Internally, Twig uses the PHP `urlencode`_ (or `rawurlencode`_ if you pass + ``true`` as the first parameter) or the `http_build_query`_ function. Note + that as of Twig 1.16.0, ``urlencode`` **always** uses ``rawurlencode`` (the + ``raw`` argument was removed.) + +.. _`urlencode`: https://secure.php.net/urlencode +.. _`rawurlencode`: https://secure.php.net/rawurlencode +.. _`http_build_query`: https://secure.php.net/http_build_query diff --git a/vendor/twig/twig/doc/functions/attribute.rst b/vendor/twig/twig/doc/functions/attribute.rst new file mode 100644 index 0000000..ceba96b --- /dev/null +++ b/vendor/twig/twig/doc/functions/attribute.rst @@ -0,0 +1,26 @@ +``attribute`` +============= + +.. versionadded:: 1.2 + The ``attribute`` function was added in Twig 1.2. + +The ``attribute`` function can be used to access a "dynamic" attribute of a +variable: + +.. code-block:: jinja + + {{ attribute(object, method) }} + {{ attribute(object, method, arguments) }} + {{ attribute(array, item) }} + +In addition, the ``defined`` test can check for the existence of a dynamic +attribute: + +.. code-block:: jinja + + {{ attribute(object, method) is defined ? 'Method exists' : 'Method does not exist' }} + +.. note:: + + The resolution algorithm is the same as the one used for the ``.`` + notation, except that the item can be any valid expression. diff --git a/vendor/twig/twig/doc/functions/block.rst b/vendor/twig/twig/doc/functions/block.rst new file mode 100644 index 0000000..6b8f0d4 --- /dev/null +++ b/vendor/twig/twig/doc/functions/block.rst @@ -0,0 +1,41 @@ +``block`` +========= + +.. versionadded: 1.28 + Using ``block`` with the ``defined`` test was added in Twig 1.28. + +.. versionadded: 1.28 + Support for the template argument was added in Twig 1.28. + +When a template uses inheritance and if you want to print a block multiple +times, use the ``block`` function: + +.. code-block:: jinja + + {% block title %}{% endblock %} + +

{{ block('title') }}

+ + {% block body %}{% endblock %} + +The ``block`` function can also be used to display one block from another +template: + +.. code-block:: jinja + + {{ block("title", "common_blocks.twig") }} + +Use the ``defined`` test to check if a block exists in the context of the +current template: + +.. code-block:: jinja + + {% if block("footer") is defined %} + ... + {% endif %} + + {% if block("footer", "common_blocks.twig") is defined %} + ... + {% endif %} + +.. seealso:: :doc:`extends<../tags/extends>`, :doc:`parent<../functions/parent>` diff --git a/vendor/twig/twig/doc/functions/constant.rst b/vendor/twig/twig/doc/functions/constant.rst new file mode 100644 index 0000000..97aa5c8 --- /dev/null +++ b/vendor/twig/twig/doc/functions/constant.rst @@ -0,0 +1,29 @@ +``constant`` +============ + +.. versionadded: 1.12.1 + constant now accepts object instances as the second argument. + +.. versionadded: 1.28 + Using ``constant`` with the ``defined`` test was added in Twig 1.28. + +``constant`` returns the constant value for a given string: + +.. code-block:: jinja + + {{ some_date|date(constant('DATE_W3C')) }} + {{ constant('Namespace\\Classname::CONSTANT_NAME') }} + +As of 1.12.1 you can read constants from object instances as well: + +.. code-block:: jinja + + {{ constant('RSS', date) }} + +Use the ``defined`` test to check if a constant is defined: + +.. code-block:: jinja + + {% if constant('SOME_CONST') is defined %} + ... + {% endif %} diff --git a/vendor/twig/twig/doc/functions/cycle.rst b/vendor/twig/twig/doc/functions/cycle.rst new file mode 100644 index 0000000..e343493 --- /dev/null +++ b/vendor/twig/twig/doc/functions/cycle.rst @@ -0,0 +1,28 @@ +``cycle`` +========= + +The ``cycle`` function cycles on an array of values: + +.. code-block:: jinja + + {% set start_year = date() | date('Y') %} + {% set end_year = start_year + 5 %} + + {% for year in start_year..end_year %} + {{ cycle(['odd', 'even'], loop.index0) }} + {% endfor %} + +The array can contain any number of values: + +.. code-block:: jinja + + {% set fruits = ['apple', 'orange', 'citrus'] %} + + {% for i in 0..10 %} + {{ cycle(fruits, i) }} + {% endfor %} + +Arguments +--------- + +* ``position``: The cycle position diff --git a/vendor/twig/twig/doc/functions/date.rst b/vendor/twig/twig/doc/functions/date.rst new file mode 100644 index 0000000..7801ad8 --- /dev/null +++ b/vendor/twig/twig/doc/functions/date.rst @@ -0,0 +1,55 @@ +``date`` +======== + +.. versionadded:: 1.6 + The date function has been added in Twig 1.6. + +.. versionadded:: 1.6.1 + The default timezone support has been added in Twig 1.6.1. + +Converts an argument to a date to allow date comparison: + +.. code-block:: jinja + + {% if date(user.created_at) < date('-2days') %} + {# do something #} + {% endif %} + +The argument must be in one of PHP’s supported `date and time formats`_. + +You can pass a timezone as the second argument: + +.. code-block:: jinja + + {% if date(user.created_at) < date('-2days', 'Europe/Paris') %} + {# do something #} + {% endif %} + +If no argument is passed, the function returns the current date: + +.. code-block:: jinja + + {% if date(user.created_at) < date() %} + {# always! #} + {% endif %} + +.. note:: + + You can set the default timezone globally by calling ``setTimezone()`` on + the ``core`` extension instance: + + .. code-block:: php + + $twig = new Twig_Environment($loader); + $twig->getExtension('Twig_Extension_Core')->setTimezone('Europe/Paris'); + + // before Twig 1.26 + $twig->getExtension('core')->setTimezone('Europe/Paris'); + +Arguments +--------- + +* ``date``: The date +* ``timezone``: The timezone + +.. _`date and time formats`: https://secure.php.net/manual/en/datetime.formats.php diff --git a/vendor/twig/twig/doc/functions/dump.rst b/vendor/twig/twig/doc/functions/dump.rst new file mode 100644 index 0000000..611b979 --- /dev/null +++ b/vendor/twig/twig/doc/functions/dump.rst @@ -0,0 +1,69 @@ +``dump`` +======== + +.. versionadded:: 1.5 + The ``dump`` function was added in Twig 1.5. + +The ``dump`` function dumps information about a template variable. This is +mostly useful to debug a template that does not behave as expected by +introspecting its variables: + +.. code-block:: jinja + + {{ dump(user) }} + +.. note:: + + The ``dump`` function is not available by default. You must add the + ``Twig_Extension_Debug`` extension explicitly when creating your Twig + environment:: + + $twig = new Twig_Environment($loader, array( + 'debug' => true, + // ... + )); + $twig->addExtension(new Twig_Extension_Debug()); + + Even when enabled, the ``dump`` function won't display anything if the + ``debug`` option on the environment is not enabled (to avoid leaking debug + information on a production server). + +In an HTML context, wrap the output with a ``pre`` tag to make it easier to +read: + +.. code-block:: jinja + +
+        {{ dump(user) }}
+    
+ +.. tip:: + + Using a ``pre`` tag is not needed when `XDebug`_ is enabled and + ``html_errors`` is ``on``; as a bonus, the output is also nicer with + XDebug enabled. + +You can debug several variables by passing them as additional arguments: + +.. code-block:: jinja + + {{ dump(user, categories) }} + +If you don't pass any value, all variables from the current context are +dumped: + +.. code-block:: jinja + + {{ dump() }} + +.. note:: + + Internally, Twig uses the PHP `var_dump`_ function. + +Arguments +--------- + +* ``context``: The context to dump + +.. _`XDebug`: https://xdebug.org/docs/display +.. _`var_dump`: https://secure.php.net/var_dump diff --git a/vendor/twig/twig/doc/functions/include.rst b/vendor/twig/twig/doc/functions/include.rst new file mode 100644 index 0000000..2f88ed7 --- /dev/null +++ b/vendor/twig/twig/doc/functions/include.rst @@ -0,0 +1,84 @@ +``include`` +=========== + +.. versionadded:: 1.12 + The ``include`` function was added in Twig 1.12. + +The ``include`` function returns the rendered content of a template: + +.. code-block:: jinja + + {{ include('template.html') }} + {{ include(some_var) }} + +Included templates have access to the variables of the active context. + +If you are using the filesystem loader, the templates are looked for in the +paths defined by it. + +The context is passed by default to the template but you can also pass +additional variables: + +.. code-block:: jinja + + {# template.html will have access to the variables from the current context and the additional ones provided #} + {{ include('template.html', {foo: 'bar'}) }} + +You can disable access to the context by setting ``with_context`` to +``false``: + +.. code-block:: jinja + + {# only the foo variable will be accessible #} + {{ include('template.html', {foo: 'bar'}, with_context = false) }} + +.. code-block:: jinja + + {# no variables will be accessible #} + {{ include('template.html', with_context = false) }} + +And if the expression evaluates to a ``Twig_Template`` or a +``Twig_TemplateWrapper`` instance, Twig will use it directly:: + + // {{ include(template) }} + + // deprecated as of Twig 1.28 + $template = $twig->loadTemplate('some_template.twig'); + + // as of Twig 1.28 + $template = $twig->load('some_template.twig'); + + $twig->display('template.twig', array('template' => $template)); + +When you set the ``ignore_missing`` flag, Twig will return an empty string if +the template does not exist: + +.. code-block:: jinja + + {{ include('sidebar.html', ignore_missing = true) }} + +You can also provide a list of templates that are checked for existence before +inclusion. The first template that exists will be rendered: + +.. code-block:: jinja + + {{ include(['page_detailed.html', 'page.html']) }} + +If ``ignore_missing`` is set, it will fall back to rendering nothing if none +of the templates exist, otherwise it will throw an exception. + +When including a template created by an end user, you should consider +sandboxing it: + +.. code-block:: jinja + + {{ include('page.html', sandboxed = true) }} + +Arguments +--------- + +* ``template``: The template to render +* ``variables``: The variables to pass to the template +* ``with_context``: Whether to pass the current context variables or not +* ``ignore_missing``: Whether to ignore missing templates or not +* ``sandboxed``: Whether to sandbox the template or not diff --git a/vendor/twig/twig/doc/functions/index.rst b/vendor/twig/twig/doc/functions/index.rst new file mode 100644 index 0000000..07214a7 --- /dev/null +++ b/vendor/twig/twig/doc/functions/index.rst @@ -0,0 +1,20 @@ +Functions +========= + +.. toctree:: + :maxdepth: 1 + + attribute + block + constant + cycle + date + dump + include + max + min + parent + random + range + source + template_from_string diff --git a/vendor/twig/twig/doc/functions/max.rst b/vendor/twig/twig/doc/functions/max.rst new file mode 100644 index 0000000..6f3cfc5 --- /dev/null +++ b/vendor/twig/twig/doc/functions/max.rst @@ -0,0 +1,20 @@ +``max`` +======= + +.. versionadded:: 1.15 + The ``max`` function was added in Twig 1.15. + +``max`` returns the biggest value of a sequence or a set of values: + +.. code-block:: jinja + + {{ max(1, 3, 2) }} + {{ max([1, 3, 2]) }} + +When called with a mapping, max ignores keys and only compares values: + +.. code-block:: jinja + + {{ max({2: "e", 1: "a", 3: "b", 5: "d", 4: "c"}) }} + {# returns "e" #} + diff --git a/vendor/twig/twig/doc/functions/min.rst b/vendor/twig/twig/doc/functions/min.rst new file mode 100644 index 0000000..7b6a65e --- /dev/null +++ b/vendor/twig/twig/doc/functions/min.rst @@ -0,0 +1,20 @@ +``min`` +======= + +.. versionadded:: 1.15 + The ``min`` function was added in Twig 1.15. + +``min`` returns the lowest value of a sequence or a set of values: + +.. code-block:: jinja + + {{ min(1, 3, 2) }} + {{ min([1, 3, 2]) }} + +When called with a mapping, min ignores keys and only compares values: + +.. code-block:: jinja + + {{ min({2: "e", 3: "a", 1: "b", 5: "d", 4: "c"}) }} + {# returns "a" #} + diff --git a/vendor/twig/twig/doc/functions/parent.rst b/vendor/twig/twig/doc/functions/parent.rst new file mode 100644 index 0000000..f5bd200 --- /dev/null +++ b/vendor/twig/twig/doc/functions/parent.rst @@ -0,0 +1,20 @@ +``parent`` +========== + +When a template uses inheritance, it's possible to render the contents of the +parent block when overriding a block by using the ``parent`` function: + +.. code-block:: jinja + + {% extends "base.html" %} + + {% block sidebar %} +

Table Of Contents

+ ... + {{ parent() }} + {% endblock %} + +The ``parent()`` call will return the content of the ``sidebar`` block as +defined in the ``base.html`` template. + +.. seealso:: :doc:`extends<../tags/extends>`, :doc:`block<../functions/block>`, :doc:`block<../tags/block>` diff --git a/vendor/twig/twig/doc/functions/random.rst b/vendor/twig/twig/doc/functions/random.rst new file mode 100644 index 0000000..57015b8 --- /dev/null +++ b/vendor/twig/twig/doc/functions/random.rst @@ -0,0 +1,29 @@ +``random`` +========== + +.. versionadded:: 1.5 + The ``random`` function was added in Twig 1.5. + +.. versionadded:: 1.6 + String and integer handling was added in Twig 1.6. + +The ``random`` function returns a random value depending on the supplied +parameter type: + +* a random item from a sequence; +* a random character from a string; +* a random integer between 0 and the integer parameter (inclusive). + +.. code-block:: jinja + + {{ random(['apple', 'orange', 'citrus']) }} {# example output: orange #} + {{ random('ABC') }} {# example output: C #} + {{ random() }} {# example output: 15386094 (works as the native PHP mt_rand function) #} + {{ random(5) }} {# example output: 3 #} + +Arguments +--------- + +* ``values``: The values + +.. _`mt_rand`: https://secure.php.net/mt_rand diff --git a/vendor/twig/twig/doc/functions/range.rst b/vendor/twig/twig/doc/functions/range.rst new file mode 100644 index 0000000..38d2824 --- /dev/null +++ b/vendor/twig/twig/doc/functions/range.rst @@ -0,0 +1,58 @@ +``range`` +========= + +Returns a list containing an arithmetic progression of integers: + +.. code-block:: jinja + + {% for i in range(0, 3) %} + {{ i }}, + {% endfor %} + + {# outputs 0, 1, 2, 3, #} + +When step is given (as the third parameter), it specifies the increment (or +decrement for negative values): + +.. code-block:: jinja + + {% for i in range(0, 6, 2) %} + {{ i }}, + {% endfor %} + + {# outputs 0, 2, 4, 6, #} + +.. note:: + + Note that if the start is greater than the end, ``range`` assumes a step of + ``-1``: + + .. code-block:: jinja + + {% for i in range(3, 0) %} + {{ i }}, + {% endfor %} + + {# outputs 3, 2, 1, 0, #} + +The Twig built-in ``..`` operator is just syntactic sugar for the ``range`` +function (with a step of ``1``, or ``-1`` if the start is greater than the end): + +.. code-block:: jinja + + {% for i in 0..3 %} + {{ i }}, + {% endfor %} + +.. tip:: + + The ``range`` function works as the native PHP `range`_ function. + +Arguments +--------- + +* ``low``: The first value of the sequence. +* ``high``: The highest possible value of the sequence. +* ``step``: The increment between elements of the sequence. + +.. _`range`: https://secure.php.net/range diff --git a/vendor/twig/twig/doc/functions/source.rst b/vendor/twig/twig/doc/functions/source.rst new file mode 100644 index 0000000..3c921b1 --- /dev/null +++ b/vendor/twig/twig/doc/functions/source.rst @@ -0,0 +1,32 @@ +``source`` +========== + +.. versionadded:: 1.15 + The ``source`` function was added in Twig 1.15. + +.. versionadded:: 1.18.3 + The ``ignore_missing`` flag was added in Twig 1.18.3. + +The ``source`` function returns the content of a template without rendering it: + +.. code-block:: jinja + + {{ source('template.html') }} + {{ source(some_var) }} + +When you set the ``ignore_missing`` flag, Twig will return an empty string if +the template does not exist: + +.. code-block:: jinja + + {{ source('template.html', ignore_missing = true) }} + +The function uses the same template loaders as the ones used to include +templates. So, if you are using the filesystem loader, the templates are looked +for in the paths defined by it. + +Arguments +--------- + +* ``name``: The name of the template to read +* ``ignore_missing``: Whether to ignore missing templates or not diff --git a/vendor/twig/twig/doc/functions/template_from_string.rst b/vendor/twig/twig/doc/functions/template_from_string.rst new file mode 100644 index 0000000..ce6a60d --- /dev/null +++ b/vendor/twig/twig/doc/functions/template_from_string.rst @@ -0,0 +1,32 @@ +``template_from_string`` +======================== + +.. versionadded:: 1.11 + The ``template_from_string`` function was added in Twig 1.11. + +The ``template_from_string`` function loads a template from a string: + +.. code-block:: jinja + + {{ include(template_from_string("Hello {{ name }}")) }} + {{ include(template_from_string(page.template)) }} + +.. note:: + + The ``template_from_string`` function is not available by default. You + must add the ``Twig_Extension_StringLoader`` extension explicitly when + creating your Twig environment:: + + $twig = new Twig_Environment(...); + $twig->addExtension(new Twig_Extension_StringLoader()); + +.. note:: + + Even if you will probably always use the ``template_from_string`` function + with the ``include`` function, you can use it with any tag or function that + takes a template as an argument (like the ``embed`` or ``extends`` tags). + +Arguments +--------- + +* ``template``: The template diff --git a/vendor/twig/twig/doc/index.rst b/vendor/twig/twig/doc/index.rst new file mode 100644 index 0000000..358bd73 --- /dev/null +++ b/vendor/twig/twig/doc/index.rst @@ -0,0 +1,19 @@ +Twig +==== + +.. toctree:: + :maxdepth: 2 + + intro + installation + templates + api + advanced + internals + deprecated + recipes + coding_standards + tags/index + filters/index + functions/index + tests/index diff --git a/vendor/twig/twig/doc/installation.rst b/vendor/twig/twig/doc/installation.rst new file mode 100644 index 0000000..860f261 --- /dev/null +++ b/vendor/twig/twig/doc/installation.rst @@ -0,0 +1,116 @@ +Installation +============ + +You have multiple ways to install Twig. + +Installing the Twig PHP package +------------------------------- + +Installing via Composer (recommended) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Install `Composer`_ and run the following command to get the latest version: + +.. code-block:: bash + + composer require twig/twig:~1.0 + +Installing from the tarball release +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +1. Download the most recent tarball from the `download page`_ +2. Verify the integrity of the tarball http://fabien.potencier.org/article/73/signing-project-releases +3. Unpack the tarball +4. Move the files somewhere in your project + +Installing the development version +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. code-block:: bash + + git clone git://github.com/twigphp/Twig.git + +Installing the PEAR package +~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +.. note:: + + Using PEAR for installing Twig is deprecated and Twig 1.15.1 was the last + version published on the PEAR channel; use Composer instead. + +.. code-block:: bash + + pear channel-discover pear.twig-project.org + pear install twig/Twig + +Installing the C extension +-------------------------- + +.. versionadded:: 1.4 + The C extension was added in Twig 1.4. + +.. note:: + + The C extension is **optional** but it brings some nice performance + improvements. Note that the extension is not a replacement for the PHP + code; it only implements a small part of the PHP code to improve the + performance at runtime; you must still install the regular PHP code. + +Twig comes with a C extension that enhances the performance of the Twig +runtime engine; install it like any other PHP extensions: + +.. code-block:: bash + + cd ext/twig + phpize + ./configure + make + make install + +.. note:: + + You can also install the C extension via PEAR (note that this method is + deprecated and newer versions of Twig are not available on the PEAR + channel): + + .. code-block:: bash + + pear channel-discover pear.twig-project.org + pear install twig/CTwig + +For Windows: + +1. Setup the build environment following the `PHP documentation`_ +2. Put Twig's C extension source code into ``C:\php-sdk\phpdev\vcXX\x86\php-source-directory\ext\twig`` +3. Use the ``configure --disable-all --enable-cli --enable-twig=shared`` command instead of step 14 +4. ``nmake`` +5. Copy the ``C:\php-sdk\phpdev\vcXX\x86\php-source-directory\Release_TS\php_twig.dll`` file to your PHP setup. + +.. tip:: + + For Windows ZendServer, ZTS is not enabled as mentioned in `Zend Server + FAQ`_. + + You have to use ``configure --disable-all --disable-zts --enable-cli + --enable-twig=shared`` to be able to build the twig C extension for + ZendServer. + + The built DLL will be available in + ``C:\\php-sdk\\phpdev\\vcXX\\x86\\php-source-directory\\Release`` + +Finally, enable the extension in your ``php.ini`` configuration file: + +.. code-block:: ini + + extension=twig.so #For Unix systems + extension=php_twig.dll #For Windows systems + +And from now on, Twig will automatically compile your templates to take +advantage of the C extension. Note that this extension does not replace the +PHP code but only provides an optimized version of the +``Twig_Template::getAttribute()`` method. + +.. _`download page`: https://github.com/twigphp/Twig/tags +.. _`Composer`: https://getcomposer.org/download/ +.. _`PHP documentation`: https://wiki.php.net/internals/windows/stepbystepbuild +.. _`Zend Server FAQ`: https://www.zend.com/en/products/server/faq#faqD6 diff --git a/vendor/twig/twig/doc/internals.rst b/vendor/twig/twig/doc/internals.rst new file mode 100644 index 0000000..fec65e0 --- /dev/null +++ b/vendor/twig/twig/doc/internals.rst @@ -0,0 +1,142 @@ +Twig Internals +============== + +Twig is very extensible and you can easily hack it. Keep in mind that you +should probably try to create an extension before hacking the core, as most +features and enhancements can be handled with extensions. This chapter is also +useful for people who want to understand how Twig works under the hood. + +How does Twig work? +------------------- + +The rendering of a Twig template can be summarized into four key steps: + +* **Load** the template: If the template is already compiled, load it and go + to the *evaluation* step, otherwise: + + * First, the **lexer** tokenizes the template source code into small pieces + for easier processing; + * Then, the **parser** converts the token stream into a meaningful tree + of nodes (the Abstract Syntax Tree); + * Eventually, the *compiler* transforms the AST into PHP code. + +* **Evaluate** the template: It basically means calling the ``display()`` + method of the compiled template and passing it the context. + +The Lexer +--------- + +The lexer tokenizes a template source code into a token stream (each token is +an instance of ``Twig_Token``, and the stream is an instance of +``Twig_TokenStream``). The default lexer recognizes 13 different token types: + +* ``Twig_Token::BLOCK_START_TYPE``, ``Twig_Token::BLOCK_END_TYPE``: Delimiters for blocks (``{% %}``) +* ``Twig_Token::VAR_START_TYPE``, ``Twig_Token::VAR_END_TYPE``: Delimiters for variables (``{{ }}``) +* ``Twig_Token::TEXT_TYPE``: A text outside an expression; +* ``Twig_Token::NAME_TYPE``: A name in an expression; +* ``Twig_Token::NUMBER_TYPE``: A number in an expression; +* ``Twig_Token::STRING_TYPE``: A string in an expression; +* ``Twig_Token::OPERATOR_TYPE``: An operator; +* ``Twig_Token::PUNCTUATION_TYPE``: A punctuation sign; +* ``Twig_Token::INTERPOLATION_START_TYPE``, ``Twig_Token::INTERPOLATION_END_TYPE`` (as of Twig 1.5): Delimiters for string interpolation; +* ``Twig_Token::EOF_TYPE``: Ends of template. + +You can manually convert a source code into a token stream by calling the +``tokenize()`` method of an environment:: + + $stream = $twig->tokenize(new Twig_Source($source, $identifier)); + +.. versionadded:: 1.27 + ``Twig_Source`` was introduced in version 1.27, pass the source and the + identifier directly on previous versions. + +As the stream has a ``__toString()`` method, you can have a textual +representation of it by echoing the object:: + + echo $stream."\n"; + +Here is the output for the ``Hello {{ name }}`` template: + +.. code-block:: text + + TEXT_TYPE(Hello ) + VAR_START_TYPE() + NAME_TYPE(name) + VAR_END_TYPE() + EOF_TYPE() + +.. note:: + + The default lexer (``Twig_Lexer``) can be changed by calling + the ``setLexer()`` method:: + + $twig->setLexer($lexer); + +The Parser +---------- + +The parser converts the token stream into an AST (Abstract Syntax Tree), or a +node tree (an instance of ``Twig_Node_Module``). The core extension defines +the basic nodes like: ``for``, ``if``, ... and the expression nodes. + +You can manually convert a token stream into a node tree by calling the +``parse()`` method of an environment:: + + $nodes = $twig->parse($stream); + +Echoing the node object gives you a nice representation of the tree:: + + echo $nodes."\n"; + +Here is the output for the ``Hello {{ name }}`` template: + +.. code-block:: text + + Twig_Node_Module( + Twig_Node_Text(Hello ) + Twig_Node_Print( + Twig_Node_Expression_Name(name) + ) + ) + +.. note:: + + The default parser (``Twig_TokenParser``) can be changed by calling the + ``setParser()`` method:: + + $twig->setParser($parser); + +The Compiler +------------ + +The last step is done by the compiler. It takes a node tree as an input and +generates PHP code usable for runtime execution of the template. + +You can manually compile a node tree to PHP code with the ``compile()`` method +of an environment:: + + $php = $twig->compile($nodes); + +The generated template for a ``Hello {{ name }}`` template reads as follows +(the actual output can differ depending on the version of Twig you are +using):: + + /* Hello {{ name }} */ + class __TwigTemplate_1121b6f109fe93ebe8c6e22e3712bceb extends Twig_Template + { + protected function doDisplay(array $context, array $blocks = array()) + { + // line 1 + echo "Hello "; + echo twig_escape_filter($this->env, (isset($context["name"]) ? $context["name"] : null), "html", null, true); + } + + // some more code + } + +.. note:: + + The default compiler (``Twig_Compiler``) can be changed by calling the + ``setCompiler()`` method:: + + $twig->setCompiler($compiler); diff --git a/vendor/twig/twig/doc/intro.rst b/vendor/twig/twig/doc/intro.rst new file mode 100644 index 0000000..d631430 --- /dev/null +++ b/vendor/twig/twig/doc/intro.rst @@ -0,0 +1,86 @@ +Introduction +============ + +This is the documentation for Twig, the flexible, fast, and secure template +engine for PHP. + +If you have any exposure to other text-based template languages, such as +Smarty, Django, or Jinja, you should feel right at home with Twig. It's both +designer and developer friendly by sticking to PHP's principles and adding +functionality useful for templating environments. + +The key-features are... + +* *Fast*: Twig compiles templates down to plain optimized PHP code. The + overhead compared to regular PHP code was reduced to the very minimum. + +* *Secure*: Twig has a sandbox mode to evaluate untrusted template code. This + allows Twig to be used as a template language for applications where users + may modify the template design. + +* *Flexible*: Twig is powered by a flexible lexer and parser. This allows the + developer to define their own custom tags and filters, and to create their own DSL. + +Twig is used by many Open-Source projects like Symfony, Drupal8, eZPublish, +phpBB, Piwik, OroCRM; and many frameworks have support for it as well like +Slim, Yii, Laravel, Codeigniter and Kohana — just to name a few. + +Prerequisites +------------- + +Twig needs at least **PHP 5.2.7** to run. As of 1.34, the minimum requirement +was bumped to **PHP 5.3.3**. + +Installation +------------ + +The recommended way to install Twig is via Composer: + +.. code-block:: bash + + composer require "twig/twig:~1.0" + +.. note:: + + To learn more about the other installation methods, read the + :doc:`installation` chapter; it also explains how to install + the Twig C extension. + +Basic API Usage +--------------- + +This section gives you a brief introduction to the PHP API for Twig. + +.. code-block:: php + + require_once '/path/to/vendor/autoload.php'; + + $loader = new Twig_Loader_Array(array( + 'index' => 'Hello {{ name }}!', + )); + $twig = new Twig_Environment($loader); + + echo $twig->render('index', array('name' => 'Fabien')); + +Twig uses a loader (``Twig_Loader_Array``) to locate templates, and an +environment (``Twig_Environment``) to store the configuration. + +The ``render()`` method loads the template passed as a first argument and +renders it with the variables passed as a second argument. + +As templates are generally stored on the filesystem, Twig also comes with a +filesystem loader:: + + $loader = new Twig_Loader_Filesystem('/path/to/templates'); + $twig = new Twig_Environment($loader, array( + 'cache' => '/path/to/compilation_cache', + )); + + echo $twig->render('index.html', array('name' => 'Fabien')); + +.. tip:: + + If you are not using Composer, use the Twig built-in autoloader:: + + require_once '/path/to/lib/Twig/Autoloader.php'; + Twig_Autoloader::register(); diff --git a/vendor/twig/twig/doc/recipes.rst b/vendor/twig/twig/doc/recipes.rst new file mode 100644 index 0000000..8f46da5 --- /dev/null +++ b/vendor/twig/twig/doc/recipes.rst @@ -0,0 +1,568 @@ +Recipes +======= + +.. _deprecation-notices: + +Displaying Deprecation Notices +------------------------------ + +.. versionadded:: 1.21 + This works as of Twig 1.21. + +Deprecated features generate deprecation notices (via a call to the +``trigger_error()`` PHP function). By default, they are silenced and never +displayed nor logged. + +To easily remove all deprecated feature usages from your templates, write and +run a script along the lines of the following:: + + require_once __DIR__.'/vendor/autoload.php'; + + $twig = create_your_twig_env(); + + $deprecations = new Twig_Util_DeprecationCollector($twig); + + print_r($deprecations->collectDir(__DIR__.'/templates')); + +The ``collectDir()`` method compiles all templates found in a directory, +catches deprecation notices, and return them. + +.. tip:: + + If your templates are not stored on the filesystem, use the ``collect()`` + method instead. ``collect()`` takes a ``Traversable`` which must return + template names as keys and template contents as values (as done by + ``Twig_Util_TemplateDirIterator``). + +However, this code won't find all deprecations (like using deprecated some Twig +classes). To catch all notices, register a custom error handler like the one +below:: + + $deprecations = array(); + set_error_handler(function ($type, $msg) use (&$deprecations) { + if (E_USER_DEPRECATED === $type) { + $deprecations[] = $msg; + } + }); + + // run your application + + print_r($deprecations); + +Note that most deprecation notices are triggered during **compilation**, so +they won't be generated when templates are already cached. + +.. tip:: + + If you want to manage the deprecation notices from your PHPUnit tests, have + a look at the `symfony/phpunit-bridge + `_ package, which eases the + process a lot. + +Making a Layout conditional +--------------------------- + +Working with Ajax means that the same content is sometimes displayed as is, +and sometimes decorated with a layout. As Twig layout template names can be +any valid expression, you can pass a variable that evaluates to ``true`` when +the request is made via Ajax and choose the layout accordingly: + +.. code-block:: jinja + + {% extends request.ajax ? "base_ajax.html" : "base.html" %} + + {% block content %} + This is the content to be displayed. + {% endblock %} + +Making an Include dynamic +------------------------- + +When including a template, its name does not need to be a string. For +instance, the name can depend on the value of a variable: + +.. code-block:: jinja + + {% include var ~ '_foo.html' %} + +If ``var`` evaluates to ``index``, the ``index_foo.html`` template will be +rendered. + +As a matter of fact, the template name can be any valid expression, such as +the following: + +.. code-block:: jinja + + {% include var|default('index') ~ '_foo.html' %} + +Overriding a Template that also extends itself +---------------------------------------------- + +A template can be customized in two different ways: + +* *Inheritance*: A template *extends* a parent template and overrides some + blocks; + +* *Replacement*: If you use the filesystem loader, Twig loads the first + template it finds in a list of configured directories; a template found in a + directory *replaces* another one from a directory further in the list. + +But how do you combine both: *replace* a template that also extends itself +(aka a template in a directory further in the list)? + +Let's say that your templates are loaded from both ``.../templates/mysite`` +and ``.../templates/default`` in this order. The ``page.twig`` template, +stored in ``.../templates/default`` reads as follows: + +.. code-block:: jinja + + {# page.twig #} + {% extends "layout.twig" %} + + {% block content %} + {% endblock %} + +You can replace this template by putting a file with the same name in +``.../templates/mysite``. And if you want to extend the original template, you +might be tempted to write the following: + +.. code-block:: jinja + + {# page.twig in .../templates/mysite #} + {% extends "page.twig" %} {# from .../templates/default #} + +Of course, this will not work as Twig will always load the template from +``.../templates/mysite``. + +It turns out it is possible to get this to work, by adding a directory right +at the end of your template directories, which is the parent of all of the +other directories: ``.../templates`` in our case. This has the effect of +making every template file within our system uniquely addressable. Most of the +time you will use the "normal" paths, but in the special case of wanting to +extend a template with an overriding version of itself we can reference its +parent's full, unambiguous template path in the extends tag: + +.. code-block:: jinja + + {# page.twig in .../templates/mysite #} + {% extends "default/page.twig" %} {# from .../templates #} + +.. note:: + + This recipe was inspired by the following Django wiki page: + https://code.djangoproject.com/wiki/ExtendingTemplates + +Customizing the Syntax +---------------------- + +Twig allows some syntax customization for the block delimiters. It's not +recommended to use this feature as templates will be tied with your custom +syntax. But for specific projects, it can make sense to change the defaults. + +To change the block delimiters, you need to create your own lexer object:: + + $twig = new Twig_Environment(); + + $lexer = new Twig_Lexer($twig, array( + 'tag_comment' => array('{#', '#}'), + 'tag_block' => array('{%', '%}'), + 'tag_variable' => array('{{', '}}'), + 'interpolation' => array('#{', '}'), + )); + $twig->setLexer($lexer); + +Here are some configuration example that simulates some other template engines +syntax:: + + // Ruby erb syntax + $lexer = new Twig_Lexer($twig, array( + 'tag_comment' => array('<%#', '%>'), + 'tag_block' => array('<%', '%>'), + 'tag_variable' => array('<%=', '%>'), + )); + + // SGML Comment Syntax + $lexer = new Twig_Lexer($twig, array( + 'tag_comment' => array(''), + 'tag_block' => array(''), + 'tag_variable' => array('${', '}'), + )); + + // Smarty like + $lexer = new Twig_Lexer($twig, array( + 'tag_comment' => array('{*', '*}'), + 'tag_block' => array('{', '}'), + 'tag_variable' => array('{$', '}'), + )); + +Using dynamic Object Properties +------------------------------- + +When Twig encounters a variable like ``article.title``, it tries to find a +``title`` public property in the ``article`` object. + +It also works if the property does not exist but is rather defined dynamically +thanks to the magic ``__get()`` method; you just need to also implement the +``__isset()`` magic method like shown in the following snippet of code:: + + class Article + { + public function __get($name) + { + if ('title' == $name) { + return 'The title'; + } + + // throw some kind of error + } + + public function __isset($name) + { + if ('title' == $name) { + return true; + } + + return false; + } + } + +Accessing the parent Context in Nested Loops +-------------------------------------------- + +Sometimes, when using nested loops, you need to access the parent context. The +parent context is always accessible via the ``loop.parent`` variable. For +instance, if you have the following template data:: + + $data = array( + 'topics' => array( + 'topic1' => array('Message 1 of topic 1', 'Message 2 of topic 1'), + 'topic2' => array('Message 1 of topic 2', 'Message 2 of topic 2'), + ), + ); + +And the following template to display all messages in all topics: + +.. code-block:: jinja + + {% for topic, messages in topics %} + * {{ loop.index }}: {{ topic }} + {% for message in messages %} + - {{ loop.parent.loop.index }}.{{ loop.index }}: {{ message }} + {% endfor %} + {% endfor %} + +The output will be similar to: + +.. code-block:: text + + * 1: topic1 + - 1.1: The message 1 of topic 1 + - 1.2: The message 2 of topic 1 + * 2: topic2 + - 2.1: The message 1 of topic 2 + - 2.2: The message 2 of topic 2 + +In the inner loop, the ``loop.parent`` variable is used to access the outer +context. So, the index of the current ``topic`` defined in the outer for loop +is accessible via the ``loop.parent.loop.index`` variable. + +Defining undefined Functions and Filters on the Fly +--------------------------------------------------- + +When a function (or a filter) is not defined, Twig defaults to throw a +``Twig_Error_Syntax`` exception. However, it can also call a `callback`_ (any +valid PHP callable) which should return a function (or a filter). + +For filters, register callbacks with ``registerUndefinedFilterCallback()``. +For functions, use ``registerUndefinedFunctionCallback()``:: + + // auto-register all native PHP functions as Twig functions + // don't try this at home as it's not secure at all! + $twig->registerUndefinedFunctionCallback(function ($name) { + if (function_exists($name)) { + return new Twig_SimpleFunction($name, $name); + } + + return false; + }); + +If the callable is not able to return a valid function (or filter), it must +return ``false``. + +If you register more than one callback, Twig will call them in turn until one +does not return ``false``. + +.. tip:: + + As the resolution of functions and filters is done during compilation, + there is no overhead when registering these callbacks. + +Validating the Template Syntax +------------------------------ + +When template code is provided by a third-party (through a web interface for +instance), it might be interesting to validate the template syntax before +saving it. If the template code is stored in a `$template` variable, here is +how you can do it:: + + try { + $twig->parse($twig->tokenize(new Twig_Source($template))); + + // the $template is valid + } catch (Twig_Error_Syntax $e) { + // $template contains one or more syntax errors + } + +If you iterate over a set of files, you can pass the filename to the +``tokenize()`` method to get the filename in the exception message:: + + foreach ($files as $file) { + try { + $twig->parse($twig->tokenize(new Twig_Source($template, $file->getFilename(), $file))); + + // the $template is valid + } catch (Twig_Error_Syntax $e) { + // $template contains one or more syntax errors + } + } + +.. versionadded:: 1.27 + ``Twig_Source`` was introduced in version 1.27, pass the source and the + identifier directly on previous versions. + +.. note:: + + This method won't catch any sandbox policy violations because the policy + is enforced during template rendering (as Twig needs the context for some + checks like allowed methods on objects). + +Refreshing modified Templates when OPcache or APC is enabled +------------------------------------------------------------ + +When using OPcache with ``opcache.validate_timestamps`` set to ``0`` or APC +with ``apc.stat`` set to ``0`` and Twig cache enabled, clearing the template +cache won't update the cache. + +To get around this, force Twig to invalidate the bytecode cache:: + + $twig = new Twig_Environment($loader, array( + 'cache' => new Twig_Cache_Filesystem('/some/cache/path', Twig_Cache_Filesystem::FORCE_BYTECODE_INVALIDATION), + // ... + )); + +.. note:: + + Before Twig 1.22, you should extend ``Twig_Environment`` instead:: + + class OpCacheAwareTwigEnvironment extends Twig_Environment + { + protected function writeCacheFile($file, $content) + { + parent::writeCacheFile($file, $content); + + // Compile cached file into bytecode cache + if (function_exists('opcache_invalidate')) { + opcache_invalidate($file, true); + } elseif (function_exists('apc_compile_file')) { + apc_compile_file($file); + } + } + } + +Reusing a stateful Node Visitor +------------------------------- + +When attaching a visitor to a ``Twig_Environment`` instance, Twig uses it to +visit *all* templates it compiles. If you need to keep some state information +around, you probably want to reset it when visiting a new template. + +This can be easily achieved with the following code:: + + protected $someTemplateState = array(); + + public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Module) { + // reset the state as we are entering a new template + $this->someTemplateState = array(); + } + + // ... + + return $node; + } + +Using a Database to store Templates +----------------------------------- + +If you are developing a CMS, templates are usually stored in a database. This +recipe gives you a simple PDO template loader you can use as a starting point +for your own. + +First, let's create a temporary in-memory SQLite3 database to work with:: + + $dbh = new PDO('sqlite::memory:'); + $dbh->exec('CREATE TABLE templates (name STRING, source STRING, last_modified INTEGER)'); + $base = '{% block content %}{% endblock %}'; + $index = ' + {% extends "base.twig" %} + {% block content %}Hello {{ name }}{% endblock %} + '; + $now = time(); + $dbh->exec("INSERT INTO templates (name, source, last_modified) VALUES ('base.twig', '$base', $now)"); + $dbh->exec("INSERT INTO templates (name, source, last_modified) VALUES ('index.twig', '$index', $now)"); + +We have created a simple ``templates`` table that hosts two templates: +``base.twig`` and ``index.twig``. + +Now, let's define a loader able to use this database:: + + class DatabaseTwigLoader implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface + { + protected $dbh; + + public function __construct(PDO $dbh) + { + $this->dbh = $dbh; + } + + public function getSource($name) + { + if (false === $source = $this->getValue('source', $name)) { + throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name)); + } + + return $source; + } + + // Twig_SourceContextLoaderInterface as of Twig 1.27 + public function getSourceContext($name) + { + if (false === $source = $this->getValue('source', $name)) { + throw new Twig_Error_Loader(sprintf('Template "%s" does not exist.', $name)); + } + + return new Twig_Source($source, $name); + } + + // Twig_ExistsLoaderInterface as of Twig 1.11 + public function exists($name) + { + return $name === $this->getValue('name', $name); + } + + public function getCacheKey($name) + { + return $name; + } + + public function isFresh($name, $time) + { + if (false === $lastModified = $this->getValue('last_modified', $name)) { + return false; + } + + return $lastModified <= $time; + } + + protected function getValue($column, $name) + { + $sth = $this->dbh->prepare('SELECT '.$column.' FROM templates WHERE name = :name'); + $sth->execute(array(':name' => (string) $name)); + + return $sth->fetchColumn(); + } + } + +Finally, here is an example on how you can use it:: + + $loader = new DatabaseTwigLoader($dbh); + $twig = new Twig_Environment($loader); + + echo $twig->render('index.twig', array('name' => 'Fabien')); + +Using different Template Sources +-------------------------------- + +This recipe is the continuation of the previous one. Even if you store the +contributed templates in a database, you might want to keep the original/base +templates on the filesystem. When templates can be loaded from different +sources, you need to use the ``Twig_Loader_Chain`` loader. + +As you can see in the previous recipe, we reference the template in the exact +same way as we would have done it with a regular filesystem loader. This is +the key to be able to mix and match templates coming from the database, the +filesystem, or any other loader for that matter: the template name should be a +logical name, and not the path from the filesystem:: + + $loader1 = new DatabaseTwigLoader($dbh); + $loader2 = new Twig_Loader_Array(array( + 'base.twig' => '{% block content %}{% endblock %}', + )); + $loader = new Twig_Loader_Chain(array($loader1, $loader2)); + + $twig = new Twig_Environment($loader); + + echo $twig->render('index.twig', array('name' => 'Fabien')); + +Now that the ``base.twig`` templates is defined in an array loader, you can +remove it from the database, and everything else will still work as before. + +Loading a Template from a String +-------------------------------- + +From a template, you can easily load a template stored in a string via the +``template_from_string`` function (available as of Twig 1.11 via the +``Twig_Extension_StringLoader`` extension): + +.. code-block:: jinja + + {{ include(template_from_string("Hello {{ name }}")) }} + +From PHP, it's also possible to load a template stored in a string via +``Twig_Environment::createTemplate()`` (available as of Twig 1.18):: + + $template = $twig->createTemplate('hello {{ name }}'); + echo $template->render(array('name' => 'Fabien')); + +.. note:: + + Never use the ``Twig_Loader_String`` loader, which has severe limitations. + +Using Twig and AngularJS in the same Templates +---------------------------------------------- + +Mixing different template syntaxes in the same file is not a recommended +practice as both AngularJS and Twig use the same delimiters in their syntax: +``{{`` and ``}}``. + +Still, if you want to use AngularJS and Twig in the same template, there are +two ways to make it work depending on the amount of AngularJS you need to +include in your templates: + +* Escaping the AngularJS delimiters by wrapping AngularJS sections with the + ``{% verbatim %}`` tag or by escaping each delimiter via ``{{ '{{' }}`` and + ``{{ '}}' }}``; + +* Changing the delimiters of one of the template engines (depending on which + engine you introduced last): + + * For AngularJS, change the interpolation tags using the + ``interpolateProvider`` service, for instance at the module initialization + time: + + .. code-block:: javascript + + angular.module('myApp', []).config(function($interpolateProvider) { + $interpolateProvider.startSymbol('{[').endSymbol(']}'); + }); + + * For Twig, change the delimiters via the ``tag_variable`` Lexer option: + + .. code-block:: php + + $env->setLexer(new Twig_Lexer($env, array( + 'tag_variable' => array('{[', ']}'), + ))); + +.. _callback: https://secure.php.net/manual/en/function.is-callable.php diff --git a/vendor/twig/twig/doc/tags/autoescape.rst b/vendor/twig/twig/doc/tags/autoescape.rst new file mode 100644 index 0000000..8aa8c75 --- /dev/null +++ b/vendor/twig/twig/doc/tags/autoescape.rst @@ -0,0 +1,81 @@ +``autoescape`` +============== + +Whether automatic escaping is enabled or not, you can mark a section of a +template to be escaped or not by using the ``autoescape`` tag: + +.. code-block:: jinja + + {% autoescape %} + Everything will be automatically escaped in this block + using the HTML strategy + {% endautoescape %} + + {% autoescape 'html' %} + Everything will be automatically escaped in this block + using the HTML strategy + {% endautoescape %} + + {% autoescape 'js' %} + Everything will be automatically escaped in this block + using the js escaping strategy + {% endautoescape %} + + {% autoescape false %} + Everything will be outputted as is in this block + {% endautoescape %} + +.. note:: + + Before Twig 1.8, the syntax was different: + + .. code-block:: jinja + + {% autoescape true %} + Everything will be automatically escaped in this block + using the HTML strategy + {% endautoescape %} + + {% autoescape false %} + Everything will be outputted as is in this block + {% endautoescape %} + + {% autoescape true js %} + Everything will be automatically escaped in this block + using the js escaping strategy + {% endautoescape %} + +When automatic escaping is enabled everything is escaped by default except for +values explicitly marked as safe. Those can be marked in the template by using +the :doc:`raw<../filters/raw>` filter: + +.. code-block:: jinja + + {% autoescape %} + {{ safe_value|raw }} + {% endautoescape %} + +Functions returning template data (like :doc:`macros` and +:doc:`parent<../functions/parent>`) always return safe markup. + +.. note:: + + Twig is smart enough to not escape an already escaped value by the + :doc:`escape<../filters/escape>` filter. + +.. note:: + + Twig does not escape static expressions: + + .. code-block:: jinja + + {% set hello = "Hello" %} + {{ hello }} + {{ "world" }} + + Will be rendered "Hello **world**". + +.. note:: + + The chapter :doc:`Twig for Developers<../api>` gives more information + about when and how automatic escaping is applied. diff --git a/vendor/twig/twig/doc/tags/block.rst b/vendor/twig/twig/doc/tags/block.rst new file mode 100644 index 0000000..e380482 --- /dev/null +++ b/vendor/twig/twig/doc/tags/block.rst @@ -0,0 +1,11 @@ +``block`` +========= + +Blocks are used for inheritance and act as placeholders and replacements at +the same time. They are documented in detail in the documentation for the +:doc:`extends<../tags/extends>` tag. + +Block names should consist of alphanumeric characters, and underscores. Dashes +are not permitted. + +.. seealso:: :doc:`block<../functions/block>`, :doc:`parent<../functions/parent>`, :doc:`use<../tags/use>`, :doc:`extends<../tags/extends>` diff --git a/vendor/twig/twig/doc/tags/deprecated.rst b/vendor/twig/twig/doc/tags/deprecated.rst new file mode 100644 index 0000000..f36743f --- /dev/null +++ b/vendor/twig/twig/doc/tags/deprecated.rst @@ -0,0 +1,30 @@ +``deprecated`` +============== + +.. versionadded:: 1.36 and 2.6 + The ``deprecated`` tag was added in Twig 1.36 and 2.6. + +Twig generates a deprecation notice (via a call to the ``trigger_error()`` +PHP function) where the ``deprecated`` tag is used in a template: + +.. code-block:: jinja + + {# base.twig #} + {% deprecated 'The "base.twig" template is deprecated, use "layout.twig" instead.' %} + {% extends 'layout.twig' %} + +Also you can deprecate a block in the following way: + +.. code-block:: jinja + + {% block hey %} + {% deprecated 'The "hey" block is deprecated, use "greet" instead.' %} + {{ block('greet') }} + {% endblock %} + + {% block greet %} + Hey you! + {% endblock %} + +Note that by default, the deprecation notices are silenced and never displayed nor logged. +See :ref:`deprecation-notices` to learn how to handle them. diff --git a/vendor/twig/twig/doc/tags/do.rst b/vendor/twig/twig/doc/tags/do.rst new file mode 100644 index 0000000..1c344e3 --- /dev/null +++ b/vendor/twig/twig/doc/tags/do.rst @@ -0,0 +1,12 @@ +``do`` +====== + +.. versionadded:: 1.5 + The ``do`` tag was added in Twig 1.5. + +The ``do`` tag works exactly like the regular variable expression (``{{ ... +}}``) just that it doesn't print anything: + +.. code-block:: jinja + + {% do 1 + 2 %} diff --git a/vendor/twig/twig/doc/tags/embed.rst b/vendor/twig/twig/doc/tags/embed.rst new file mode 100644 index 0000000..8bca936 --- /dev/null +++ b/vendor/twig/twig/doc/tags/embed.rst @@ -0,0 +1,178 @@ +``embed`` +========= + +.. versionadded:: 1.8 + The ``embed`` tag was added in Twig 1.8. + +The ``embed`` tag combines the behaviour of :doc:`include` and +:doc:`extends`. +It allows you to include another template's contents, just like ``include`` +does. But it also allows you to override any block defined inside the +included template, like when extending a template. + +Think of an embedded template as a "micro layout skeleton". + +.. code-block:: jinja + + {% embed "teasers_skeleton.twig" %} + {# These blocks are defined in "teasers_skeleton.twig" #} + {# and we override them right here: #} + {% block left_teaser %} + Some content for the left teaser box + {% endblock %} + {% block right_teaser %} + Some content for the right teaser box + {% endblock %} + {% endembed %} + +The ``embed`` tag takes the idea of template inheritance to the level of +content fragments. While template inheritance allows for "document skeletons", +which are filled with life by child templates, the ``embed`` tag allows you to +create "skeletons" for smaller units of content and re-use and fill them +anywhere you like. + +Since the use case may not be obvious, let's look at a simplified example. +Imagine a base template shared by multiple HTML pages, defining a single block +named "content": + +.. code-block:: text + + ┌─── page layout ─────────────────────┐ + │ │ + │ ┌── block "content" ──┐ │ + │ │ │ │ + │ │ │ │ + │ │ (child template to │ │ + │ │ put content here) │ │ + │ │ │ │ + │ │ │ │ + │ └─────────────────────┘ │ + │ │ + └─────────────────────────────────────┘ + +Some pages ("foo" and "bar") share the same content structure - +two vertically stacked boxes: + +.. code-block:: text + + ┌─── page layout ─────────────────────┐ + │ │ + │ ┌── block "content" ──┐ │ + │ │ ┌─ block "top" ───┐ │ │ + │ │ │ │ │ │ + │ │ └─────────────────┘ │ │ + │ │ ┌─ block "bottom" ┐ │ │ + │ │ │ │ │ │ + │ │ └─────────────────┘ │ │ + │ └─────────────────────┘ │ + │ │ + └─────────────────────────────────────┘ + +While other pages ("boom" and "baz") share a different content structure - +two boxes side by side: + +.. code-block:: text + + ┌─── page layout ─────────────────────┐ + │ │ + │ ┌── block "content" ──┐ │ + │ │ │ │ + │ │ ┌ block ┐ ┌ block ┐ │ │ + │ │ │"left" │ │"right"│ │ │ + │ │ │ │ │ │ │ │ + │ │ │ │ │ │ │ │ + │ │ └───────┘ └───────┘ │ │ + │ └─────────────────────┘ │ + │ │ + └─────────────────────────────────────┘ + +Without the ``embed`` tag, you have two ways to design your templates: + +* Create two "intermediate" base templates that extend the master layout + template: one with vertically stacked boxes to be used by the "foo" and + "bar" pages and another one with side-by-side boxes for the "boom" and + "baz" pages. + +* Embed the markup for the top/bottom and left/right boxes into each page + template directly. + +These two solutions do not scale well because they each have a major drawback: + +* The first solution may indeed work for this simplified example. But imagine + we add a sidebar, which may again contain different, recurring structures + of content. Now we would need to create intermediate base templates for + all occurring combinations of content structure and sidebar structure... + and so on. + +* The second solution involves duplication of common code with all its negative + consequences: any change involves finding and editing all affected copies + of the structure, correctness has to be verified for each copy, copies may + go out of sync by careless modifications etc. + +In such a situation, the ``embed`` tag comes in handy. The common layout +code can live in a single base template, and the two different content structures, +let's call them "micro layouts" go into separate templates which are embedded +as necessary: + +Page template ``foo.twig``: + +.. code-block:: jinja + + {% extends "layout_skeleton.twig" %} + + {% block content %} + {% embed "vertical_boxes_skeleton.twig" %} + {% block top %} + Some content for the top box + {% endblock %} + + {% block bottom %} + Some content for the bottom box + {% endblock %} + {% endembed %} + {% endblock %} + +And here is the code for ``vertical_boxes_skeleton.twig``: + +.. code-block:: html+jinja + +
+ {% block top %} + Top box default content + {% endblock %} +
+ +
+ {% block bottom %} + Bottom box default content + {% endblock %} +
+ +The goal of the ``vertical_boxes_skeleton.twig`` template being to factor +out the HTML markup for the boxes. + +The ``embed`` tag takes the exact same arguments as the ``include`` tag: + +.. code-block:: jinja + + {% embed "base" with {'foo': 'bar'} %} + ... + {% endembed %} + + {% embed "base" with {'foo': 'bar'} only %} + ... + {% endembed %} + + {% embed "base" ignore missing %} + ... + {% endembed %} + +.. warning:: + + As embedded templates do not have "names", auto-escaping strategies based + on the template name won't work as expected if you change the context (for + instance, if you embed a CSS/JavaScript template into an HTML one). In that + case, explicitly set the default auto-escaping strategy with the + ``autoescape`` tag. + +.. seealso:: :doc:`include<../tags/include>` diff --git a/vendor/twig/twig/doc/tags/extends.rst b/vendor/twig/twig/doc/tags/extends.rst new file mode 100644 index 0000000..8bf29c4 --- /dev/null +++ b/vendor/twig/twig/doc/tags/extends.rst @@ -0,0 +1,272 @@ +``extends`` +=========== + +The ``extends`` tag can be used to extend a template from another one. + +.. note:: + + Like PHP, Twig does not support multiple inheritance. So you can only have + one extends tag called per rendering. However, Twig supports horizontal + :doc:`reuse`. + +Let's define a base template, ``base.html``, which defines a simple HTML +skeleton document: + +.. code-block:: html+jinja + + + + + {% block head %} + + {% block title %}{% endblock %} - My Webpage + {% endblock %} + + +
{% block content %}{% endblock %}
+ + + + +In this example, the :doc:`block` tags define four blocks that child +templates can fill in. + +All the ``block`` tag does is to tell the template engine that a child +template may override those portions of the template. + +Child Template +-------------- + +A child template might look like this: + +.. code-block:: jinja + + {% extends "base.html" %} + + {% block title %}Index{% endblock %} + {% block head %} + {{ parent() }} + + {% endblock %} + {% block content %} +

Index

+

+ Welcome on my awesome homepage. +

+ {% endblock %} + +The ``extends`` tag is the key here. It tells the template engine that this +template "extends" another template. When the template system evaluates this +template, first it locates the parent. The extends tag should be the first tag +in the template. + +Note that since the child template doesn't define the ``footer`` block, the +value from the parent template is used instead. + +You can't define multiple ``block`` tags with the same name in the same +template. This limitation exists because a block tag works in "both" +directions. That is, a block tag doesn't just provide a hole to fill - it also +defines the content that fills the hole in the *parent*. If there were two +similarly-named ``block`` tags in a template, that template's parent wouldn't +know which one of the blocks' content to use. + +If you want to print a block multiple times you can however use the +``block`` function: + +.. code-block:: jinja + + {% block title %}{% endblock %} +

{{ block('title') }}

+ {% block body %}{% endblock %} + +Parent Blocks +------------- + +It's possible to render the contents of the parent block by using the +:doc:`parent<../functions/parent>` function. This gives back the results of +the parent block: + +.. code-block:: jinja + + {% block sidebar %} +

Table Of Contents

+ ... + {{ parent() }} + {% endblock %} + +Named Block End-Tags +-------------------- + +Twig allows you to put the name of the block after the end tag for better +readability: + +.. code-block:: jinja + + {% block sidebar %} + {% block inner_sidebar %} + ... + {% endblock inner_sidebar %} + {% endblock sidebar %} + +Of course, the name after the ``endblock`` word must match the block name. + +Block Nesting and Scope +----------------------- + +Blocks can be nested for more complex layouts. Per default, blocks have access +to variables from outer scopes: + +.. code-block:: jinja + + {% for item in seq %} +
  • {% block loop_item %}{{ item }}{% endblock %}
  • + {% endfor %} + +Block Shortcuts +--------------- + +For blocks with little content, it's possible to use a shortcut syntax. The +following constructs do the same thing: + +.. code-block:: jinja + + {% block title %} + {{ page_title|title }} + {% endblock %} + +.. code-block:: jinja + + {% block title page_title|title %} + +Dynamic Inheritance +------------------- + +Twig supports dynamic inheritance by using a variable as the base template: + +.. code-block:: jinja + + {% extends some_var %} + +If the variable evaluates to a ``Twig_Template`` or a ``Twig_TemplateWrapper`` +instance, Twig will use it as the parent template:: + + // {% extends layout %} + + // deprecated as of Twig 1.28 + $layout = $twig->loadTemplate('some_layout_template.twig'); + + // as of Twig 1.28 + $layout = $twig->load('some_layout_template.twig'); + + $twig->display('template.twig', array('layout' => $layout)); + +.. versionadded:: 1.2 + The possibility to pass an array of templates has been added in Twig 1.2. + +You can also provide a list of templates that are checked for existence. The +first template that exists will be used as a parent: + +.. code-block:: jinja + + {% extends ['layout.html', 'base_layout.html'] %} + +Conditional Inheritance +----------------------- + +As the template name for the parent can be any valid Twig expression, it's +possible to make the inheritance mechanism conditional: + +.. code-block:: jinja + + {% extends standalone ? "minimum.html" : "base.html" %} + +In this example, the template will extend the "minimum.html" layout template +if the ``standalone`` variable evaluates to ``true``, and "base.html" +otherwise. + +How do blocks work? +------------------- + +A block provides a way to change how a certain part of a template is rendered +but it does not interfere in any way with the logic around it. + +Let's take the following example to illustrate how a block works and more +importantly, how it does not work: + +.. code-block:: jinja + + {# base.twig #} + + {% for post in posts %} + {% block post %} +

    {{ post.title }}

    +

    {{ post.body }}

    + {% endblock %} + {% endfor %} + +If you render this template, the result would be exactly the same with or +without the ``block`` tag. The ``block`` inside the ``for`` loop is just a way +to make it overridable by a child template: + +.. code-block:: jinja + + {# child.twig #} + + {% extends "base.twig" %} + + {% block post %} +
    +
    {{ post.title }}
    +
    {{ post.text }}
    +
    + {% endblock %} + +Now, when rendering the child template, the loop is going to use the block +defined in the child template instead of the one defined in the base one; the +executed template is then equivalent to the following one: + +.. code-block:: jinja + + {% for post in posts %} +
    +
    {{ post.title }}
    +
    {{ post.text }}
    +
    + {% endfor %} + +Let's take another example: a block included within an ``if`` statement: + +.. code-block:: jinja + + {% if posts is empty %} + {% block head %} + {{ parent() }} + + + {% endblock head %} + {% endif %} + +Contrary to what you might think, this template does not define a block +conditionally; it just makes overridable by a child template the output of +what will be rendered when the condition is ``true``. + +If you want the output to be displayed conditionally, use the following +instead: + +.. code-block:: jinja + + {% block head %} + {{ parent() }} + + {% if posts is empty %} + + {% endif %} + {% endblock head %} + +.. seealso:: :doc:`block<../functions/block>`, :doc:`block<../tags/block>`, :doc:`parent<../functions/parent>`, :doc:`use<../tags/use>` diff --git a/vendor/twig/twig/doc/tags/filter.rst b/vendor/twig/twig/doc/tags/filter.rst new file mode 100644 index 0000000..82ca5c6 --- /dev/null +++ b/vendor/twig/twig/doc/tags/filter.rst @@ -0,0 +1,21 @@ +``filter`` +========== + +Filter sections allow you to apply regular Twig filters on a block of template +data. Just wrap the code in the special ``filter`` section: + +.. code-block:: jinja + + {% filter upper %} + This text becomes uppercase + {% endfilter %} + +You can also chain filters: + +.. code-block:: jinja + + {% filter lower|escape %} + SOME TEXT + {% endfilter %} + + {# outputs "<strong>some text</strong>" #} diff --git a/vendor/twig/twig/doc/tags/flush.rst b/vendor/twig/twig/doc/tags/flush.rst new file mode 100644 index 0000000..7fed615 --- /dev/null +++ b/vendor/twig/twig/doc/tags/flush.rst @@ -0,0 +1,17 @@ +``flush`` +========= + +.. versionadded:: 1.5 + The flush tag was added in Twig 1.5. + +The ``flush`` tag tells Twig to flush the output buffer: + +.. code-block:: jinja + + {% flush %} + +.. note:: + + Internally, Twig uses the PHP `flush`_ function. + +.. _`flush`: https://secure.php.net/flush diff --git a/vendor/twig/twig/doc/tags/for.rst b/vendor/twig/twig/doc/tags/for.rst new file mode 100644 index 0000000..0673b55 --- /dev/null +++ b/vendor/twig/twig/doc/tags/for.rst @@ -0,0 +1,172 @@ +``for`` +======= + +Loop over each item in a sequence. For example, to display a list of users +provided in a variable called ``users``: + +.. code-block:: jinja + +

    Members

    +
      + {% for user in users %} +
    • {{ user.username|e }}
    • + {% endfor %} +
    + +.. note:: + + A sequence can be either an array or an object implementing the + ``Traversable`` interface. + +If you do need to iterate over a sequence of numbers, you can use the ``..`` +operator: + +.. code-block:: jinja + + {% for i in 0..10 %} + * {{ i }} + {% endfor %} + +The above snippet of code would print all numbers from 0 to 10. + +It can be also useful with letters: + +.. code-block:: jinja + + {% for letter in 'a'..'z' %} + * {{ letter }} + {% endfor %} + +The ``..`` operator can take any expression at both sides: + +.. code-block:: jinja + + {% for letter in 'a'|upper..'z'|upper %} + * {{ letter }} + {% endfor %} + +.. tip: + + If you need a step different from 1, you can use the ``range`` function + instead. + +The `loop` variable +------------------- + +Inside of a ``for`` loop block you can access some special variables: + +===================== ============================================================= +Variable Description +===================== ============================================================= +``loop.index`` The current iteration of the loop. (1 indexed) +``loop.index0`` The current iteration of the loop. (0 indexed) +``loop.revindex`` The number of iterations from the end of the loop (1 indexed) +``loop.revindex0`` The number of iterations from the end of the loop (0 indexed) +``loop.first`` True if first iteration +``loop.last`` True if last iteration +``loop.length`` The number of items in the sequence +``loop.parent`` The parent context +===================== ============================================================= + +.. code-block:: jinja + + {% for user in users %} + {{ loop.index }} - {{ user.username }} + {% endfor %} + +.. note:: + + The ``loop.length``, ``loop.revindex``, ``loop.revindex0``, and + ``loop.last`` variables are only available for PHP arrays, or objects that + implement the ``Countable`` interface. They are also not available when + looping with a condition. + +.. versionadded:: 1.2 + The ``if`` modifier support has been added in Twig 1.2. + +Adding a condition +------------------ + +Unlike in PHP, it's not possible to ``break`` or ``continue`` in a loop. You +can however filter the sequence during iteration which allows you to skip +items. The following example skips all the users which are not active: + +.. code-block:: jinja + +
      + {% for user in users if user.active %} +
    • {{ user.username|e }}
    • + {% endfor %} +
    + +The advantage is that the special loop variable will count correctly thus not +counting the users not iterated over. Keep in mind that properties like +``loop.last`` will not be defined when using loop conditions. + +.. note:: + + Using the ``loop`` variable within the condition is not recommended as it + will probably not be doing what you expect it to. For instance, adding a + condition like ``loop.index > 4`` won't work as the index is only + incremented when the condition is true (so the condition will never + match). + +The `else` Clause +----------------- + +If no iteration took place because the sequence was empty, you can render a +replacement block by using ``else``: + +.. code-block:: jinja + +
      + {% for user in users %} +
    • {{ user.username|e }}
    • + {% else %} +
    • no user found
    • + {% endfor %} +
    + +Iterating over Keys +------------------- + +By default, a loop iterates over the values of the sequence. You can iterate +on keys by using the ``keys`` filter: + +.. code-block:: jinja + +

    Members

    +
      + {% for key in users|keys %} +
    • {{ key }}
    • + {% endfor %} +
    + +Iterating over Keys and Values +------------------------------ + +You can also access both keys and values: + +.. code-block:: jinja + +

    Members

    +
      + {% for key, user in users %} +
    • {{ key }}: {{ user.username|e }}
    • + {% endfor %} +
    + +Iterating over a Subset +----------------------- + +You might want to iterate over a subset of values. This can be achieved using +the :doc:`slice <../filters/slice>` filter: + +.. code-block:: jinja + +

    Top Ten Members

    +
      + {% for user in users|slice(0, 10) %} +
    • {{ user.username|e }}
    • + {% endfor %} +
    diff --git a/vendor/twig/twig/doc/tags/from.rst b/vendor/twig/twig/doc/tags/from.rst new file mode 100644 index 0000000..39334fd --- /dev/null +++ b/vendor/twig/twig/doc/tags/from.rst @@ -0,0 +1,8 @@ +``from`` +======== + +The ``from`` tag imports :doc:`macro<../tags/macro>` names into the current +namespace. The tag is documented in detail in the documentation for the +:doc:`import<../tags/import>` tag. + +.. seealso:: :doc:`macro<../tags/macro>`, :doc:`import<../tags/import>` diff --git a/vendor/twig/twig/doc/tags/if.rst b/vendor/twig/twig/doc/tags/if.rst new file mode 100644 index 0000000..225246e --- /dev/null +++ b/vendor/twig/twig/doc/tags/if.rst @@ -0,0 +1,79 @@ +``if`` +====== + +The ``if`` statement in Twig is comparable with the if statements of PHP. + +In the simplest form you can use it to test if an expression evaluates to +``true``: + +.. code-block:: jinja + + {% if online == false %} +

    Our website is in maintenance mode. Please, come back later.

    + {% endif %} + +You can also test if an array is not empty: + +.. code-block:: jinja + + {% if users %} +
      + {% for user in users %} +
    • {{ user.username|e }}
    • + {% endfor %} +
    + {% endif %} + +.. note:: + + If you want to test if the variable is defined, use ``if users is + defined`` instead. + +You can also use ``not`` to check for values that evaluate to ``false``: + +.. code-block:: jinja + + {% if not user.subscribed %} +

    You are not subscribed to our mailing list.

    + {% endif %} + +For multiple conditions, ``and`` and ``or`` can be used: + +.. code-block:: jinja + + {% if temperature > 18 and temperature < 27 %} +

    It's a nice day for a walk in the park.

    + {% endif %} + +For multiple branches ``elseif`` and ``else`` can be used like in PHP. You can +use more complex ``expressions`` there too: + +.. code-block:: jinja + + {% if product.stock > 10 %} + Available + {% elseif product.stock > 0 %} + Only {{ product.stock }} left! + {% else %} + Sold-out! + {% endif %} + +.. note:: + + The rules to determine if an expression is ``true`` or ``false`` are the + same as in PHP; here are the edge cases rules: + + ====================== ==================== + Value Boolean evaluation + ====================== ==================== + empty string false + numeric zero false + NAN (Not A Number) true + INF (Infinity) true + whitespace-only string true + string "0" or '0' false + empty array false + null false + non-empty array true + object true + ====================== ==================== diff --git a/vendor/twig/twig/doc/tags/import.rst b/vendor/twig/twig/doc/tags/import.rst new file mode 100644 index 0000000..21a1e19 --- /dev/null +++ b/vendor/twig/twig/doc/tags/import.rst @@ -0,0 +1,57 @@ +``import`` +========== + +Twig supports putting often used code into :doc:`macros<../tags/macro>`. These +macros can go into different templates and get imported from there. + +There are two ways to import templates. You can import the complete template +into a variable or request specific macros from it. + +Imagine we have a helper module that renders forms (called ``forms.html``): + +.. code-block:: jinja + + {% macro input(name, value, type, size) %} + + {% endmacro %} + + {% macro textarea(name, value, rows, cols) %} + + {% endmacro %} + +The easiest and most flexible is importing the whole module into a variable. +That way you can access the attributes: + +.. code-block:: jinja + + {% import 'forms.html' as forms %} + +
    +
    Username
    +
    {{ forms.input('username') }}
    +
    Password
    +
    {{ forms.input('password', null, 'password') }}
    +
    +

    {{ forms.textarea('comment') }}

    + +Alternatively you can import names from the template into the current +namespace: + +.. code-block:: jinja + + {% from 'forms.html' import input as input_field, textarea %} + +
    +
    Username
    +
    {{ input_field('username') }}
    +
    Password
    +
    {{ input_field('password', '', 'password') }}
    +
    +

    {{ textarea('comment') }}

    + +.. tip:: + + To import macros from the current file, use the special ``_self`` variable + for the source. + +.. seealso:: :doc:`macro<../tags/macro>`, :doc:`from<../tags/from>` diff --git a/vendor/twig/twig/doc/tags/include.rst b/vendor/twig/twig/doc/tags/include.rst new file mode 100644 index 0000000..24ff24d --- /dev/null +++ b/vendor/twig/twig/doc/tags/include.rst @@ -0,0 +1,90 @@ +``include`` +=========== + +The ``include`` statement includes a template and returns the rendered content +of that file into the current namespace: + +.. code-block:: jinja + + {% include 'header.html' %} + Body + {% include 'footer.html' %} + +Included templates have access to the variables of the active context. + +If you are using the filesystem loader, the templates are looked for in the +paths defined by it. + +You can add additional variables by passing them after the ``with`` keyword: + +.. code-block:: jinja + + {# template.html will have access to the variables from the current context and the additional ones provided #} + {% include 'template.html' with {'foo': 'bar'} %} + + {% set vars = {'foo': 'bar'} %} + {% include 'template.html' with vars %} + +You can disable access to the context by appending the ``only`` keyword: + +.. code-block:: jinja + + {# only the foo variable will be accessible #} + {% include 'template.html' with {'foo': 'bar'} only %} + +.. code-block:: jinja + + {# no variables will be accessible #} + {% include 'template.html' only %} + +.. tip:: + + When including a template created by an end user, you should consider + sandboxing it. More information in the :doc:`Twig for Developers<../api>` + chapter and in the :doc:`sandbox<../tags/sandbox>` tag documentation. + +The template name can be any valid Twig expression: + +.. code-block:: jinja + + {% include some_var %} + {% include ajax ? 'ajax.html' : 'not_ajax.html' %} + +And if the expression evaluates to a ``Twig_Template`` or a +``Twig_TemplateWrapper`` instance, Twig will use it directly:: + + // {% include template %} + + // deprecated as of Twig 1.28 + $template = $twig->loadTemplate('some_template.twig'); + + // as of Twig 1.28 + $template = $twig->load('some_template.twig'); + + $twig->display('template.twig', array('template' => $template)); + +.. versionadded:: 1.2 + The ``ignore missing`` feature has been added in Twig 1.2. + +You can mark an include with ``ignore missing`` in which case Twig will ignore +the statement if the template to be included does not exist. It has to be +placed just after the template name. Here some valid examples: + +.. code-block:: jinja + + {% include 'sidebar.html' ignore missing %} + {% include 'sidebar.html' ignore missing with {'foo': 'bar'} %} + {% include 'sidebar.html' ignore missing only %} + +.. versionadded:: 1.2 + The possibility to pass an array of templates has been added in Twig 1.2. + +You can also provide a list of templates that are checked for existence before +inclusion. The first template that exists will be included: + +.. code-block:: jinja + + {% include ['page_detailed.html', 'page.html'] %} + +If ``ignore missing`` is given, it will fall back to rendering nothing if none +of the templates exist, otherwise it will throw an exception. diff --git a/vendor/twig/twig/doc/tags/index.rst b/vendor/twig/twig/doc/tags/index.rst new file mode 100644 index 0000000..373cf6e --- /dev/null +++ b/vendor/twig/twig/doc/tags/index.rst @@ -0,0 +1,26 @@ +Tags +==== + +.. toctree:: + :maxdepth: 1 + + autoescape + block + do + embed + extends + filter + flush + for + from + if + import + include + macro + sandbox + set + spaceless + use + verbatim + with + deprecated diff --git a/vendor/twig/twig/doc/tags/macro.rst b/vendor/twig/twig/doc/tags/macro.rst new file mode 100644 index 0000000..a8aa76f --- /dev/null +++ b/vendor/twig/twig/doc/tags/macro.rst @@ -0,0 +1,103 @@ +``macro`` +========= + +Macros are comparable with functions in regular programming languages. They +are useful to put often used HTML idioms into reusable elements to not repeat +yourself. + +Here is a small example of a macro that renders a form element: + +.. code-block:: jinja + + {% macro input(name, value, type, size) %} + + {% endmacro %} + +Macros differ from native PHP functions in a few ways: + +* Default argument values are defined by using the ``default`` filter in the + macro body; + +* Arguments of a macro are always optional. + +* If extra positional arguments are passed to a macro, they end up in the + special ``varargs`` variable as a list of values. + +But as with PHP functions, macros don't have access to the current template +variables. + +.. tip:: + + You can pass the whole context as an argument by using the special + ``_context`` variable. + +Import +------ + +Macros can be defined in any template, and need to be "imported" before being +used (see the documentation for the :doc:`import<../tags/import>` tag for more +information): + +.. code-block:: jinja + + {% import "forms.html" as forms %} + +The above ``import`` call imports the "forms.html" file (which can contain only +macros, or a template and some macros), and import the functions as items of +the ``forms`` variable. + +The macro can then be called at will: + +.. code-block:: jinja + +

    {{ forms.input('username') }}

    +

    {{ forms.input('password', null, 'password') }}

    + +If macros are defined and used in the same template, you can use the +special ``_self`` variable to import them: + +.. code-block:: jinja + + {% import _self as forms %} + +

    {{ forms.input('username') }}

    + +.. warning:: + + When you define a macro in the template where you are going to use it, you + might be tempted to call the macro directly via ``_self.input()`` instead + of importing it; even if seems to work, this is just a side-effect of the + current implementation and it won't work anymore in Twig 2.x. + +When you want to use a macro in another macro from the same file, you need to +import it locally: + +.. code-block:: jinja + + {% macro input(name, value, type, size) %} + + {% endmacro %} + + {% macro wrapped_input(name, value, type, size) %} + {% import _self as forms %} + +
    + {{ forms.input(name, value, type, size) }} +
    + {% endmacro %} + +Named Macro End-Tags +-------------------- + +Twig allows you to put the name of the macro after the end tag for better +readability: + +.. code-block:: jinja + + {% macro input() %} + ... + {% endmacro input %} + +Of course, the name after the ``endmacro`` word must match the macro name. + +.. seealso:: :doc:`from<../tags/from>`, :doc:`import<../tags/import>` diff --git a/vendor/twig/twig/doc/tags/sandbox.rst b/vendor/twig/twig/doc/tags/sandbox.rst new file mode 100644 index 0000000..e186726 --- /dev/null +++ b/vendor/twig/twig/doc/tags/sandbox.rst @@ -0,0 +1,30 @@ +``sandbox`` +=========== + +The ``sandbox`` tag can be used to enable the sandboxing mode for an included +template, when sandboxing is not enabled globally for the Twig environment: + +.. code-block:: jinja + + {% sandbox %} + {% include 'user.html' %} + {% endsandbox %} + +.. warning:: + + The ``sandbox`` tag is only available when the sandbox extension is + enabled (see the :doc:`Twig for Developers<../api>` chapter). + +.. note:: + + The ``sandbox`` tag can only be used to sandbox an include tag and it + cannot be used to sandbox a section of a template. The following example + won't work: + + .. code-block:: jinja + + {% sandbox %} + {% for i in 1..2 %} + {{ i }} + {% endfor %} + {% endsandbox %} diff --git a/vendor/twig/twig/doc/tags/set.rst b/vendor/twig/twig/doc/tags/set.rst new file mode 100644 index 0000000..3eba239 --- /dev/null +++ b/vendor/twig/twig/doc/tags/set.rst @@ -0,0 +1,78 @@ +``set`` +======= + +Inside code blocks you can also assign values to variables. Assignments use +the ``set`` tag and can have multiple targets. + +Here is how you can assign the ``bar`` value to the ``foo`` variable: + +.. code-block:: jinja + + {% set foo = 'bar' %} + +After the ``set`` call, the ``foo`` variable is available in the template like +any other ones: + +.. code-block:: jinja + + {# displays bar #} + {{ foo }} + +The assigned value can be any valid :ref:`Twig expressions +`: + +.. code-block:: jinja + + {% set foo = [1, 2] %} + {% set foo = {'foo': 'bar'} %} + {% set foo = 'foo' ~ 'bar' %} + +Several variables can be assigned in one block: + +.. code-block:: jinja + + {% set foo, bar = 'foo', 'bar' %} + + {# is equivalent to #} + + {% set foo = 'foo' %} + {% set bar = 'bar' %} + +The ``set`` tag can also be used to 'capture' chunks of text: + +.. code-block:: jinja + + {% set foo %} + + {% endset %} + +.. caution:: + + If you enable automatic output escaping, Twig will only consider the + content to be safe when capturing chunks of text. + +.. note:: + + Note that loops are scoped in Twig; therefore a variable declared inside a + ``for`` loop is not accessible outside the loop itself: + + .. code-block:: jinja + + {% for item in list %} + {% set foo = item %} + {% endfor %} + + {# foo is NOT available #} + + If you want to access the variable, just declare it before the loop: + + .. code-block:: jinja + + {% set foo = "" %} + {% for item in list %} + {% set foo = item %} + {% endfor %} + + {# foo is available #} diff --git a/vendor/twig/twig/doc/tags/spaceless.rst b/vendor/twig/twig/doc/tags/spaceless.rst new file mode 100644 index 0000000..b39cb27 --- /dev/null +++ b/vendor/twig/twig/doc/tags/spaceless.rst @@ -0,0 +1,37 @@ +``spaceless`` +============= + +Use the ``spaceless`` tag to remove whitespace *between HTML tags*, not +whitespace within HTML tags or whitespace in plain text: + +.. code-block:: jinja + + {% spaceless %} +
    + foo +
    + {% endspaceless %} + + {# output will be
    foo
    #} + +This tag is not meant to "optimize" the size of the generated HTML content but +merely to avoid extra whitespace between HTML tags to avoid browser rendering +quirks under some circumstances. + +.. tip:: + + If you want to optimize the size of the generated HTML content, gzip + compress the output instead. + +.. tip:: + + If you want to create a tag that actually removes all extra whitespace in + an HTML string, be warned that this is not as easy as it seems to be + (think of ``textarea`` or ``pre`` tags for instance). Using a third-party + library like Tidy is probably a better idea. + +.. tip:: + + For more information on whitespace control, read the + :ref:`dedicated section ` of the documentation and learn how + you can also use the whitespace control modifier on your tags. diff --git a/vendor/twig/twig/doc/tags/use.rst b/vendor/twig/twig/doc/tags/use.rst new file mode 100644 index 0000000..a6fdefb --- /dev/null +++ b/vendor/twig/twig/doc/tags/use.rst @@ -0,0 +1,124 @@ +``use`` +======= + +.. versionadded:: 1.1 + Horizontal reuse was added in Twig 1.1. + +.. note:: + + Horizontal reuse is an advanced Twig feature that is hardly ever needed in + regular templates. It is mainly used by projects that need to make + template blocks reusable without using inheritance. + +Template inheritance is one of the most powerful features of Twig but it is +limited to single inheritance; a template can only extend one other template. +This limitation makes template inheritance simple to understand and easy to +debug: + +.. code-block:: jinja + + {% extends "base.html" %} + + {% block title %}{% endblock %} + {% block content %}{% endblock %} + +Horizontal reuse is a way to achieve the same goal as multiple inheritance, +but without the associated complexity: + +.. code-block:: jinja + + {% extends "base.html" %} + + {% use "blocks.html" %} + + {% block title %}{% endblock %} + {% block content %}{% endblock %} + +The ``use`` statement tells Twig to import the blocks defined in +``blocks.html`` into the current template (it's like macros, but for blocks): + +.. code-block:: jinja + + {# blocks.html #} + + {% block sidebar %}{% endblock %} + +In this example, the ``use`` statement imports the ``sidebar`` block into the +main template. The code is mostly equivalent to the following one (the +imported blocks are not outputted automatically): + +.. code-block:: jinja + + {% extends "base.html" %} + + {% block sidebar %}{% endblock %} + {% block title %}{% endblock %} + {% block content %}{% endblock %} + +.. note:: + + The ``use`` tag only imports a template if it does not extend another + template, if it does not define macros, and if the body is empty. But it + can *use* other templates. + +.. note:: + + Because ``use`` statements are resolved independently of the context + passed to the template, the template reference cannot be an expression. + +The main template can also override any imported block. If the template +already defines the ``sidebar`` block, then the one defined in ``blocks.html`` +is ignored. To avoid name conflicts, you can rename imported blocks: + +.. code-block:: jinja + + {% extends "base.html" %} + + {% use "blocks.html" with sidebar as base_sidebar, title as base_title %} + + {% block sidebar %}{% endblock %} + {% block title %}{% endblock %} + {% block content %}{% endblock %} + +.. versionadded:: 1.3 + The ``parent()`` support was added in Twig 1.3. + +The ``parent()`` function automatically determines the correct inheritance +tree, so it can be used when overriding a block defined in an imported +template: + +.. code-block:: jinja + + {% extends "base.html" %} + + {% use "blocks.html" %} + + {% block sidebar %} + {{ parent() }} + {% endblock %} + + {% block title %}{% endblock %} + {% block content %}{% endblock %} + +In this example, ``parent()`` will correctly call the ``sidebar`` block from +the ``blocks.html`` template. + +.. tip:: + + In Twig 1.2, renaming allows you to simulate inheritance by calling the + "parent" block: + + .. code-block:: jinja + + {% extends "base.html" %} + + {% use "blocks.html" with sidebar as parent_sidebar %} + + {% block sidebar %} + {{ block('parent_sidebar') }} + {% endblock %} + +.. note:: + + You can use as many ``use`` statements as you want in any given template. + If two imported templates define the same block, the latest one wins. diff --git a/vendor/twig/twig/doc/tags/verbatim.rst b/vendor/twig/twig/doc/tags/verbatim.rst new file mode 100644 index 0000000..fe61ca1 --- /dev/null +++ b/vendor/twig/twig/doc/tags/verbatim.rst @@ -0,0 +1,24 @@ +``verbatim`` +============ + +.. versionadded:: 1.12 + The ``verbatim`` tag was added in Twig 1.12 (it was named ``raw`` before). + +The ``verbatim`` tag marks sections as being raw text that should not be +parsed. For example to put Twig syntax as example into a template you can use +this snippet: + +.. code-block:: jinja + + {% verbatim %} +
      + {% for item in seq %} +
    • {{ item }}
    • + {% endfor %} +
    + {% endverbatim %} + +.. note:: + + The ``verbatim`` tag works in the exact same way as the old ``raw`` tag, + but was renamed to avoid confusion with the ``raw`` filter. \ No newline at end of file diff --git a/vendor/twig/twig/doc/tags/with.rst b/vendor/twig/twig/doc/tags/with.rst new file mode 100644 index 0000000..815b069 --- /dev/null +++ b/vendor/twig/twig/doc/tags/with.rst @@ -0,0 +1,44 @@ +``with`` +======== + +.. versionadded:: 1.28 + The ``with`` tag was added in Twig 1.28. + +Use the ``with`` tag to create a new inner scope. Variables set within this +scope are not visible outside of the scope: + +.. code-block:: jinja + + {% with %} + {% set foo = 42 %} + {{ foo }} foo is 42 here + {% endwith %} + foo is not visible here any longer + +Instead of defining variables at the beginning of the scope, you can pass a +hash of variables you want to define in the ``with`` tag; the previous example +is equivalent to the following one: + +.. code-block:: jinja + + {% with { foo: 42 } %} + {{ foo }} foo is 42 here + {% endwith %} + foo is not visible here any longer + + {# it works with any expression that resolves to a hash #} + {% set vars = { foo: 42 } %} + {% with vars %} + ... + {% endwith %} + +By default, the inner scope has access to the outer scope context; you can +disable this behavior by appending the ``only`` keyword: + +.. code-block:: jinja + + {% set bar = 'bar' %} + {% with { foo: 42 } only %} + {# only foo is defined #} + {# bar is not defined #} + {% endwith %} diff --git a/vendor/twig/twig/doc/templates.rst b/vendor/twig/twig/doc/templates.rst new file mode 100644 index 0000000..23f1b8b --- /dev/null +++ b/vendor/twig/twig/doc/templates.rst @@ -0,0 +1,911 @@ +Twig for Template Designers +=========================== + +This document describes the syntax and semantics of the template engine and +will be most useful as reference to those creating Twig templates. + +Synopsis +-------- + +A template is simply a text file. It can generate any text-based format (HTML, +XML, CSV, LaTeX, etc.). It doesn't have a specific extension, ``.html`` or +``.xml`` are just fine. + +A template contains **variables** or **expressions**, which get replaced with +values when the template is evaluated, and **tags**, which control the logic +of the template. + +Below is a minimal template that illustrates a few basics. We will cover further +details later on: + +.. code-block:: html+jinja + + + + + My Webpage + + + + +

    My Webpage

    + {{ a_variable }} + + + +There are two kinds of delimiters: ``{% ... %}`` and ``{{ ... }}``. The first +one is used to execute statements such as for-loops, the latter prints the +result of an expression to the template. + +IDEs Integration +---------------- + +Many IDEs support syntax highlighting and auto-completion for Twig: + +* *Textmate* via the `Twig bundle`_ +* *Vim* via the `Jinja syntax plugin`_ or the `vim-twig plugin`_ +* *Netbeans* via the `Twig syntax plugin`_ (until 7.1, native as of 7.2) +* *PhpStorm* (native as of 2.1) +* *Eclipse* via the `Twig plugin`_ +* *Sublime Text* via the `Twig bundle`_ +* *GtkSourceView* via the `Twig language definition`_ (used by gedit and other projects) +* *Coda* and *SubEthaEdit* via the `Twig syntax mode`_ +* *Coda 2* via the `other Twig syntax mode`_ +* *Komodo* and *Komodo Edit* via the Twig highlight/syntax check mode +* *Notepad++* via the `Notepad++ Twig Highlighter`_ +* *Emacs* via `web-mode.el`_ +* *Atom* via the `PHP-twig for atom`_ +* *Visual Studio Code* via the `Twig pack`_ + +Also, `TwigFiddle`_ is an online service that allows you to execute Twig templates +from a browser; it supports all versions of Twig. + +Variables +--------- + +The application passes variables to the templates for manipulation in the +template. Variables may have attributes or elements you can access, +too. The visual representation of a variable depends heavily on the application providing +it. + +You can use a dot (``.``) to access attributes of a variable (methods or +properties of a PHP object, or items of a PHP array), or the so-called +"subscript" syntax (``[]``): + +.. code-block:: jinja + + {{ foo.bar }} + {{ foo['bar'] }} + +When the attribute contains special characters (like ``-`` that would be +interpreted as the minus operator), use the ``attribute`` function instead to +access the variable attribute: + +.. code-block:: jinja + + {# equivalent to the non-working foo.data-foo #} + {{ attribute(foo, 'data-foo') }} + +.. note:: + + It's important to know that the curly braces are *not* part of the + variable but the print statement. When accessing variables inside tags, + don't put the braces around them. + +If a variable or attribute does not exist, you will receive a ``null`` value +when the ``strict_variables`` option is set to ``false``; alternatively, if ``strict_variables`` +is set, Twig will throw an error (see :ref:`environment options`). + +.. sidebar:: Implementation + + For convenience's sake ``foo.bar`` does the following things on the PHP + layer: + + * check if ``foo`` is an array and ``bar`` a valid element; + * if not, and if ``foo`` is an object, check that ``bar`` is a valid property; + * if not, and if ``foo`` is an object, check that ``bar`` is a valid method + (even if ``bar`` is the constructor - use ``__construct()`` instead); + * if not, and if ``foo`` is an object, check that ``getBar`` is a valid method; + * if not, and if ``foo`` is an object, check that ``isBar`` is a valid method; + * if not, return a ``null`` value. + + ``foo['bar']`` on the other hand only works with PHP arrays: + + * check if ``foo`` is an array and ``bar`` a valid element; + * if not, return a ``null`` value. + +.. note:: + + If you want to access a dynamic attribute of a variable, use the + :doc:`attribute` function instead. + +Global Variables +~~~~~~~~~~~~~~~~ + +The following variables are always available in templates: + +* ``_self``: references the current template; +* ``_context``: references the current context; +* ``_charset``: references the current charset. + +Setting Variables +~~~~~~~~~~~~~~~~~ + +You can assign values to variables inside code blocks. Assignments use the +:doc:`set` tag: + +.. code-block:: jinja + + {% set foo = 'foo' %} + {% set foo = [1, 2] %} + {% set foo = {'foo': 'bar'} %} + +Filters +------- + +Variables can be modified by **filters**. Filters are separated from the +variable by a pipe symbol (``|``) and may have optional arguments in +parentheses. Multiple filters can be chained. The output of one filter is +applied to the next. + +The following example removes all HTML tags from the ``name`` and title-cases +it: + +.. code-block:: jinja + + {{ name|striptags|title }} + +Filters that accept arguments have parentheses around the arguments. This +example will join a list by commas: + +.. code-block:: jinja + + {{ list|join(', ') }} + +To apply a filter on a section of code, wrap it in the +:doc:`filter` tag: + +.. code-block:: jinja + + {% filter upper %} + This text becomes uppercase + {% endfilter %} + +Go to the :doc:`filters` page to learn more about built-in +filters. + +Functions +--------- + +Functions can be called to generate content. Functions are called by their +name followed by parentheses (``()``) and may have arguments. + +For instance, the ``range`` function returns a list containing an arithmetic +progression of integers: + +.. code-block:: jinja + + {% for i in range(0, 3) %} + {{ i }}, + {% endfor %} + +Go to the :doc:`functions` page to learn more about the +built-in functions. + +Named Arguments +--------------- + +.. versionadded:: 1.12 + Support for named arguments was added in Twig 1.12. + +.. code-block:: jinja + + {% for i in range(low=1, high=10, step=2) %} + {{ i }}, + {% endfor %} + +Using named arguments makes your templates more explicit about the meaning of +the values you pass as arguments: + +.. code-block:: jinja + + {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} + + {# versus #} + + {{ data|convert_encoding(from='iso-2022-jp', to='UTF-8') }} + +Named arguments also allow you to skip some arguments for which you don't want +to change the default value: + +.. code-block:: jinja + + {# the first argument is the date format, which defaults to the global date format if null is passed #} + {{ "now"|date(null, "Europe/Paris") }} + + {# or skip the format value by using a named argument for the time zone #} + {{ "now"|date(timezone="Europe/Paris") }} + +You can also use both positional and named arguments in one call, in which +case positional arguments must always come before named arguments: + +.. code-block:: jinja + + {{ "now"|date('d/m/Y H:i', timezone="Europe/Paris") }} + +.. tip:: + + Each function and filter documentation page has a section where the names + of all arguments are listed when supported. + +Control Structure +----------------- + +A control structure refers to all those things that control the flow of a +program - conditionals (i.e. ``if``/``elseif``/``else``), ``for``-loops, as +well as things like blocks. Control structures appear inside ``{% ... %}`` +blocks. + +For example, to display a list of users provided in a variable called +``users``, use the :doc:`for` tag: + +.. code-block:: jinja + +

    Members

    +
      + {% for user in users %} +
    • {{ user.username|e }}
    • + {% endfor %} +
    + +The :doc:`if` tag can be used to test an expression: + +.. code-block:: jinja + + {% if users|length > 0 %} +
      + {% for user in users %} +
    • {{ user.username|e }}
    • + {% endfor %} +
    + {% endif %} + +Go to the :doc:`tags` page to learn more about the built-in tags. + +Comments +-------- + +To comment-out part of a line in a template, use the comment syntax ``{# ... +#}``. This is useful for debugging or to add information for other template +designers or yourself: + +.. code-block:: jinja + + {# note: disabled template because we no longer use this + {% for user in users %} + ... + {% endfor %} + #} + +Including other Templates +------------------------- + +The :doc:`include` function is useful to include a template +and return the rendered content of that template into the current one: + +.. code-block:: jinja + + {{ include('sidebar.html') }} + +By default, included templates have access to the same context as the template +which includes them. This means that any variable defined in the main template +will be available in the included template too: + +.. code-block:: jinja + + {% for box in boxes %} + {{ include('render_box.html') }} + {% endfor %} + +The included template ``render_box.html`` is able to access the ``box`` variable. + +The name of the template depends on the template loader. For instance, the +``Twig_Loader_Filesystem`` allows you to access other templates by giving the +filename. You can access templates in subdirectories with a slash: + +.. code-block:: jinja + + {{ include('sections/articles/sidebar.html') }} + +This behavior depends on the application embedding Twig. + +Template Inheritance +-------------------- + +The most powerful part of Twig is template inheritance. Template inheritance +allows you to build a base "skeleton" template that contains all the common +elements of your site and defines **blocks** that child templates can +override. + +Sounds complicated but it is very basic. It's easier to understand it by +starting with an example. + +Let's define a base template, ``base.html``, which defines a simple HTML +skeleton document that you might use for a simple two-column page: + +.. code-block:: html+jinja + + + + + {% block head %} + + {% block title %}{% endblock %} - My Webpage + {% endblock %} + + +
    {% block content %}{% endblock %}
    + + + + +In this example, the :doc:`block` tags define four blocks that +child templates can fill in. All the ``block`` tag does is to tell the +template engine that a child template may override those portions of the +template. + +A child template might look like this: + +.. code-block:: jinja + + {% extends "base.html" %} + + {% block title %}Index{% endblock %} + {% block head %} + {{ parent() }} + + {% endblock %} + {% block content %} +

    Index

    +

    + Welcome to my awesome homepage. +

    + {% endblock %} + +The :doc:`extends` tag is the key here. It tells the template +engine that this template "extends" another template. When the template system +evaluates this template, first it locates the parent. The extends tag should +be the first tag in the template. + +Note that since the child template doesn't define the ``footer`` block, the +value from the parent template is used instead. + +It's possible to render the contents of the parent block by using the +:doc:`parent` function. This gives back the results of the +parent block: + +.. code-block:: jinja + + {% block sidebar %} +

    Table Of Contents

    + ... + {{ parent() }} + {% endblock %} + +.. tip:: + + The documentation page for the :doc:`extends` tag describes + more advanced features like block nesting, scope, dynamic inheritance, and + conditional inheritance. + +.. note:: + + Twig also supports multiple inheritance with the so called horizontal reuse + with the help of the :doc:`use` tag. This is an advanced feature + hardly ever needed in regular templates. + +HTML Escaping +------------- + +When generating HTML from templates, there's always a risk that a variable +will include characters that affect the resulting HTML. There are two +approaches: manually escaping each variable or automatically escaping +everything by default. + +Twig supports both, automatic escaping is enabled by default. + +The automatic escaping strategy can be configured via the +:ref:`autoescape` option and defaults to ``html``. + +Working with Manual Escaping +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +If manual escaping is enabled, it is **your** responsibility to escape +variables if needed. What to escape? Any variable you don't trust. + +Escaping works by piping the variable through the +:doc:`escape` or ``e`` filter: + +.. code-block:: jinja + + {{ user.username|e }} + +By default, the ``escape`` filter uses the ``html`` strategy, but depending on +the escaping context, you might want to explicitly use any other available +strategies: + +.. code-block:: jinja + + {{ user.username|e('js') }} + {{ user.username|e('css') }} + {{ user.username|e('url') }} + {{ user.username|e('html_attr') }} + +Working with Automatic Escaping +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Whether automatic escaping is enabled or not, you can mark a section of a +template to be escaped or not by using the :doc:`autoescape` +tag: + +.. code-block:: jinja + + {% autoescape %} + Everything will be automatically escaped in this block (using the HTML strategy) + {% endautoescape %} + +By default, auto-escaping uses the ``html`` escaping strategy. If you output +variables in other contexts, you need to explicitly escape them with the +appropriate escaping strategy: + +.. code-block:: jinja + + {% autoescape 'js' %} + Everything will be automatically escaped in this block (using the JS strategy) + {% endautoescape %} + +Escaping +-------- + +It is sometimes desirable or even necessary to have Twig ignore parts it would +otherwise handle as variables or blocks. For example if the default syntax is +used and you want to use ``{{`` as raw string in the template and not start a +variable you have to use a trick. + +The easiest way is to output the variable delimiter (``{{``) by using a variable +expression: + +.. code-block:: jinja + + {{ '{{' }} + +For bigger sections it makes sense to mark a block +:doc:`verbatim`. + +Macros +------ + +.. versionadded:: 1.12 + Support for default argument values was added in Twig 1.12. + +Macros are comparable with functions in regular programming languages. They +are useful to reuse often used HTML fragments to not repeat yourself. + +A macro is defined via the :doc:`macro` tag. Here is a small example +(subsequently called ``forms.html``) of a macro that renders a form element: + +.. code-block:: jinja + + {% macro input(name, value, type, size) %} + + {% endmacro %} + +Macros can be defined in any template, and need to be "imported" via the +:doc:`import` tag before being used: + +.. code-block:: jinja + + {% import "forms.html" as forms %} + +

    {{ forms.input('username') }}

    + +Alternatively, you can import individual macro names from a template into the +current namespace via the :doc:`from` tag and optionally alias them: + +.. code-block:: jinja + + {% from 'forms.html' import input as input_field %} + +
    +
    Username
    +
    {{ input_field('username') }}
    +
    Password
    +
    {{ input_field('password', '', 'password') }}
    +
    + +A default value can also be defined for macro arguments when not provided in a +macro call: + +.. code-block:: jinja + + {% macro input(name, value = "", type = "text", size = 20) %} + + {% endmacro %} + +If extra positional arguments are passed to a macro call, they end up in the +special ``varargs`` variable as a list of values. + +.. _twig-expressions: + +Expressions +----------- + +Twig allows expressions everywhere. These work very similar to regular PHP and +even if you're not working with PHP you should feel comfortable with it. + +.. note:: + + The operator precedence is as follows, with the lowest-precedence + operators listed first: ``b-and``, ``b-xor``, ``b-or``, ``or``, ``and``, + ``==``, ``!=``, ``<``, ``>``, ``>=``, ``<=``, ``in``, ``matches``, + ``starts with``, ``ends with``, ``..``, ``+``, ``-``, ``~``, ``*``, ``/``, + ``//``, ``%``, ``is``, ``**``, ``|``, ``[]``, and ``.``: + + .. code-block:: jinja + + {% set greeting = 'Hello ' %} + {% set name = 'Fabien' %} + + {{ greeting ~ name|lower }} {# Hello fabien #} + + {# use parenthesis to change precedence #} + {{ (greeting ~ name)|lower }} {# hello fabien #} + +Literals +~~~~~~~~ + +.. versionadded:: 1.5 + Support for hash keys as names and expressions was added in Twig 1.5. + +The simplest form of expressions are literals. Literals are representations +for PHP types such as strings, numbers, and arrays. The following literals +exist: + +* ``"Hello World"``: Everything between two double or single quotes is a + string. They are useful whenever you need a string in the template (for + example as arguments to function calls, filters or just to extend or include + a template). A string can contain a delimiter if it is preceded by a + backslash (``\``) -- like in ``'It\'s good'``. If the string contains a + backslash (e.g. ``'c:\Program Files'``) escape it by doubling it + (e.g. ``'c:\\Program Files'``). + +* ``42`` / ``42.23``: Integers and floating point numbers are created by just + writing the number down. If a dot is present the number is a float, + otherwise an integer. + +* ``["foo", "bar"]``: Arrays are defined by a sequence of expressions + separated by a comma (``,``) and wrapped with squared brackets (``[]``). + +* ``{"foo": "bar"}``: Hashes are defined by a list of keys and values + separated by a comma (``,``) and wrapped with curly braces (``{}``): + + .. code-block:: jinja + + {# keys as string #} + { 'foo': 'foo', 'bar': 'bar' } + + {# keys as names (equivalent to the previous hash) -- as of Twig 1.5 #} + { foo: 'foo', bar: 'bar' } + + {# keys as integer #} + { 2: 'foo', 4: 'bar' } + + {# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #} + {% set foo = 'foo' %} + { (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' } + +* ``true`` / ``false``: ``true`` represents the true value, ``false`` + represents the false value. + +* ``null``: ``null`` represents no specific value. This is the value returned + when a variable does not exist. ``none`` is an alias for ``null``. + +Arrays and hashes can be nested: + +.. code-block:: jinja + + {% set foo = [1, {"foo": "bar"}] %} + +.. tip:: + + Using double-quoted or single-quoted strings has no impact on performance + but string interpolation is only supported in double-quoted strings. + +Math +~~~~ + +Twig allows you to calculate with values. This is rarely useful in templates +but exists for completeness' sake. The following operators are supported: + +* ``+``: Adds two objects together (the operands are casted to numbers). ``{{ + 1 + 1 }}`` is ``2``. + +* ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is + ``1``. + +* ``/``: Divides two numbers. The returned value will be a floating point + number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``. + +* ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is + ``4``. + +* ``//``: Divides two numbers and returns the floored integer result. ``{{ 20 + // 7 }}`` is ``2``, ``{{ -20 // 7 }}`` is ``-3`` (this is just syntactic + sugar for the :doc:`round` filter). + +* ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would + return ``4``. + +* ``**``: Raises the left operand to the power of the right operand. ``{{ 2 ** + 3 }}`` would return ``8``. + +.. _template_logic: + +Logic +~~~~~ + +You can combine multiple expressions with the following operators: + +* ``and``: Returns true if the left and the right operands are both true. + +* ``or``: Returns true if the left or the right operand is true. + +* ``not``: Negates a statement. + +* ``(expr)``: Groups an expression. + +.. note:: + + Twig also supports bitwise operators (``b-and``, ``b-xor``, and ``b-or``). + +.. note:: + + Operators are case sensitive. + +Comparisons +~~~~~~~~~~~ + +The following comparison operators are supported in any expression: ``==``, +``!=``, ``<``, ``>``, ``>=``, and ``<=``. + +You can also check if a string ``starts with`` or ``ends with`` another +string: + +.. code-block:: jinja + + {% if 'Fabien' starts with 'F' %} + {% endif %} + + {% if 'Fabien' ends with 'n' %} + {% endif %} + +.. note:: + + For complex string comparisons, the ``matches`` operator allows you to use + `regular expressions`_: + + .. code-block:: jinja + + {% if phone matches '/^[\\d\\.]+$/' %} + {% endif %} + +Containment Operator +~~~~~~~~~~~~~~~~~~~~ + +The ``in`` operator performs containment test. + +It returns ``true`` if the left operand is contained in the right: + +.. code-block:: jinja + + {# returns true #} + + {{ 1 in [1, 2, 3] }} + + {{ 'cd' in 'abcde' }} + +.. tip:: + + You can use this filter to perform a containment test on strings, arrays, + or objects implementing the ``Traversable`` interface. + +To perform a negative test, use the ``not in`` operator: + +.. code-block:: jinja + + {% if 1 not in [1, 2, 3] %} + + {# is equivalent to #} + {% if not (1 in [1, 2, 3]) %} + +Test Operator +~~~~~~~~~~~~~ + +The ``is`` operator performs tests. Tests can be used to test a variable against +a common expression. The right operand is name of the test: + +.. code-block:: jinja + + {# find out if a variable is odd #} + + {{ name is odd }} + +Tests can accept arguments too: + +.. code-block:: jinja + + {% if post.status is constant('Post::PUBLISHED') %} + +Tests can be negated by using the ``is not`` operator: + +.. code-block:: jinja + + {% if post.status is not constant('Post::PUBLISHED') %} + + {# is equivalent to #} + {% if not (post.status is constant('Post::PUBLISHED')) %} + +Go to the :doc:`tests` page to learn more about the built-in +tests. + +Other Operators +~~~~~~~~~~~~~~~ + +.. versionadded:: 1.12.0 + Support for the extended ternary operator was added in Twig 1.12.0. + +The following operators don't fit into any of the other categories: + +* ``|``: Applies a filter. + +* ``..``: Creates a sequence based on the operand before and after the operator + (this is just syntactic sugar for the :doc:`range` function): + + .. code-block:: jinja + + {{ 1..5 }} + + {# equivalent to #} + {{ range(1, 5) }} + + Note that you must use parentheses when combining it with the filter operator + due to the :ref:`operator precedence rules `: + + .. code-block:: jinja + + (1..5)|join(', ') + +* ``~``: Converts all operands into strings and concatenates them. ``{{ "Hello + " ~ name ~ "!" }}`` would return (assuming ``name`` is ``'John'``) ``Hello + John!``. + +* ``.``, ``[]``: Gets an attribute of an object. + +* ``?:``: The ternary operator: + + .. code-block:: jinja + + {{ foo ? 'yes' : 'no' }} + + {# as of Twig 1.12.0 #} + {{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }} + {{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }} + +* ``??``: The null-coalescing operator: + + .. code-block:: jinja + + {# returns the value of foo if it is defined and not null, 'no' otherwise #} + {{ foo ?? 'no' }} + +String Interpolation +~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.5 + String interpolation was added in Twig 1.5. + +String interpolation (``#{expression}``) allows any valid expression to appear +within a *double-quoted string*. The result of evaluating that expression is +inserted into the string: + +.. code-block:: jinja + + {{ "foo #{bar} baz" }} + {{ "foo #{1 + 2} baz" }} + +.. _templates-whitespace-control: + +Whitespace Control +------------------ + +.. versionadded:: 1.1 + Tag level whitespace control was added in Twig 1.1. + +The first newline after a template tag is removed automatically (like in PHP.) +Whitespace is not further modified by the template engine, so each whitespace +(spaces, tabs, newlines etc.) is returned unchanged. + +Use the ``spaceless`` tag to remove whitespace *between HTML tags*: + +.. code-block:: jinja + + {% spaceless %} +
    + foo bar +
    + {% endspaceless %} + + {# output will be
    foo bar
    #} + +In addition to the spaceless tag you can also control whitespace on a per tag +level. By using the whitespace control modifier on your tags, you can trim +leading and or trailing whitespace: + +.. code-block:: jinja + + {% set value = 'no spaces' %} + {#- No leading/trailing whitespace -#} + {%- if true -%} + {{- value -}} + {%- endif -%} + + {# output 'no spaces' #} + +The above sample shows the default whitespace control modifier, and how you can +use it to remove whitespace around tags. Trimming space will consume all whitespace +for that side of the tag. It is possible to use whitespace trimming on one side +of a tag: + +.. code-block:: jinja + + {% set value = 'no spaces' %} +
  • {{- value }}
  • + + {# outputs '
  • no spaces
  • ' #} + +Extensions +---------- + +Twig can be easily extended. + +If you are looking for new tags, filters, or functions, have a look at the Twig official +`extension repository`_. + +If you want to create your own, read the :ref:`Creating an +Extension` chapter. + +.. _`Twig bundle`: https://github.com/Anomareh/PHP-Twig.tmbundle +.. _`Jinja syntax plugin`: http://jinja.pocoo.org/docs/integration/#vim +.. _`vim-twig plugin`: https://github.com/lumiliet/vim-twig +.. _`Twig syntax plugin`: http://plugins.netbeans.org/plugin/37069/php-twig +.. _`Twig plugin`: https://github.com/pulse00/Twig-Eclipse-Plugin +.. _`Twig language definition`: https://github.com/gabrielcorpse/gedit-twig-template-language +.. _`extension repository`: https://github.com/twigphp/Twig-extensions +.. _`Twig syntax mode`: https://github.com/bobthecow/Twig-HTML.mode +.. _`other Twig syntax mode`: https://github.com/muxx/Twig-HTML.mode +.. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig +.. _`web-mode.el`: http://web-mode.org/ +.. _`regular expressions`: https://secure.php.net/manual/en/pcre.pattern.php +.. _`PHP-twig for atom`: https://github.com/reesef/php-twig +.. _`TwigFiddle`: https://twigfiddle.com/ +.. _`Twig pack`: https://marketplace.visualstudio.com/items?itemName=bajdzis.vscode-twig-pack diff --git a/vendor/twig/twig/doc/tests/constant.rst b/vendor/twig/twig/doc/tests/constant.rst new file mode 100644 index 0000000..8d0724a --- /dev/null +++ b/vendor/twig/twig/doc/tests/constant.rst @@ -0,0 +1,22 @@ +``constant`` +============ + +.. versionadded: 1.13.1 + constant now accepts object instances as the second argument. + +``constant`` checks if a variable has the exact same value as a constant. You +can use either global constants or class constants: + +.. code-block:: jinja + + {% if post.status is constant('Post::PUBLISHED') %} + the status attribute is exactly the same as Post::PUBLISHED + {% endif %} + +You can test constants from object instances as well: + +.. code-block:: jinja + + {% if post.status is constant('PUBLISHED', post) %} + the status attribute is exactly the same as Post::PUBLISHED + {% endif %} diff --git a/vendor/twig/twig/doc/tests/defined.rst b/vendor/twig/twig/doc/tests/defined.rst new file mode 100644 index 0000000..702ce72 --- /dev/null +++ b/vendor/twig/twig/doc/tests/defined.rst @@ -0,0 +1,30 @@ +``defined`` +=========== + +``defined`` checks if a variable is defined in the current context. This is very +useful if you use the ``strict_variables`` option: + +.. code-block:: jinja + + {# defined works with variable names #} + {% if foo is defined %} + ... + {% endif %} + + {# and attributes on variables names #} + {% if foo.bar is defined %} + ... + {% endif %} + + {% if foo['bar'] is defined %} + ... + {% endif %} + +When using the ``defined`` test on an expression that uses variables in some +method calls, be sure that they are all defined first: + +.. code-block:: jinja + + {% if var is defined and foo.method(var) is defined %} + ... + {% endif %} diff --git a/vendor/twig/twig/doc/tests/divisibleby.rst b/vendor/twig/twig/doc/tests/divisibleby.rst new file mode 100644 index 0000000..6c693b2 --- /dev/null +++ b/vendor/twig/twig/doc/tests/divisibleby.rst @@ -0,0 +1,14 @@ +``divisible by`` +================ + +.. versionadded:: 1.14.2 + The ``divisible by`` test was added in Twig 1.14.2 as an alias for + ``divisibleby``. + +``divisible by`` checks if a variable is divisible by a number: + +.. code-block:: jinja + + {% if loop.index is divisible by(3) %} + ... + {% endif %} diff --git a/vendor/twig/twig/doc/tests/empty.rst b/vendor/twig/twig/doc/tests/empty.rst new file mode 100644 index 0000000..639cdcc --- /dev/null +++ b/vendor/twig/twig/doc/tests/empty.rst @@ -0,0 +1,22 @@ +``empty`` +========= + +.. versionadded:: 1.33 + + Support for the ``__toString()`` magic method has been added in Twig 1.33. + +``empty`` checks if a variable is an empty string, an empty array, an empty +hash, exactly ``false``, or exactly ``null``. + +For objects that implement the ``Countable`` interface, ``empty`` will check the +return value of the ``count()`` method. + +For objects that implement the ``__toString()`` magic method (and not ``Countable``), +it will check if an empty string is returned. + +.. code-block:: jinja + + {% if foo is empty %} + ... + {% endif %} + diff --git a/vendor/twig/twig/doc/tests/even.rst b/vendor/twig/twig/doc/tests/even.rst new file mode 100644 index 0000000..6ab5cc3 --- /dev/null +++ b/vendor/twig/twig/doc/tests/even.rst @@ -0,0 +1,10 @@ +``even`` +======== + +``even`` returns ``true`` if the given number is even: + +.. code-block:: jinja + + {{ var is even }} + +.. seealso:: :doc:`odd<../tests/odd>` diff --git a/vendor/twig/twig/doc/tests/index.rst b/vendor/twig/twig/doc/tests/index.rst new file mode 100644 index 0000000..c63208e --- /dev/null +++ b/vendor/twig/twig/doc/tests/index.rst @@ -0,0 +1,15 @@ +Tests +===== + +.. toctree:: + :maxdepth: 1 + + constant + defined + divisibleby + empty + even + iterable + null + odd + sameas diff --git a/vendor/twig/twig/doc/tests/iterable.rst b/vendor/twig/twig/doc/tests/iterable.rst new file mode 100644 index 0000000..89a172f --- /dev/null +++ b/vendor/twig/twig/doc/tests/iterable.rst @@ -0,0 +1,19 @@ +``iterable`` +============ + +.. versionadded:: 1.7 + The iterable test was added in Twig 1.7. + +``iterable`` checks if a variable is an array or a traversable object: + +.. code-block:: jinja + + {# evaluates to true if the foo variable is iterable #} + {% if users is iterable %} + {% for user in users %} + Hello {{ user }}! + {% endfor %} + {% else %} + {# users is probably a string #} + Hello {{ users }}! + {% endif %} diff --git a/vendor/twig/twig/doc/tests/null.rst b/vendor/twig/twig/doc/tests/null.rst new file mode 100644 index 0000000..44eec62 --- /dev/null +++ b/vendor/twig/twig/doc/tests/null.rst @@ -0,0 +1,12 @@ +``null`` +======== + +``null`` returns ``true`` if the variable is ``null``: + +.. code-block:: jinja + + {{ var is null }} + +.. note:: + + ``none`` is an alias for ``null``. diff --git a/vendor/twig/twig/doc/tests/odd.rst b/vendor/twig/twig/doc/tests/odd.rst new file mode 100644 index 0000000..9eece77 --- /dev/null +++ b/vendor/twig/twig/doc/tests/odd.rst @@ -0,0 +1,10 @@ +``odd`` +======= + +``odd`` returns ``true`` if the given number is odd: + +.. code-block:: jinja + + {{ var is odd }} + +.. seealso:: :doc:`even<../tests/even>` diff --git a/vendor/twig/twig/doc/tests/sameas.rst b/vendor/twig/twig/doc/tests/sameas.rst new file mode 100644 index 0000000..16f904d --- /dev/null +++ b/vendor/twig/twig/doc/tests/sameas.rst @@ -0,0 +1,14 @@ +``same as`` +=========== + +.. versionadded:: 1.14.2 + The ``same as`` test was added in Twig 1.14.2 as an alias for ``sameas``. + +``same as`` checks if a variable is the same as another variable. +This is the equivalent to ``===`` in PHP: + +.. code-block:: jinja + + {% if foo.attribute is same as(false) %} + the foo attribute really is the 'false' PHP value + {% endif %} diff --git a/vendor/twig/twig/ext/twig/.gitignore b/vendor/twig/twig/ext/twig/.gitignore new file mode 100644 index 0000000..56ea76c --- /dev/null +++ b/vendor/twig/twig/ext/twig/.gitignore @@ -0,0 +1,30 @@ +*.sw* +.deps +Makefile +Makefile.fragments +Makefile.global +Makefile.objects +acinclude.m4 +aclocal.m4 +build/ +config.cache +config.guess +config.h +config.h.in +config.log +config.nice +config.status +config.sub +configure +configure.in +install-sh +libtool +ltmain.sh +missing +mkinstalldirs +run-tests.php +twig.loT +.libs/ +modules/ +twig.la +twig.lo diff --git a/vendor/twig/twig/ext/twig/config.m4 b/vendor/twig/twig/ext/twig/config.m4 new file mode 100644 index 0000000..83486be --- /dev/null +++ b/vendor/twig/twig/ext/twig/config.m4 @@ -0,0 +1,8 @@ +dnl config.m4 for extension twig + +PHP_ARG_ENABLE(twig, whether to enable twig support, +[ --enable-twig Enable twig support]) + +if test "$PHP_TWIG" != "no"; then + PHP_NEW_EXTENSION(twig, twig.c, $ext_shared) +fi diff --git a/vendor/twig/twig/ext/twig/config.w32 b/vendor/twig/twig/ext/twig/config.w32 new file mode 100644 index 0000000..cb287b9 --- /dev/null +++ b/vendor/twig/twig/ext/twig/config.w32 @@ -0,0 +1,8 @@ +// vim:ft=javascript + +ARG_ENABLE("twig", "Twig support", "no"); + +if (PHP_TWIG != "no") { + AC_DEFINE('HAVE_TWIG', 1); + EXTENSION('twig', 'twig.c'); +} diff --git a/vendor/twig/twig/ext/twig/php_twig.h b/vendor/twig/twig/ext/twig/php_twig.h new file mode 100644 index 0000000..727d9da --- /dev/null +++ b/vendor/twig/twig/ext/twig/php_twig.h @@ -0,0 +1,35 @@ +/* + +----------------------------------------------------------------------+ + | Twig Extension | + +----------------------------------------------------------------------+ + | Copyright (c) 2011 Derick Rethans | + +----------------------------------------------------------------------+ + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the conditions mentioned | + | in the accompanying LICENSE file are met (BSD-3-Clause). | + +----------------------------------------------------------------------+ + | Author: Derick Rethans | + +----------------------------------------------------------------------+ + */ + +#ifndef PHP_TWIG_H +#define PHP_TWIG_H + +#define PHP_TWIG_VERSION "1.36.0" + +#include "php.h" + +extern zend_module_entry twig_module_entry; +#define phpext_twig_ptr &twig_module_entry +#ifndef PHP_WIN32 +zend_module_entry *get_module(void); +#endif + +#ifdef ZTS +#include "TSRM.h" +#endif + +PHP_FUNCTION(twig_template_get_attributes); +PHP_RSHUTDOWN_FUNCTION(twig); + +#endif diff --git a/vendor/twig/twig/ext/twig/twig.c b/vendor/twig/twig/ext/twig/twig.c new file mode 100644 index 0000000..b81d8ce --- /dev/null +++ b/vendor/twig/twig/ext/twig/twig.c @@ -0,0 +1,1217 @@ +/* + +----------------------------------------------------------------------+ + | Twig Extension | + +----------------------------------------------------------------------+ + | Copyright (c) 2011 Derick Rethans | + +----------------------------------------------------------------------+ + | Redistribution and use in source and binary forms, with or without | + | modification, are permitted provided that the conditions mentioned | + | in the accompanying LICENSE file are met (BSD-3-Clause). | + +----------------------------------------------------------------------+ + | Author: Derick Rethans | + +----------------------------------------------------------------------+ + */ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "php.h" +#include "php_twig.h" +#include "ext/standard/php_var.h" +#include "ext/standard/php_string.h" +#include "ext/standard/php_smart_str.h" +#include "ext/spl/spl_exceptions.h" + +#include "Zend/zend_object_handlers.h" +#include "Zend/zend_interfaces.h" +#include "Zend/zend_exceptions.h" + +#ifndef Z_ADDREF_P +#define Z_ADDREF_P(pz) (pz)->refcount++ +#endif + +#ifndef E_USER_DEPRECATED +#define E_USER_DEPRECATED (1<<14L) +#endif + +#define FREE_DTOR(z) \ + zval_dtor(z); \ + efree(z); + +#if PHP_VERSION_ID >= 50300 + #define APPLY_TSRMLS_DC TSRMLS_DC + #define APPLY_TSRMLS_CC TSRMLS_CC + #define APPLY_TSRMLS_FETCH() +#else + #define APPLY_TSRMLS_DC + #define APPLY_TSRMLS_CC + #define APPLY_TSRMLS_FETCH() TSRMLS_FETCH() +#endif + +ZEND_BEGIN_ARG_INFO_EX(twig_template_get_attribute_args, ZEND_SEND_BY_VAL, ZEND_RETURN_VALUE, 6) + ZEND_ARG_INFO(0, template) + ZEND_ARG_INFO(0, object) + ZEND_ARG_INFO(0, item) + ZEND_ARG_INFO(0, arguments) + ZEND_ARG_INFO(0, type) + ZEND_ARG_INFO(0, isDefinedTest) +ZEND_END_ARG_INFO() + +#ifndef PHP_FE_END +#define PHP_FE_END { NULL, NULL, NULL} +#endif + +static const zend_function_entry twig_functions[] = { + PHP_FE(twig_template_get_attributes, twig_template_get_attribute_args) + PHP_FE_END +}; + +PHP_RSHUTDOWN_FUNCTION(twig) +{ +#if ZEND_DEBUG + CG(unclean_shutdown) = 0; /* get rid of PHPUnit's exit() and report memleaks */ +#endif + return SUCCESS; +} + +zend_module_entry twig_module_entry = { + STANDARD_MODULE_HEADER, + "twig", + twig_functions, + NULL, + NULL, + NULL, + PHP_RSHUTDOWN(twig), + NULL, + PHP_TWIG_VERSION, + STANDARD_MODULE_PROPERTIES +}; + + +#ifdef COMPILE_DL_TWIG +ZEND_GET_MODULE(twig) +#endif + +static int TWIG_ARRAY_KEY_EXISTS(zval *array, zval *key) +{ + if (Z_TYPE_P(array) != IS_ARRAY) { + return 0; + } + + switch (Z_TYPE_P(key)) { + case IS_NULL: + return zend_hash_exists(Z_ARRVAL_P(array), "", 1); + + case IS_BOOL: + case IS_DOUBLE: + convert_to_long(key); + case IS_LONG: + return zend_hash_index_exists(Z_ARRVAL_P(array), Z_LVAL_P(key)); + + default: + convert_to_string(key); + return zend_symtable_exists(Z_ARRVAL_P(array), Z_STRVAL_P(key), Z_STRLEN_P(key) + 1); + } +} + +static int TWIG_INSTANCE_OF(zval *object, zend_class_entry *interface TSRMLS_DC) +{ + if (Z_TYPE_P(object) != IS_OBJECT) { + return 0; + } + return instanceof_function(Z_OBJCE_P(object), interface TSRMLS_CC); +} + +static int TWIG_INSTANCE_OF_USERLAND(zval *object, char *interface TSRMLS_DC) +{ + zend_class_entry **pce; + if (Z_TYPE_P(object) != IS_OBJECT) { + return 0; + } + if (zend_lookup_class(interface, strlen(interface), &pce TSRMLS_CC) == FAILURE) { + return 0; + } + return instanceof_function(Z_OBJCE_P(object), *pce TSRMLS_CC); +} + +static zval *TWIG_GET_ARRAYOBJECT_ELEMENT(zval *object, zval *offset TSRMLS_DC) +{ + zend_class_entry *ce = Z_OBJCE_P(object); + zval *retval; + + if (Z_TYPE_P(object) == IS_OBJECT) { + SEPARATE_ARG_IF_REF(offset); + zend_call_method_with_1_params(&object, ce, NULL, "offsetget", &retval, offset); + + zval_ptr_dtor(&offset); + + if (!retval) { + if (!EG(exception)) { + zend_error(E_ERROR, "Undefined offset for object of type %s used as array.", ce->name); + } + return NULL; + } + + return retval; + } + return NULL; +} + +static int TWIG_ISSET_ARRAYOBJECT_ELEMENT(zval *object, zval *offset TSRMLS_DC) +{ + zend_class_entry *ce = Z_OBJCE_P(object); + zval *retval; + + if (Z_TYPE_P(object) == IS_OBJECT) { + SEPARATE_ARG_IF_REF(offset); + zend_call_method_with_1_params(&object, ce, NULL, "offsetexists", &retval, offset); + + zval_ptr_dtor(&offset); + + if (!retval) { + if (!EG(exception)) { + zend_error(E_ERROR, "Undefined offset for object of type %s used as array.", ce->name); + } + return 0; + } + + return (retval && Z_TYPE_P(retval) == IS_BOOL && Z_LVAL_P(retval)); + } + return 0; +} + +static char *TWIG_STRTOLOWER(const char *str, int str_len) +{ + char *item_dup; + + item_dup = estrndup(str, str_len); + php_strtolower(item_dup, str_len); + return item_dup; +} + +static zval *TWIG_CALL_USER_FUNC_ARRAY(zval *object, char *function, zval *arguments TSRMLS_DC) +{ + zend_fcall_info fci; + zval ***args = NULL; + int arg_count = 0; + HashTable *table; + HashPosition pos; + int i = 0; + zval *retval_ptr; + zval *zfunction; + + if (arguments) { + table = HASH_OF(arguments); + args = safe_emalloc(sizeof(zval **), table->nNumOfElements, 0); + + zend_hash_internal_pointer_reset_ex(table, &pos); + + while (zend_hash_get_current_data_ex(table, (void **)&args[i], &pos) == SUCCESS) { + i++; + zend_hash_move_forward_ex(table, &pos); + } + arg_count = table->nNumOfElements; + } + + MAKE_STD_ZVAL(zfunction); + ZVAL_STRING(zfunction, function, 1); + fci.size = sizeof(fci); + fci.function_table = EG(function_table); + fci.function_name = zfunction; + fci.symbol_table = NULL; +#if PHP_VERSION_ID >= 50300 + fci.object_ptr = object; +#else + fci.object_pp = &object; +#endif + fci.retval_ptr_ptr = &retval_ptr; + fci.param_count = arg_count; + fci.params = args; + fci.no_separation = 0; + + if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE) { + ALLOC_INIT_ZVAL(retval_ptr); + ZVAL_BOOL(retval_ptr, 0); + } + + if (args) { + efree(fci.params); + } + FREE_DTOR(zfunction); + return retval_ptr; +} + +static int TWIG_CALL_BOOLEAN(zval *object, char *functionName TSRMLS_DC) +{ + zval *ret; + int res; + + ret = TWIG_CALL_USER_FUNC_ARRAY(object, functionName, NULL TSRMLS_CC); + res = Z_LVAL_P(ret); + zval_ptr_dtor(&ret); + return res; +} + +static zval *TWIG_GET_STATIC_PROPERTY(zval *class, char *prop_name TSRMLS_DC) +{ + zval **tmp_zval; + zend_class_entry *ce; + + if (class == NULL || Z_TYPE_P(class) != IS_OBJECT) { + return NULL; + } + + ce = zend_get_class_entry(class TSRMLS_CC); +#if PHP_VERSION_ID >= 50400 + tmp_zval = zend_std_get_static_property(ce, prop_name, strlen(prop_name), 0, NULL TSRMLS_CC); +#else + tmp_zval = zend_std_get_static_property(ce, prop_name, strlen(prop_name), 0 TSRMLS_CC); +#endif + return *tmp_zval; +} + +static zval *TWIG_GET_ARRAY_ELEMENT_ZVAL(zval *class, zval *prop_name TSRMLS_DC) +{ + zval **tmp_zval; + + if (class == NULL || Z_TYPE_P(class) != IS_ARRAY) { + if (class != NULL && Z_TYPE_P(class) == IS_OBJECT && TWIG_INSTANCE_OF(class, zend_ce_arrayaccess TSRMLS_CC)) { + // array access object + return TWIG_GET_ARRAYOBJECT_ELEMENT(class, prop_name TSRMLS_CC); + } + return NULL; + } + + switch(Z_TYPE_P(prop_name)) { + case IS_NULL: + zend_hash_find(HASH_OF(class), "", 1, (void**) &tmp_zval); + return *tmp_zval; + + case IS_BOOL: + case IS_DOUBLE: + convert_to_long(prop_name); + case IS_LONG: + zend_hash_index_find(HASH_OF(class), Z_LVAL_P(prop_name), (void **) &tmp_zval); + return *tmp_zval; + + case IS_STRING: + zend_symtable_find(HASH_OF(class), Z_STRVAL_P(prop_name), Z_STRLEN_P(prop_name) + 1, (void**) &tmp_zval); + return *tmp_zval; + } + + return NULL; +} + +static zval *TWIG_GET_ARRAY_ELEMENT(zval *class, char *prop_name, int prop_name_length TSRMLS_DC) +{ + zval **tmp_zval; + + if (class == NULL/* || Z_TYPE_P(class) != IS_ARRAY*/) { + return NULL; + } + + if (class != NULL && Z_TYPE_P(class) == IS_OBJECT && TWIG_INSTANCE_OF(class, zend_ce_arrayaccess TSRMLS_CC)) { + // array access object + zval *tmp_name_zval; + zval *tmp_ret_zval; + + ALLOC_INIT_ZVAL(tmp_name_zval); + ZVAL_STRING(tmp_name_zval, prop_name, 1); + tmp_ret_zval = TWIG_GET_ARRAYOBJECT_ELEMENT(class, tmp_name_zval TSRMLS_CC); + FREE_DTOR(tmp_name_zval); + return tmp_ret_zval; + } + + if (zend_symtable_find(HASH_OF(class), prop_name, prop_name_length+1, (void**)&tmp_zval) == SUCCESS) { + return *tmp_zval; + } + return NULL; +} + +static zval *TWIG_PROPERTY(zval *object, zval *propname TSRMLS_DC) +{ + zval *tmp = NULL; + + if (Z_OBJ_HT_P(object)->read_property) { +#if PHP_VERSION_ID >= 50400 + tmp = Z_OBJ_HT_P(object)->read_property(object, propname, BP_VAR_IS, NULL TSRMLS_CC); +#else + tmp = Z_OBJ_HT_P(object)->read_property(object, propname, BP_VAR_IS TSRMLS_CC); +#endif + if (tmp == EG(uninitialized_zval_ptr)) { + ZVAL_NULL(tmp); + } + } + return tmp; +} + +static int TWIG_HAS_PROPERTY(zval *object, zval *propname TSRMLS_DC) +{ + if (Z_OBJ_HT_P(object)->has_property) { +#if PHP_VERSION_ID >= 50400 + return Z_OBJ_HT_P(object)->has_property(object, propname, 0, NULL TSRMLS_CC); +#else + return Z_OBJ_HT_P(object)->has_property(object, propname, 0 TSRMLS_CC); +#endif + } + return 0; +} + +static int TWIG_HAS_DYNAMIC_PROPERTY(zval *object, char *prop, int prop_len TSRMLS_DC) +{ + if (Z_OBJ_HT_P(object)->get_properties) { + return zend_hash_quick_exists( + Z_OBJ_HT_P(object)->get_properties(object TSRMLS_CC), // the properties hash + prop, // property name + prop_len + 1, // property length + zend_get_hash_value(prop, prop_len + 1) // hash value + ); + } + return 0; +} + +static zval *TWIG_PROPERTY_CHAR(zval *object, char *propname TSRMLS_DC) +{ + zval *tmp_name_zval, *tmp; + + ALLOC_INIT_ZVAL(tmp_name_zval); + ZVAL_STRING(tmp_name_zval, propname, 1); + tmp = TWIG_PROPERTY(object, tmp_name_zval TSRMLS_CC); + FREE_DTOR(tmp_name_zval); + return tmp; +} + +static zval *TWIG_CALL_S(zval *object, char *method, char *arg0 TSRMLS_DC) +{ + zend_fcall_info fci; + zval **args[1]; + zval *argument; + zval *zfunction; + zval *retval_ptr; + + MAKE_STD_ZVAL(argument); + ZVAL_STRING(argument, arg0, 1); + args[0] = &argument; + + MAKE_STD_ZVAL(zfunction); + ZVAL_STRING(zfunction, method, 1); + fci.size = sizeof(fci); + fci.function_table = EG(function_table); + fci.function_name = zfunction; + fci.symbol_table = NULL; +#if PHP_VERSION_ID >= 50300 + fci.object_ptr = object; +#else + fci.object_pp = &object; +#endif + fci.retval_ptr_ptr = &retval_ptr; + fci.param_count = 1; + fci.params = args; + fci.no_separation = 0; + + if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE) { + FREE_DTOR(zfunction); + zval_ptr_dtor(&argument); + return 0; + } + FREE_DTOR(zfunction); + zval_ptr_dtor(&argument); + return retval_ptr; +} + +static int TWIG_CALL_SB(zval *object, char *method, char *arg0 TSRMLS_DC) +{ + zval *retval_ptr; + int success; + + retval_ptr = TWIG_CALL_S(object, method, arg0 TSRMLS_CC); + success = (retval_ptr && (Z_TYPE_P(retval_ptr) == IS_BOOL) && Z_LVAL_P(retval_ptr)); + + if (retval_ptr) { + zval_ptr_dtor(&retval_ptr); + } + + return success; +} + +static int TWIG_CALL_ZZ(zval *object, char *method, zval *arg1, zval *arg2 TSRMLS_DC) +{ + zend_fcall_info fci; + zval **args[2]; + zval *zfunction; + zval *retval_ptr; + int success; + + args[0] = &arg1; + args[1] = &arg2; + + MAKE_STD_ZVAL(zfunction); + ZVAL_STRING(zfunction, method, 1); + fci.size = sizeof(fci); + fci.function_table = EG(function_table); + fci.function_name = zfunction; + fci.symbol_table = NULL; +#if PHP_VERSION_ID >= 50300 + fci.object_ptr = object; +#else + fci.object_pp = &object; +#endif + fci.retval_ptr_ptr = &retval_ptr; + fci.param_count = 2; + fci.params = args; + fci.no_separation = 0; + + if (zend_call_function(&fci, NULL TSRMLS_CC) == FAILURE) { + FREE_DTOR(zfunction); + return 0; + } + + FREE_DTOR(zfunction); + + success = (retval_ptr && (Z_TYPE_P(retval_ptr) == IS_BOOL) && Z_LVAL_P(retval_ptr)); + if (retval_ptr) { + zval_ptr_dtor(&retval_ptr); + } + + return success; +} + +#ifndef Z_SET_REFCOUNT_P +# define Z_SET_REFCOUNT_P(pz, rc) pz->refcount = rc +# define Z_UNSET_ISREF_P(pz) pz->is_ref = 0 +#endif + +static void TWIG_NEW(zval *object, char *class, zval *arg0, zval *arg1 TSRMLS_DC) +{ + zend_class_entry **pce; + + if (zend_lookup_class(class, strlen(class), &pce TSRMLS_CC) == FAILURE) { + return; + } + + Z_TYPE_P(object) = IS_OBJECT; + object_init_ex(object, *pce); + Z_SET_REFCOUNT_P(object, 1); + Z_UNSET_ISREF_P(object); + + TWIG_CALL_ZZ(object, "__construct", arg0, arg1 TSRMLS_CC); +} + +static int twig_add_array_key_to_string(void *pDest APPLY_TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) +{ + smart_str *buf; + char *joiner; + APPLY_TSRMLS_FETCH(); + + buf = va_arg(args, smart_str*); + joiner = va_arg(args, char*); + + if (buf->len != 0) { + smart_str_appends(buf, joiner); + } + + if (hash_key->nKeyLength == 0) { + smart_str_append_long(buf, (long) hash_key->h); + } else { + char *key, *tmp_str; + int key_len, tmp_len; + key = php_addcslashes(hash_key->arKey, hash_key->nKeyLength - 1, &key_len, 0, "'\\", 2 TSRMLS_CC); + tmp_str = php_str_to_str_ex(key, key_len, "\0", 1, "' . \"\\0\" . '", 12, &tmp_len, 0, NULL); + + smart_str_appendl(buf, tmp_str, tmp_len); + efree(key); + efree(tmp_str); + } + + return 0; +} + +static char *TWIG_IMPLODE_ARRAY_KEYS(char *joiner, zval *array TSRMLS_DC) +{ + smart_str collector = { 0, 0, 0 }; + + smart_str_appendl(&collector, "", 0); + zend_hash_apply_with_arguments(HASH_OF(array) APPLY_TSRMLS_CC, twig_add_array_key_to_string, 2, &collector, joiner); + smart_str_0(&collector); + + return collector.c; +} + +static void TWIG_RUNTIME_ERROR(zval *template TSRMLS_DC, char *message, ...) +{ + char *buffer; + va_list args; + zend_class_entry **pce; + zval *ex; + zval *constructor; + zval *zmessage; + zval *lineno; + zval *filename_func; + zval *filename; + zval *constructor_args[3]; + zval *constructor_retval; + + if (zend_lookup_class("Twig_Error_Runtime", strlen("Twig_Error_Runtime"), &pce TSRMLS_CC) == FAILURE) { + return; + } + + va_start(args, message); + vspprintf(&buffer, 0, message, args); + va_end(args); + + MAKE_STD_ZVAL(ex); + object_init_ex(ex, *pce); + + // Call Twig_Error constructor + MAKE_STD_ZVAL(constructor); + MAKE_STD_ZVAL(zmessage); + MAKE_STD_ZVAL(lineno); + MAKE_STD_ZVAL(filename); + MAKE_STD_ZVAL(filename_func); + MAKE_STD_ZVAL(constructor_retval); + + ZVAL_STRINGL(constructor, "__construct", sizeof("__construct")-1, 1); + ZVAL_STRING(zmessage, buffer, 1); + ZVAL_LONG(lineno, -1); + + // Get template filename + ZVAL_STRINGL(filename_func, "getTemplateName", sizeof("getTemplateName")-1, 1); + call_user_function(EG(function_table), &template, filename_func, filename, 0, 0 TSRMLS_CC); + + constructor_args[0] = zmessage; + constructor_args[1] = lineno; + constructor_args[2] = filename; + call_user_function(EG(function_table), &ex, constructor, constructor_retval, 3, constructor_args TSRMLS_CC); + + zval_ptr_dtor(&constructor_retval); + zval_ptr_dtor(&zmessage); + zval_ptr_dtor(&lineno); + zval_ptr_dtor(&filename); + FREE_DTOR(constructor); + FREE_DTOR(filename_func); + efree(buffer); + + zend_throw_exception_object(ex TSRMLS_CC); +} + +static char *TWIG_GET_CLASS_NAME(zval *object TSRMLS_DC) +{ + char *class_name; + zend_uint class_name_len; + + if (Z_TYPE_P(object) != IS_OBJECT) { + return ""; + } +#if PHP_API_VERSION >= 20100412 + zend_get_object_classname(object, (const char **) &class_name, &class_name_len TSRMLS_CC); +#else + zend_get_object_classname(object, &class_name, &class_name_len TSRMLS_CC); +#endif + return class_name; +} + +static int twig_add_method_to_class(void *pDest APPLY_TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) +{ + zend_class_entry *ce; + zval *retval; + char *item; + size_t item_len; + zend_function *mptr = (zend_function *) pDest; + APPLY_TSRMLS_FETCH(); + + if (!(mptr->common.fn_flags & ZEND_ACC_PUBLIC)) { + return 0; + } + + ce = *va_arg(args, zend_class_entry**); + retval = va_arg(args, zval*); + + item_len = strlen(mptr->common.function_name); + item = estrndup(mptr->common.function_name, item_len); + php_strtolower(item, item_len); + + if (strcmp("getenvironment", item) == 0) { + zend_class_entry **twig_template_ce; + if (zend_lookup_class("Twig_Template", strlen("Twig_Template"), &twig_template_ce TSRMLS_CC) == FAILURE) { + return 0; + } + if (instanceof_function(ce, *twig_template_ce TSRMLS_CC)) { + return 0; + } + } + + add_assoc_stringl_ex(retval, item, item_len+1, item, item_len, 0); + + return 0; +} + +static int twig_add_property_to_class(void *pDest APPLY_TSRMLS_DC, int num_args, va_list args, zend_hash_key *hash_key) +{ + zend_class_entry *ce; + zval *retval; + char *class_name, *prop_name; + zend_property_info *pptr = (zend_property_info *) pDest; + APPLY_TSRMLS_FETCH(); + + if (!(pptr->flags & ZEND_ACC_PUBLIC) || (pptr->flags & ZEND_ACC_STATIC)) { + return 0; + } + + ce = *va_arg(args, zend_class_entry**); + retval = va_arg(args, zval*); + +#if PHP_API_VERSION >= 20100412 + zend_unmangle_property_name(pptr->name, pptr->name_length, (const char **) &class_name, (const char **) &prop_name); +#else + zend_unmangle_property_name(pptr->name, pptr->name_length, &class_name, &prop_name); +#endif + + add_assoc_string(retval, prop_name, prop_name, 1); + + return 0; +} + +static void twig_add_class_to_cache(zval *cache, zval *object, char *class_name TSRMLS_DC) +{ + zval *class_info, *class_methods, *class_properties; + zend_class_entry *class_ce; + + class_ce = zend_get_class_entry(object TSRMLS_CC); + + ALLOC_INIT_ZVAL(class_info); + ALLOC_INIT_ZVAL(class_methods); + ALLOC_INIT_ZVAL(class_properties); + array_init(class_info); + array_init(class_methods); + array_init(class_properties); + // add all methods to self::cache[$class]['methods'] + zend_hash_apply_with_arguments(&class_ce->function_table APPLY_TSRMLS_CC, twig_add_method_to_class, 2, &class_ce, class_methods); + zend_hash_apply_with_arguments(&class_ce->properties_info APPLY_TSRMLS_CC, twig_add_property_to_class, 2, &class_ce, class_properties); + + add_assoc_zval(class_info, "methods", class_methods); + add_assoc_zval(class_info, "properties", class_properties); + add_assoc_zval(cache, class_name, class_info); +} + +/* {{{ proto mixed twig_template_get_attributes(TwigTemplate template, mixed object, mixed item, array arguments, string type, boolean isDefinedTest, boolean ignoreStrictCheck) + A C implementation of TwigTemplate::getAttribute() */ +PHP_FUNCTION(twig_template_get_attributes) +{ + zval *template; + zval *object; + char *item; + int item_len; + zval *zitem, ztmpitem; + zval *arguments = NULL; + zval *ret = NULL; + char *type = NULL; + int type_len = 0; + zend_bool isDefinedTest = 0; + zend_bool ignoreStrictCheck = 0; + int free_ret = 0; + zval *tmp_self_cache; + char *class_name = NULL; + zval *tmp_class; + char *type_name; + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "ozz|asbb", &template, &object, &zitem, &arguments, &type, &type_len, &isDefinedTest, &ignoreStrictCheck) == FAILURE) { + return; + } + + // convert the item to a string + ztmpitem = *zitem; + zval_copy_ctor(&ztmpitem); + convert_to_string(&ztmpitem); + item_len = Z_STRLEN(ztmpitem); + item = estrndup(Z_STRVAL(ztmpitem), item_len); + zval_dtor(&ztmpitem); + + if (!type) { + type = "any"; + } + +/* + // array + if (Twig_Template::METHOD_CALL !== $type) { + $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item; + + if ((is_array($object) && array_key_exists($arrayItem, $object)) + || ($object instanceof ArrayAccess && isset($object[$arrayItem])) + ) { + if ($isDefinedTest) { + return true; + } + + return $object[$arrayItem]; + } +*/ + + + if (strcmp("method", type) != 0) { + if ((TWIG_ARRAY_KEY_EXISTS(object, zitem)) + || (TWIG_INSTANCE_OF(object, zend_ce_arrayaccess TSRMLS_CC) && TWIG_ISSET_ARRAYOBJECT_ELEMENT(object, zitem TSRMLS_CC)) + ) { + + if (isDefinedTest) { + efree(item); + RETURN_TRUE; + } + + ret = TWIG_GET_ARRAY_ELEMENT_ZVAL(object, zitem TSRMLS_CC); + + if (!ret) { + ret = &EG(uninitialized_zval); + } + RETVAL_ZVAL(ret, 1, 0); + if (free_ret) { + zval_ptr_dtor(&ret); + } + efree(item); + return; + } +/* + if (Twig_Template::ARRAY_CALL === $type) { + if ($isDefinedTest) { + return false; + } + if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { + return null; + } +*/ + if (strcmp("array", type) == 0 || Z_TYPE_P(object) != IS_OBJECT) { + if (isDefinedTest) { + efree(item); + RETURN_FALSE; + } + if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) { + efree(item); + 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 (empty($object)) { + $message = sprintf('Key "%s" does not exist as the array is empty', $arrayItem); + } else { + $message = sprintf('Key "%s" for array with keys "%s" does not exist', $arrayItem, implode(', ', array_keys($object))); + } + } elseif (Twig_Template::ARRAY_CALL === $type) { + 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); + } + } 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); + } + throw new Twig_Error_Runtime($message, -1, $this->getTemplateName()); + } + } +*/ + if (TWIG_INSTANCE_OF(object, zend_ce_arrayaccess TSRMLS_CC)) { + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Key \"%s\" in object with ArrayAccess of class \"%s\" does not exist.", item, TWIG_GET_CLASS_NAME(object TSRMLS_CC)); + } else if (Z_TYPE_P(object) == IS_OBJECT) { + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Impossible to access a key \"%s\" on an object of class \"%s\" that does not implement ArrayAccess interface.", item, TWIG_GET_CLASS_NAME(object TSRMLS_CC)); + } else if (Z_TYPE_P(object) == IS_ARRAY) { + if (0 == zend_hash_num_elements(Z_ARRVAL_P(object))) { + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Key \"%s\" does not exist as the array is empty.", item); + } else { + char *array_keys = TWIG_IMPLODE_ARRAY_KEYS(", ", object TSRMLS_CC); + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Key \"%s\" for array with keys \"%s\" does not exist.", item, array_keys); + efree(array_keys); + } + } else { + char *type_name = zend_zval_type_name(object); + Z_ADDREF_P(object); + if (Z_TYPE_P(object) == IS_NULL) { + convert_to_string(object); + TWIG_RUNTIME_ERROR(template TSRMLS_CC, + (strcmp("array", type) == 0) + ? "Impossible to access a key (\"%s\") on a %s variable." + : "Impossible to access an attribute (\"%s\") on a %s variable.", + item, type_name); + } else { + convert_to_string(object); + TWIG_RUNTIME_ERROR(template TSRMLS_CC, + (strcmp("array", type) == 0) + ? "Impossible to access a key (\"%s\") on a %s variable (\"%s\")." + : "Impossible to access an attribute (\"%s\") on a %s variable (\"%s\").", + item, type_name, Z_STRVAL_P(object)); + } + zval_ptr_dtor(&object); + } + efree(item); + return; + } + } + +/* + if (!is_object($object)) { + if ($isDefinedTest) { + return false; + } +*/ + + if (Z_TYPE_P(object) != IS_OBJECT) { + if (isDefinedTest) { + efree(item); + RETURN_FALSE; + } +/* + if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { + return null; + } + + 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); + } + + throw new Twig_Error_Runtime($message, -1, $this->getTemplateName()); + } +*/ + if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) { + efree(item); + return; + } + + type_name = zend_zval_type_name(object); + Z_ADDREF_P(object); + if (Z_TYPE_P(object) == IS_NULL) { + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Impossible to invoke a method (\"%s\") on a null variable.", item); + } else if (Z_TYPE_P(object) == IS_ARRAY) { + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Impossible to invoke a method (\"%s\") on an array.", item); + } else { + convert_to_string_ex(&object); + + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Impossible to invoke a method (\"%s\") on a %s variable (\"%s\").", item, type_name, Z_STRVAL_P(object)); + } + + zval_ptr_dtor(&object); + efree(item); + return; + } +/* + $class = get_class($object); +*/ + + class_name = TWIG_GET_CLASS_NAME(object TSRMLS_CC); + tmp_self_cache = TWIG_GET_STATIC_PROPERTY(template, "cache" TSRMLS_CC); + tmp_class = TWIG_GET_ARRAY_ELEMENT(tmp_self_cache, class_name, strlen(class_name) TSRMLS_CC); + + if (!tmp_class) { + twig_add_class_to_cache(tmp_self_cache, object, class_name TSRMLS_CC); + tmp_class = TWIG_GET_ARRAY_ELEMENT(tmp_self_cache, class_name, strlen(class_name) TSRMLS_CC); + } + efree(class_name); + +/* + // object property + if (Twig_Template::METHOD_CALL !== $type && !$object instanceof Twig_Template) { + if (isset($object->$item) || array_key_exists((string) $item, $object)) { + if ($isDefinedTest) { + return true; + } + + if ($this->env->hasExtension('Twig_Extension_Sandbox')) { + $this->env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item); + } + + return $object->$item; + } + } +*/ + if (strcmp("method", type) != 0 && !TWIG_INSTANCE_OF_USERLAND(object, "Twig_Template" TSRMLS_CC)) { + zval *tmp_properties, *tmp_item; + + tmp_properties = TWIG_GET_ARRAY_ELEMENT(tmp_class, "properties", strlen("properties") TSRMLS_CC); + tmp_item = TWIG_GET_ARRAY_ELEMENT(tmp_properties, item, item_len TSRMLS_CC); + + if (tmp_item || TWIG_HAS_PROPERTY(object, zitem TSRMLS_CC) || TWIG_HAS_DYNAMIC_PROPERTY(object, item, item_len TSRMLS_CC)) { + if (isDefinedTest) { + efree(item); + RETURN_TRUE; + } + if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "Twig_Extension_Sandbox" TSRMLS_CC)) { + TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "Twig_Extension_Sandbox" TSRMLS_CC), "checkPropertyAllowed", object, zitem TSRMLS_CC); + } + if (EG(exception)) { + efree(item); + return; + } + + ret = TWIG_PROPERTY(object, zitem TSRMLS_CC); + efree(item); + RETURN_ZVAL(ret, 1, 0); + } + } +/* + // object method + if (!isset(self::$cache[$class]['methods'])) { + if ($object instanceof self) { + $ref = new ReflectionClass($class); + $methods = array(); + + foreach ($ref->getMethods(ReflectionMethod::IS_PUBLIC) as $refMethod) { + $methodName = strtolower($refMethod->name); + + // Accessing the environment from templates is forbidden to prevent untrusted changes to the environment + if ('getenvironment' !== $methodName) { + $methods[$methodName] = true; + } + } + + self::$cache[$class]['methods'] = $methods; + } else { + self::$cache[$class]['methods'] = array_change_key_case(array_flip(get_class_methods($object))); + } + } + + $call = false; + $lcItem = strtolower($item); + if (isset(self::$cache[$class]['methods'][$lcItem])) { + $method = (string) $item; + } elseif (isset(self::$cache[$class]['methods']['get'.$lcItem])) { + $method = 'get'.$item; + } elseif (isset(self::$cache[$class]['methods']['is'.$lcItem])) { + $method = 'is'.$item; + } elseif (isset(self::$cache[$class]['methods']['__call'])) { + $method = (string) $item; + $call = true; +*/ + { + int call = 0; + char *lcItem = TWIG_STRTOLOWER(item, item_len); + int lcItem_length; + char *method = NULL; + char *methodForDeprecation = NULL; + char *tmp_method_name_get; + char *tmp_method_name_is; + zval *zmethod; + zval *tmp_methods; + + lcItem_length = strlen(lcItem); + tmp_method_name_get = emalloc(4 + lcItem_length); + tmp_method_name_is = emalloc(3 + lcItem_length); + + sprintf(tmp_method_name_get, "get%s", lcItem); + sprintf(tmp_method_name_is, "is%s", lcItem); + + tmp_methods = TWIG_GET_ARRAY_ELEMENT(tmp_class, "methods", strlen("methods") TSRMLS_CC); + methodForDeprecation = emalloc(item_len + 1); + sprintf(methodForDeprecation, "%s", item); + + if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, lcItem, lcItem_length TSRMLS_CC)) { + method = item; + } else if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, tmp_method_name_get, lcItem_length + 3 TSRMLS_CC)) { + method = tmp_method_name_get; + } else if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, tmp_method_name_is, lcItem_length + 2 TSRMLS_CC)) { + method = tmp_method_name_is; + } else if (TWIG_GET_ARRAY_ELEMENT(tmp_methods, "__call", 6 TSRMLS_CC)) { + method = item; + call = 1; +/* + } else { + if ($isDefinedTest) { + return false; + } + + if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { + return null; + } + + throw new Twig_Error_Runtime(sprintf('Method "%s" for object "%s" does not exist.', $item, get_class($object)), -1, $this->getTemplateName()); + } + + if ($isDefinedTest) { + return true; + } +*/ + } else { + efree(tmp_method_name_get); + efree(tmp_method_name_is); + efree(lcItem); + + if (isDefinedTest) { + efree(item); + RETURN_FALSE; + } + if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) { + efree(item); + return; + } + TWIG_RUNTIME_ERROR(template TSRMLS_CC, "Neither the property \"%s\" nor one of the methods \"%s()\", \"get%s()\"/\"is%s()\" or \"__call()\" exist and have public access in class \"%s\".", item, item, item, item, TWIG_GET_CLASS_NAME(object TSRMLS_CC)); + efree(item); + return; + } + + if (isDefinedTest) { + efree(tmp_method_name_get); + efree(tmp_method_name_is); + efree(lcItem);efree(item); + RETURN_TRUE; + } +/* + if ($this->env->hasExtension('Twig_Extension_Sandbox')) { + $this->env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method); + } +*/ + MAKE_STD_ZVAL(zmethod); + ZVAL_STRING(zmethod, method, 1); + if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "Twig_Extension_Sandbox" TSRMLS_CC)) { + TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "Twig_Extension_Sandbox" TSRMLS_CC), "checkMethodAllowed", object, zmethod TSRMLS_CC); + } + zval_ptr_dtor(&zmethod); + if (EG(exception)) { + efree(tmp_method_name_get); + efree(tmp_method_name_is); + efree(lcItem);efree(item); + return; + } +/* + // Some objects throw exceptions when they have __call, and the method we try + // to call is not supported. If ignoreStrictCheck is true, we should return null. + try { + $ret = call_user_func_array(array($object, $method), $arguments); + } catch (BadMethodCallException $e) { + if ($call && ($ignoreStrictCheck || !$this->env->isStrictVariables())) { + return null; + } + throw $e; + } +*/ + ret = TWIG_CALL_USER_FUNC_ARRAY(object, method, arguments TSRMLS_CC); + if (EG(exception) && TWIG_INSTANCE_OF(EG(exception), spl_ce_BadMethodCallException TSRMLS_CC)) { + if (ignoreStrictCheck || !TWIG_CALL_BOOLEAN(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "isStrictVariables" TSRMLS_CC)) { + efree(tmp_method_name_get); + efree(tmp_method_name_is); + efree(lcItem);efree(item); + zend_clear_exception(TSRMLS_C); + return; + } + } + free_ret = 1; + efree(tmp_method_name_get); + efree(tmp_method_name_is); + efree(lcItem); +/* + // @deprecated in 1.28 + 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()); + if ('renderBlock' === $method || 'displayBlock' === $method) { + $message .= sprintf(' Use block("%s"%s) instead).', $arguments[0], $self ? '' : ', template'); + } elseif ('hasBlock' === $method) { + $message .= sprintf(' Use "block("%s"%s) is defined" instead).', $arguments[0], $self ? '' : ', template'); + } elseif ('render' === $method || 'display' === $method) { + $message .= sprintf(' Use include("%s") instead).', $object->getTemplateName()); + } + @trigger_error($message, E_USER_DEPRECATED); + + return $ret === '' ? '' : new Twig_Markup($ret, $this->env->getCharset()); + } + + return $ret; +*/ + efree(item); + // ret can be null, if e.g. the called method throws an exception + if (ret) { + if (TWIG_INSTANCE_OF_USERLAND(object, "Twig_TemplateInterface" TSRMLS_CC)) { + int self; + int old_error_reporting; + zval *object_filename; + zval *this_filename; + zval *filename_func; + char *deprecation_message_complement = NULL; + char *deprecation_message = NULL; + + MAKE_STD_ZVAL(object_filename); + MAKE_STD_ZVAL(this_filename); + MAKE_STD_ZVAL(filename_func); + + // Get templates names + ZVAL_STRINGL(filename_func, "getTemplateName", sizeof("getTemplateName")-1, 1); + call_user_function(EG(function_table), &object, filename_func, object_filename, 0, 0 TSRMLS_CC); + ZVAL_STRINGL(filename_func, "getTemplateName", sizeof("getTemplateName")-1, 1); + call_user_function(EG(function_table), &template, filename_func, this_filename, 0, 0 TSRMLS_CC); + + self = (strcmp(Z_STRVAL_P(object_filename), Z_STRVAL_P(this_filename)) == 0); + + if (strcmp(methodForDeprecation, "renderBlock") == 0 || strcmp(methodForDeprecation, "displayBlock") == 0) { + zval **arg0; + zend_hash_index_find(HASH_OF(arguments), 0, (void **) &arg0); + asprintf( + &deprecation_message_complement, + " Use block(\"%s\"%s) instead).", + Z_STRVAL_PP(arg0), + self ? "" : ", template" + ); + } else if (strcmp(methodForDeprecation, "hasBlock") == 0) { + zval **arg0; + zend_hash_index_find(HASH_OF(arguments), 0, (void **) &arg0); + asprintf( + &deprecation_message_complement, + " Use \"block(\"%s\"%s) is defined\" instead).", + Z_STRVAL_PP(arg0), + self ? "" : ", template" + ); + } else if (strcmp(methodForDeprecation, "render") == 0 || strcmp(methodForDeprecation, "display") == 0) { + asprintf( + &deprecation_message_complement, + " Use include(\"%s\") instead).", + Z_STRVAL_P(object_filename) + ); + } else { + deprecation_message_complement = (char*)calloc(0, sizeof(char)); + } + + asprintf( + &deprecation_message, + "Calling \"%s\" on template \"%s\" from template \"%s\" is deprecated since version 1.28 and won't be supported anymore in 2.0.%s", + methodForDeprecation, + Z_STRVAL_P(object_filename), + Z_STRVAL_P(this_filename), + deprecation_message_complement + ); + + old_error_reporting = EG(error_reporting); + EG(error_reporting) = 0; + zend_error(E_USER_DEPRECATED, "%s", deprecation_message); + EG(error_reporting) = old_error_reporting; + + FREE_DTOR(filename_func) + FREE_DTOR(object_filename) + FREE_DTOR(this_filename) + free(deprecation_message); + free(deprecation_message_complement); + + if (Z_STRLEN_P(ret) != 0) { + zval *charset = TWIG_CALL_USER_FUNC_ARRAY(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getCharset", NULL TSRMLS_CC); + TWIG_NEW(return_value, "Twig_Markup", ret, charset TSRMLS_CC); + zval_ptr_dtor(&charset); + if (ret) { + zval_ptr_dtor(&ret); + } + efree(methodForDeprecation); + return; + } + } + + RETVAL_ZVAL(ret, 1, 0); + if (free_ret) { + zval_ptr_dtor(&ret); + } + } + + efree(methodForDeprecation); + } +} diff --git a/vendor/twig/twig/lib/Twig/Autoloader.php b/vendor/twig/twig/lib/Twig/Autoloader.php new file mode 100644 index 0000000..212af54 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Autoloader.php @@ -0,0 +1,54 @@ + + * + * @deprecated since 1.21 and will be removed in 2.0. Use Composer instead. 2.0. + */ +class Twig_Autoloader +{ + /** + * Registers Twig_Autoloader as an SPL autoloader. + * + * @param bool $prepend whether to prepend the autoloader or not + */ + public static function register($prepend = false) + { + @trigger_error('Using Twig_Autoloader is deprecated since version 1.21. Use Composer instead.', E_USER_DEPRECATED); + + if (PHP_VERSION_ID < 50300) { + spl_autoload_register(array(__CLASS__, 'autoload')); + } else { + spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend); + } + } + + /** + * Handles autoloading of classes. + * + * @param string $class a class name + */ + public static function autoload($class) + { + if (0 !== strpos($class, 'Twig')) { + return; + } + + if (is_file($file = dirname(__FILE__).'/../'.str_replace(array('_', "\0"), array('/', ''), $class).'.php')) { + require $file; + } + } +} diff --git a/vendor/twig/twig/lib/Twig/BaseNodeVisitor.php b/vendor/twig/twig/lib/Twig/BaseNodeVisitor.php new file mode 100644 index 0000000..d8ef02f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/BaseNodeVisitor.php @@ -0,0 +1,54 @@ + + */ +abstract class Twig_BaseNodeVisitor implements Twig_NodeVisitorInterface +{ + final public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) + { + if (!$node instanceof Twig_Node) { + throw new LogicException('Twig_BaseNodeVisitor only supports Twig_Node instances.'); + } + + return $this->doEnterNode($node, $env); + } + + final public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env) + { + if (!$node instanceof Twig_Node) { + throw new LogicException('Twig_BaseNodeVisitor only supports Twig_Node instances.'); + } + + return $this->doLeaveNode($node, $env); + } + + /** + * Called before child nodes are visited. + * + * @return Twig_Node The modified node + */ + abstract protected function doEnterNode(Twig_Node $node, Twig_Environment $env); + + /** + * Called after child nodes are visited. + * + * @return Twig_Node|false The modified node or false if the node must be removed + */ + abstract protected function doLeaveNode(Twig_Node $node, Twig_Environment $env); +} + +class_alias('Twig_BaseNodeVisitor', 'Twig\NodeVisitor\AbstractNodeVisitor', false); +class_exists('Twig_Environment'); +class_exists('Twig_Node'); diff --git a/vendor/twig/twig/lib/Twig/Cache/Filesystem.php b/vendor/twig/twig/lib/Twig/Cache/Filesystem.php new file mode 100644 index 0000000..6597628 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Cache/Filesystem.php @@ -0,0 +1,93 @@ + + */ +class Twig_Cache_Filesystem implements Twig_CacheInterface +{ + const FORCE_BYTECODE_INVALIDATION = 1; + + private $directory; + private $options; + + /** + * @param $directory string The root cache directory + * @param $options int 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)) { + if (PHP_VERSION_ID >= 50300) { + 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')) { + 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_Filesystem', 'Twig\Cache\FilesystemCache', false); diff --git a/vendor/twig/twig/lib/Twig/Cache/Null.php b/vendor/twig/twig/lib/Twig/Cache/Null.php new file mode 100644 index 0000000..69d1d2f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Cache/Null.php @@ -0,0 +1,40 @@ + + */ +class Twig_Cache_Null implements Twig_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_Null', 'Twig\Cache\NullCache', false); diff --git a/vendor/twig/twig/lib/Twig/CacheInterface.php b/vendor/twig/twig/lib/Twig/CacheInterface.php new file mode 100644 index 0000000..776808b --- /dev/null +++ b/vendor/twig/twig/lib/Twig/CacheInterface.php @@ -0,0 +1,58 @@ + + */ +interface Twig_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_CacheInterface', 'Twig\Cache\CacheInterface', false); diff --git a/vendor/twig/twig/lib/Twig/Compiler.php b/vendor/twig/twig/lib/Twig/Compiler.php new file mode 100644 index 0000000..803eb89 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Compiler.php @@ -0,0 +1,286 @@ + + */ +class Twig_Compiler implements Twig_CompilerInterface +{ + protected $lastLine; + protected $source; + protected $indentation; + protected $env; + protected $debugInfo = array(); + protected $sourceOffset; + protected $sourceLine; + protected $filename; + private $varNameSalt = 0; + + public function __construct(Twig_Environment $env) + { + $this->env = $env; + } + + /** + * @deprecated since 1.25 (to be removed in 2.0) + */ + public function getFilename() + { + @trigger_error(sprintf('The %s() method is deprecated since version 1.25 and will be removed in 2.0.', __FUNCTION__), E_USER_DEPRECATED); + + return $this->filename; + } + + /** + * Returns the environment instance related to this compiler. + * + * @return Twig_Environment + */ + public function getEnvironment() + { + return $this->env; + } + + /** + * Gets the current PHP code after compilation. + * + * @return string The PHP code + */ + public function getSource() + { + return $this->source; + } + + /** + * Compiles a node. + * + * @param Twig_NodeInterface $node The node to compile + * @param int $indentation The current indentation + * + * @return $this + */ + public function compile(Twig_NodeInterface $node, $indentation = 0) + { + $this->lastLine = null; + $this->source = ''; + $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 Twig_Node_Module) { + // to be removed in 2.0 + $this->filename = $node->getTemplateName(); + } + + $node->compile($this); + + return $this; + } + + public function subcompile(Twig_NodeInterface $node, $raw = true) + { + if (false === $raw) { + $this->source .= str_repeat(' ', $this->indentation * 4); + } + + $node->compile($this); + + return $this; + } + + /** + * Adds a raw string to the compiled code. + * + * @param string $string The string + * + * @return $this + */ + public function raw($string) + { + $this->source .= $string; + + return $this; + } + + /** + * Writes a string to the compiled code by adding indentation. + * + * @return $this + */ + public function write() + { + $strings = func_get_args(); + foreach ($strings as $string) { + $this->source .= str_repeat(' ', $this->indentation * 4).$string; + } + + return $this; + } + + /** + * Appends an indentation to the current PHP code after compilation. + * + * @return $this + * + * @deprecated since 1.27 (to be removed in 2.0). + */ + public function addIndentation() + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use write(\'\') instead.', E_USER_DEPRECATED); + + $this->source .= str_repeat(' ', $this->indentation * 4); + + return $this; + } + + /** + * Adds a quoted string to the compiled code. + * + * @param string $value The string + * + * @return $this + */ + public function string($value) + { + $this->source .= sprintf('"%s"', addcslashes($value, "\0\t\"\$\\")); + + return $this; + } + + /** + * Returns a PHP representation of a given value. + * + * @param mixed $value The value to convert + * + * @return $this + */ + public function repr($value) + { + if (is_int($value) || is_float($value)) { + if (false !== $locale = setlocale(LC_NUMERIC, '0')) { + setlocale(LC_NUMERIC, 'C'); + } + + $this->raw($value); + + if (false !== $locale) { + setlocale(LC_NUMERIC, $locale); + } + } elseif (null === $value) { + $this->raw('null'); + } elseif (is_bool($value)) { + $this->raw($value ? 'true' : 'false'); + } elseif (is_array($value)) { + $this->raw('array('); + $first = true; + foreach ($value as $key => $v) { + if (!$first) { + $this->raw(', '); + } + $first = false; + $this->repr($key); + $this->raw(' => '); + $this->repr($v); + } + $this->raw(')'); + } else { + $this->string($value); + } + + return $this; + } + + /** + * Adds debugging information. + * + * @return $this + */ + public function addDebugInfo(Twig_NodeInterface $node) + { + if ($node->getTemplateLine() != $this->lastLine) { + $this->write(sprintf("// line %d\n", $node->getTemplateLine())); + + // when mbstring.func_overload is set to 2 + // mb_substr_count() replaces substr_count() + // but they have different signatures! + if (((int) ini_get('mbstring.func_overload')) & 2) { + @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); + + // this is much slower than the "right" version + $this->sourceLine += mb_substr_count(mb_substr($this->source, $this->sourceOffset), "\n"); + } else { + $this->sourceLine += substr_count($this->source, "\n", $this->sourceOffset); + } + $this->sourceOffset = strlen($this->source); + $this->debugInfo[$this->sourceLine] = $node->getTemplateLine(); + + $this->lastLine = $node->getTemplateLine(); + } + + return $this; + } + + public function getDebugInfo() + { + ksort($this->debugInfo); + + return $this->debugInfo; + } + + /** + * Indents the generated code. + * + * @param int $step The number of indentation to add + * + * @return $this + */ + public function indent($step = 1) + { + $this->indentation += $step; + + return $this; + } + + /** + * Outdents the generated code. + * + * @param int $step The number of indentation to remove + * + * @return $this + * + * @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.'); + } + + $this->indentation -= $step; + + return $this; + } + + public function getVarName() + { + return sprintf('__internal_%s', hash('sha256', __METHOD__.$this->varNameSalt++)); + } +} + +class_alias('Twig_Compiler', 'Twig\Compiler', false); +class_exists('Twig_Node'); diff --git a/vendor/twig/twig/lib/Twig/CompilerInterface.php b/vendor/twig/twig/lib/Twig/CompilerInterface.php new file mode 100644 index 0000000..42872c9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/CompilerInterface.php @@ -0,0 +1,34 @@ + + * + * @deprecated since 1.12 (to be removed in 3.0) + */ +interface Twig_CompilerInterface +{ + /** + * Compiles a node. + * + * @return $this + */ + public function compile(Twig_NodeInterface $node); + + /** + * Gets the current PHP code after compilation. + * + * @return string The PHP code + */ + public function getSource(); +} diff --git a/vendor/twig/twig/lib/Twig/ContainerRuntimeLoader.php b/vendor/twig/twig/lib/Twig/ContainerRuntimeLoader.php new file mode 100644 index 0000000..814ab58 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/ContainerRuntimeLoader.php @@ -0,0 +1,39 @@ + + * @author Robin Chalas + */ +class Twig_ContainerRuntimeLoader implements Twig_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_ContainerRuntimeLoader', 'Twig\RuntimeLoader\ContainerRuntimeLoader', false); diff --git a/vendor/twig/twig/lib/Twig/Environment.php b/vendor/twig/twig/lib/Twig/Environment.php new file mode 100644 index 0000000..7945bfa --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Environment.php @@ -0,0 +1,1617 @@ + + */ +class Twig_Environment +{ + const VERSION = '1.36.0'; + const VERSION_ID = 13600; + const MAJOR_VERSION = 1; + const MINOR_VERSION = 36; + const RELEASE_VERSION = 0; + const EXTRA_VERSION = ''; + + protected $charset; + protected $loader; + protected $debug; + protected $autoReload; + protected $cache; + protected $lexer; + protected $parser; + protected $compiler; + protected $baseTemplateClass; + protected $extensions; + protected $parsers; + protected $visitors; + protected $filters; + protected $tests; + protected $functions; + protected $globals; + protected $runtimeInitialized = false; + protected $extensionInitialized = false; + protected $loadedTemplates; + protected $strictVariables; + protected $unaryOperators; + protected $binaryOperators; + protected $templateClassPrefix = '__TwigTemplate_'; + protected $functionCallbacks = array(); + protected $filterCallbacks = array(); + protected $staging; + + private $originalCache; + private $bcWriteCacheFile = false; + private $bcGetCacheFilename = false; + private $lastModifiedExtension = 0; + private $extensionsByClass = array(); + private $runtimeLoaders = array(); + private $runtimes = array(); + private $optionsHash; + private $loading = array(); + + /** + * Constructor. + * + * Available options: + * + * * debug: When set to true, it automatically set "auto_reload" to true as + * well (default to false). + * + * * 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). + * + * * cache: An absolute path where to store the compiled templates, + * a Twig_Cache_Interface implementation, + * or false to disable compilation cache (default). + * + * * auto_reload: Whether to reload the template if the original source changed. + * If you don't provide the auto_reload option, it will be + * determined automatically based on the debug value. + * + * * strict_variables: Whether to ignore invalid variables in templates + * (default to false). + * + * * autoescape: Whether to enable auto-escaping (default to html): + * * false: disable auto-escaping + * * true: equivalent to html + * * html, js: set the autoescaping to one of the supported strategies + * * name: set the autoescaping strategy based on the template name extension + * * PHP callback: a PHP callback that returns an escaping strategy based on the template "name" + * + * * 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(Twig_LoaderInterface $loader = null, $options = array()) + { + if (null !== $loader) { + $this->setLoader($loader); + } else { + @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(array( + 'debug' => false, + 'charset' => 'UTF-8', + 'base_template_class' => 'Twig_Template', + 'strict_variables' => false, + 'autoescape' => 'html', + 'cache' => false, + 'auto_reload' => null, + 'optimizations' => -1, + ), $options); + + $this->debug = (bool) $options['debug']; + $this->charset = strtoupper($options['charset']); + $this->baseTemplateClass = $options['base_template_class']; + $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload']; + $this->strictVariables = (bool) $options['strict_variables']; + $this->setCache($options['cache']); + + $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); + + $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); + + $this->bcGetCacheFilename = true; + } + } + } + + /** + * Gets the base template class for compiled templates. + * + * @return string The base template class name + */ + public function getBaseTemplateClass() + { + return $this->baseTemplateClass; + } + + /** + * Sets the base template class for compiled templates. + * + * @param string $class The base template class name + */ + public function setBaseTemplateClass($class) + { + $this->baseTemplateClass = $class; + $this->updateOptionsHash(); + } + + /** + * Enables debugging mode. + */ + public function enableDebug() + { + $this->debug = true; + $this->updateOptionsHash(); + } + + /** + * Disables debugging mode. + */ + public function disableDebug() + { + $this->debug = false; + $this->updateOptionsHash(); + } + + /** + * Checks if debug mode is enabled. + * + * @return bool true if debug mode is enabled, false otherwise + */ + public function isDebug() + { + return $this->debug; + } + + /** + * Enables the auto_reload option. + */ + public function enableAutoReload() + { + $this->autoReload = true; + } + + /** + * Disables the auto_reload option. + */ + public function disableAutoReload() + { + $this->autoReload = false; + } + + /** + * Checks if the auto_reload option is enabled. + * + * @return bool true if auto_reload is enabled, false otherwise + */ + public function isAutoReload() + { + return $this->autoReload; + } + + /** + * Enables the strict_variables option. + */ + public function enableStrictVariables() + { + $this->strictVariables = true; + $this->updateOptionsHash(); + } + + /** + * Disables the strict_variables option. + */ + public function disableStrictVariables() + { + $this->strictVariables = false; + $this->updateOptionsHash(); + } + + /** + * Checks if the strict_variables option is enabled. + * + * @return bool true if strict_variables is enabled, false otherwise + */ + public function isStrictVariables() + { + return $this->strictVariables; + } + + /** + * Gets the current cache implementation. + * + * @param bool $original Whether to return the original cache option or the real cache instance + * + * @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) + { + return $original ? $this->originalCache : $this->cache; + } + + /** + * Sets the current cache implementation. + * + * @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)) { + $this->originalCache = $cache; + $this->cache = new Twig_Cache_Filesystem($cache); + } elseif (false === $cache) { + $this->originalCache = $cache; + $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 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_CacheInterface implementation.')); + } + } + + /** + * Gets the cache filename for a given template. + * + * @param string $name The template name + * + * @return string|false The cache file name or false when caching is disabled + * + * @deprecated since 1.22 (to be removed in 2.0) + */ + public function getCacheFilename($name) + { + @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); + + $key = $this->cache->generateKey($name, $this->getTemplateClass($name)); + + return !$key ? false : $key; + } + + /** + * Gets the template class associated with the given string. + * + * The generated template class is based on the following parameters: + * + * * The cache key for the given template; + * * The currently enabled extensions; + * * Whether the Twig C extension is available or not; + * * PHP version; + * * Twig version; + * * Options with what environment was created. + * + * @param string $name The name for which to calculate the template class name + * @param int|null $index The index if it is an embedded template + * + * @return string The template class name + */ + public function getTemplateClass($name, $index = null) + { + $key = $this->getLoader()->getCacheKey($name).$this->optionsHash; + + return $this->templateClassPrefix.hash('sha256', $key).(null === $index ? '' : '_'.$index); + } + + /** + * Gets the template class prefix. + * + * @return string The template class prefix + * + * @deprecated since 1.22 (to be removed in 2.0) + */ + public function getTemplateClassPrefix() + { + @trigger_error(sprintf('The %s method is deprecated since version 1.22 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); + + return $this->templateClassPrefix; + } + + /** + * Renders a 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 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 = array()) + { + return $this->loadTemplate($name)->render($context); + } + + /** + * Displays a template. + * + * @param string $name The template name + * @param array $context An array of parameters to pass to the template + * + * @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 = array()) + { + $this->loadTemplate($name)->display($context); + } + + /** + * Loads a template. + * + * @param string|Twig_TemplateWrapper|Twig_Template $name The template name + * + * @throws Twig_Error_Loader When the template cannot be found + * @throws Twig_Error_Runtime When a previously generated cache is corrupted + * @throws Twig_Error_Syntax When an error occurred during compilation + * + * @return Twig_TemplateWrapper + */ + public function load($name) + { + if ($name instanceof Twig_TemplateWrapper) { + return $name; + } + + if ($name instanceof Twig_Template) { + return new Twig_TemplateWrapper($this, $name); + } + + return new Twig_TemplateWrapper($this, $this->loadTemplate($name)); + } + + /** + * Loads a template internal representation. + * + * This method is for internal use only and should never be called + * directly. + * + * @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 + * + * @throws Twig_Error_Loader When the template cannot be found + * @throws Twig_Error_Runtime When a previously generated cache is corrupted + * @throws Twig_Error_Syntax When an error occurred during compilation + * + * @internal + */ + public function loadTemplate($name, $index = null) + { + $cls = $mainCls = $this->getTemplateClass($name); + if (null !== $index) { + $cls .= '_'.$index; + } + + if (isset($this->loadedTemplates[$cls])) { + return $this->loadedTemplates[$cls]; + } + + if (!class_exists($cls, false)) { + if ($this->bcGetCacheFilename) { + $key = $this->getCacheFilename($name); + } else { + $key = $this->cache->generateKey($name, $mainCls); + } + + if (!$this->isAutoReload() || $this->isTemplateFresh($name, $this->cache->getTimestamp($key))) { + $this->cache->load($key); + } + + if (!class_exists($cls, false)) { + $loader = $this->getLoader(); + if (!$loader instanceof Twig_SourceContextLoaderInterface) { + $source = new Twig_Source($loader->getSource($name), $name); + } else { + $source = $loader->getSourceContext($name); + } + + $content = $this->compileSource($source); + + if ($this->bcWriteCacheFile) { + $this->writeCacheFile($key, $content); + } else { + $this->cache->write($key, $content); + $this->cache->load($key); + } + + if (!class_exists($mainCls, 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 + * the cache. + */ + eval('?>'.$content); + } + } + + if (!class_exists($cls, false)) { + throw new Twig_Error_Runtime(sprintf('Failed to load Twig template "%s", index "%s": cache is corrupted.', $name, $index), -1, $source); + } + } + + if (!$this->runtimeInitialized) { + $this->initRuntime(); + } + + if (isset($this->loading[$cls])) { + throw new Twig_Error_Runtime(sprintf('Circular reference detected for Twig template "%s", path: %s.', $name, implode(' -> ', array_merge($this->loading, array($name))))); + } + + $this->loading[$cls] = $name; + + try { + $this->loadedTemplates[$cls] = new $cls($this); + unset($this->loading[$cls]); + } catch (\Exception $e) { + unset($this->loading[$cls]); + + throw $e; + } + + return $this->loadedTemplates[$cls]; + } + + /** + * Creates a template from source. + * + * This method should not be used as a generic way to load templates. + * + * @param string $template The template name + * + * @return Twig_Template A template instance representing the given template name + * + * @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 = sprintf('__string_template__%s', hash('sha256', $template, false)); + + $loader = new Twig_Loader_Chain(array( + new Twig_Loader_Array(array($name => $template)), + $current = $this->getLoader(), + )); + + $this->setLoader($loader); + try { + $template = $this->loadTemplate($name); + } catch (Exception $e) { + $this->setLoader($current); + + throw $e; + } catch (Throwable $e) { + $this->setLoader($current); + + throw $e; + } + $this->setLoader($current); + + return $template; + } + + /** + * Returns true if the template is still fresh. + * + * Besides checking the loader for freshness information, + * this method also checks if the enabled extensions have + * not changed. + * + * @param string $name The template name + * @param int $time The last modification time of the cached template + * + * @return bool true if the template is fresh, false otherwise + */ + public function isTemplateFresh($name, $time) + { + if (0 === $this->lastModifiedExtension) { + foreach ($this->extensions as $extension) { + $r = new ReflectionObject($extension); + if (file_exists($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModifiedExtension) { + $this->lastModifiedExtension = $extensionTime; + } + } + } + + return $this->lastModifiedExtension <= $time && $this->getLoader()->isFresh($name, $time); + } + + /** + * Tries to load a template consecutively from an array. + * + * Similar to loadTemplate() but it also accepts instances of Twig_Template and + * Twig_TemplateWrapper, and an array of templates where each is tried to be loaded. + * + * @param string|Twig_Template|Twig_TemplateWrapper|array $names A template or an array of templates to try consecutively + * + * @return Twig_Template|Twig_TemplateWrapper + * + * @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 = array($names); + } + + foreach ($names as $name) { + if ($name instanceof Twig_Template) { + return $name; + } + + if ($name instanceof Twig_TemplateWrapper) { + return $name; + } + + try { + return $this->loadTemplate($name); + } catch (Twig_Error_Loader $e) { + } + } + + if (1 === count($names)) { + throw $e; + } + + throw new Twig_Error_Loader(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names))); + } + + /** + * Clears the internal template cache. + * + * @deprecated since 1.18.3 (to be removed in 2.0) + */ + 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 = array(); + } + + /** + * Clears the template cache files on the filesystem. + * + * @deprecated since 1.22 (to be removed in 2.0) + */ + 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 ($file->isFile()) { + @unlink($file->getPathname()); + } + } + } + } + + /** + * Gets the Lexer instance. + * + * @return Twig_LexerInterface + * + * @deprecated since 1.25 (to be removed in 2.0) + */ + 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 Twig_Lexer($this); + } + + return $this->lexer; + } + + public function setLexer(Twig_LexerInterface $lexer) + { + $this->lexer = $lexer; + } + + /** + * Tokenizes a source code. + * + * @param string|Twig_Source $source The template source code + * @param string $name The template name (deprecated) + * + * @return Twig_TokenStream + * + * @throws Twig_Error_Syntax When the code is syntactically wrong + */ + public function tokenize($source, $name = null) + { + 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 Twig_Lexer($this); + } + + return $this->lexer->tokenize($source); + } + + /** + * Gets the Parser instance. + * + * @return Twig_ParserInterface + * + * @deprecated since 1.25 (to be removed in 2.0) + */ + 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 Twig_Parser($this); + } + + return $this->parser; + } + + public function setParser(Twig_ParserInterface $parser) + { + $this->parser = $parser; + } + + /** + * Converts a token stream to a node tree. + * + * @return Twig_Node_Module + * + * @throws Twig_Error_Syntax When the token stream is syntactically or semantically wrong + */ + public function parse(Twig_TokenStream $stream) + { + if (null === $this->parser) { + $this->parser = new Twig_Parser($this); + } + + return $this->parser->parse($stream); + } + + /** + * Gets the Compiler instance. + * + * @return Twig_CompilerInterface + * + * @deprecated since 1.25 (to be removed in 2.0) + */ + 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 Twig_Compiler($this); + } + + return $this->compiler; + } + + public function setCompiler(Twig_CompilerInterface $compiler) + { + $this->compiler = $compiler; + } + + /** + * Compiles a node and returns the PHP code. + * + * @return string The compiled PHP source code + */ + public function compile(Twig_NodeInterface $node) + { + if (null === $this->compiler) { + $this->compiler = new Twig_Compiler($this); + } + + return $this->compiler->compile($node)->getSource(); + } + + /** + * Compiles a template source code. + * + * @param string|Twig_Source $source The template source code + * @param string $name The template name (deprecated) + * + * @return string The compiled PHP source code + * + * @throws Twig_Error_Syntax When there was an error during tokenizing, parsing or compiling + */ + public function compileSource($source, $name = null) + { + 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 (Twig_Error $e) { + $e->setSourceContext($source); + throw $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(Twig_LoaderInterface $loader) + { + if (!$loader instanceof Twig_SourceContextLoaderInterface && 0 !== strpos(get_class($loader), 'Mock_')) { + @trigger_error(sprintf('Twig loader "%s" should implement Twig_SourceContextLoaderInterface since version 1.27.', get_class($loader)), E_USER_DEPRECATED); + } + + $this->loader = $loader; + } + + /** + * Gets the Loader instance. + * + * @return Twig_LoaderInterface + */ + public function getLoader() + { + if (null === $this->loader) { + throw new LogicException('You must set a loader first.'); + } + + return $this->loader; + } + + /** + * Sets the default template charset. + * + * @param string $charset The default charset + */ + public function setCharset($charset) + { + $this->charset = strtoupper($charset); + } + + /** + * Gets the default template charset. + * + * @return string The default charset + */ + public function getCharset() + { + return $this->charset; + } + + /** + * Initializes the runtime environment. + * + * @deprecated since 1.23 (to be removed in 2.0) + */ + public function initRuntime() + { + $this->runtimeInitialized = true; + + foreach ($this->getExtensions() as $name => $extension) { + if (!$extension instanceof Twig_Extension_InitRuntimeInterface) { + $m = new ReflectionMethod($extension, 'initRuntime'); + + 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); + } + } + + $extension->initRuntime($this); + } + } + + /** + * Returns true if the given extension is registered. + * + * @param string $class The extension class name + * + * @return bool Whether the extension is registered or not + */ + 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])) { + @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]); + } + + /** + * Adds a runtime loader. + */ + public function addRuntimeLoader(Twig_RuntimeLoaderInterface $loader) + { + $this->runtimeLoaders[] = $loader; + } + + /** + * Gets an extension by class name. + * + * @param string $class The extension class name + * + * @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])) { + @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 $this->extensions[$class]; + } + + if (!isset($this->extensionsByClass[$class])) { + throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class)); + } + + return $this->extensionsByClass[$class]; + } + + /** + * Returns the runtime implementation of a Twig element (filter/function/test). + * + * @param string $class A runtime class name + * + * @return object The runtime implementation + * + * @throws Twig_Error_Runtime When the template cannot be found + */ + public function getRuntime($class) + { + if (isset($this->runtimes[$class])) { + return $this->runtimes[$class]; + } + + foreach ($this->runtimeLoaders as $loader) { + if (null !== $runtime = $loader->load($class)) { + return $this->runtimes[$class] = $runtime; + } + } + + throw new Twig_Error_Runtime(sprintf('Unable to load the "%s" runtime.', $class)); + } + + 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())); + } + + $class = get_class($extension); + if ($class !== $extension->getName()) { + if (isset($this->extensions[$extension->getName()])) { + unset($this->extensions[$extension->getName()], $this->extensionsByClass[$class]); + @trigger_error(sprintf('The possibility to register the same extension twice ("%s") is deprecated since version 1.23 and will be removed in Twig 2.0. Use proper PHP inheritance instead.', $extension->getName()), E_USER_DEPRECATED); + } + } + + $this->lastModifiedExtension = 0; + $this->extensionsByClass[$class] = $extension; + $this->extensions[$extension->getName()] = $extension; + $this->updateOptionsHash(); + } + + /** + * Removes an extension by name. + * + * This method is deprecated and you should not use it. + * + * @param string $name The extension name + * + * @deprecated since 1.12 (to be removed in 2.0) + */ + 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)); + } + + $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])) { + @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); + } + + unset($this->extensions[$class]); + } + + unset($this->extensions[$class]); + $this->updateOptionsHash(); + } + + /** + * Registers an array of extensions. + * + * @param array $extensions An array of extensions + */ + public function setExtensions(array $extensions) + { + foreach ($extensions as $extension) { + $this->addExtension($extension); + } + } + + /** + * Returns all registered extensions. + * + * @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(Twig_TokenParserInterface $parser) + { + if ($this->extensionInitialized) { + throw new LogicException('Unable to add a token parser as extensions have already been initialized.'); + } + + $this->staging->addTokenParser($parser); + } + + /** + * Gets the registered Token Parsers. + * + * @return Twig_TokenParserBrokerInterface + * + * @internal + */ + public function getTokenParsers() + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + return $this->parsers; + } + + /** + * Gets registered tags. + * + * Be warned that this method cannot return tags defined by Twig_TokenParserBrokerInterface classes. + * + * @return Twig_TokenParserInterface[] + * + * @internal + */ + public function getTags() + { + $tags = array(); + foreach ($this->getTokenParsers()->getParsers() as $parser) { + if ($parser instanceof Twig_TokenParserInterface) { + $tags[$parser->getTag()] = $parser; + } + } + + return $tags; + } + + public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) + { + if ($this->extensionInitialized) { + throw new LogicException('Unable to add a node visitor as extensions have already been initialized.'); + } + + $this->staging->addNodeVisitor($visitor); + } + + /** + * Gets the registered Node Visitors. + * + * @return Twig_NodeVisitorInterface[] + * + * @internal + */ + public function getNodeVisitors() + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + return $this->visitors; + } + + /** + * Registers a 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 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 Twig_SimpleFilter) { + $filter = $name; + $name = $filter->getName(); + } else { + @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleFilter" instead when defining filter "%s".', __METHOD__, $name), E_USER_DEPRECATED); + } + + if ($this->extensionInitialized) { + throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $name)); + } + + $this->staging->addFilter($name, $filter); + } + + /** + * Get a filter by name. + * + * Subclasses may override this method and load filters differently; + * so no list of filters is available. + * + * @param string $name The filter name + * + * @return Twig_Filter|false A Twig_Filter instance or false if the filter does not exist + * + * @internal + */ + public function getFilter($name) + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + if (isset($this->filters[$name])) { + return $this->filters[$name]; + } + + foreach ($this->filters as $pattern => $filter) { + $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); + + if ($count) { + if (preg_match('#^'.$pattern.'$#', $name, $matches)) { + array_shift($matches); + $filter->setArguments($matches); + + return $filter; + } + } + } + + foreach ($this->filterCallbacks as $callback) { + if (false !== $filter = call_user_func($callback, $name)) { + return $filter; + } + } + + return false; + } + + public function registerUndefinedFilterCallback($callable) + { + $this->filterCallbacks[] = $callable; + } + + /** + * Gets the registered Filters. + * + * Be warned that this method cannot return filters defined with registerUndefinedFilterCallback. + * + * @return Twig_FilterInterface[] + * + * @see registerUndefinedFilterCallback + * + * @internal + */ + public function getFilters() + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + return $this->filters; + } + + /** + * Registers a Test. + * + * @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 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 Twig_SimpleTest) { + $test = $name; + $name = $test->getName(); + } else { + @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleTest" instead when defining test "%s".', __METHOD__, $name), E_USER_DEPRECATED); + } + + if ($this->extensionInitialized) { + throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $name)); + } + + $this->staging->addTest($name, $test); + } + + /** + * Gets the registered Tests. + * + * @return Twig_TestInterface[] + * + * @internal + */ + public function getTests() + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + return $this->tests; + } + + /** + * Gets a test by name. + * + * @param string $name The test name + * + * @return Twig_Test|false A Twig_Test instance or false if the test does not exist + * + * @internal + */ + public function getTest($name) + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + if (isset($this->tests[$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|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 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 Twig_SimpleFunction) { + $function = $name; + $name = $function->getName(); + } else { + @trigger_error(sprintf('Passing a name as a first argument to the %s method is deprecated since version 1.21. Pass an instance of "Twig_SimpleFunction" instead when defining function "%s".', __METHOD__, $name), E_USER_DEPRECATED); + } + + if ($this->extensionInitialized) { + throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $name)); + } + + $this->staging->addFunction($name, $function); + } + + /** + * Get a function by name. + * + * Subclasses may override this method and load functions differently; + * so no list of functions is available. + * + * @param string $name function name + * + * @return Twig_Function|false A Twig_Function instance or false if the function does not exist + * + * @internal + */ + public function getFunction($name) + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + if (isset($this->functions[$name])) { + return $this->functions[$name]; + } + + foreach ($this->functions as $pattern => $function) { + $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); + + if ($count) { + if (preg_match('#^'.$pattern.'$#', $name, $matches)) { + array_shift($matches); + $function->setArguments($matches); + + return $function; + } + } + } + + foreach ($this->functionCallbacks as $callback) { + if (false !== $function = call_user_func($callback, $name)) { + return $function; + } + } + + return false; + } + + public function registerUndefinedFunctionCallback($callable) + { + $this->functionCallbacks[] = $callable; + } + + /** + * Gets registered functions. + * + * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback. + * + * @return Twig_FunctionInterface[] + * + * @see registerUndefinedFunctionCallback + * + * @internal + */ + public function getFunctions() + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + return $this->functions; + } + + /** + * Registers a Global. + * + * New globals can be added before compiling or rendering a template; + * but after, you can only update existing globals. + * + * @param string $name The global name + * @param mixed $value The global value + */ + public function addGlobal($name, $value) + { + if ($this->extensionInitialized || $this->runtimeInitialized) { + if (null === $this->globals) { + $this->globals = $this->initGlobals(); + } + + 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)); + } + } + + if ($this->extensionInitialized || $this->runtimeInitialized) { + // update the value + $this->globals[$name] = $value; + } else { + $this->staging->addGlobal($name, $value); + } + } + + /** + * Gets the registered Globals. + * + * @return array An array of globals + * + * @internal + */ + public function getGlobals() + { + if (!$this->runtimeInitialized && !$this->extensionInitialized) { + return $this->initGlobals(); + } + + if (null === $this->globals) { + $this->globals = $this->initGlobals(); + } + + return $this->globals; + } + + /** + * Merges a context with the defined globals. + * + * @param array $context An array representing the context + * + * @return array The context merged with the globals + */ + 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)) { + $context[$key] = $value; + } + } + + return $context; + } + + /** + * Gets the registered unary Operators. + * + * @return array An array of unary operators + * + * @internal + */ + public function getUnaryOperators() + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + return $this->unaryOperators; + } + + /** + * Gets the registered binary Operators. + * + * @return array An array of binary operators + * + * @internal + */ + public function getBinaryOperators() + { + if (!$this->extensionInitialized) { + $this->initExtensions(); + } + + return $this->binaryOperators; + } + + /** + * @deprecated since 1.23 (to be removed in 2.0) + */ + 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 Twig_Error_Syntax::computeAlternatives($name, $items); + } + + /** + * @internal + */ + protected function initGlobals() + { + $globals = array(); + foreach ($this->extensions as $name => $extension) { + if (!$extension instanceof Twig_Extension_GlobalsInterface) { + $m = new ReflectionMethod($extension, 'getGlobals'); + + 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))); + } + + $globals[] = $extGlob; + } + + $globals[] = $this->staging->getGlobals(); + + return call_user_func_array('array_merge', $globals); + } + + /** + * @internal + */ + protected function initExtensions() + { + if ($this->extensionInitialized) { + return; + } + + $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(Twig_ExtensionInterface $extension) + { + // filters + foreach ($extension->getFilters() as $name => $filter) { + 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); + } + + $this->filters[$name] = $filter; + } + + // functions + foreach ($extension->getFunctions() as $name => $function) { + 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); + } + + $this->functions[$name] = $function; + } + + // tests + foreach ($extension->getTests() as $name => $test) { + 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); + } + + $this->tests[$name] = $test; + } + + // token parsers + foreach ($extension->getTokenParsers() as $parser) { + 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); + + $this->parsers->addTokenParserBroker($parser); + } else { + throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances.'); + } + } + + // node visitors + foreach ($extension->getNodeVisitors() as $visitor) { + $this->visitors[] = $visitor; + } + + // 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 (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]); + $this->binaryOperators = array_merge($this->binaryOperators, $operators[1]); + } + } + + /** + * @deprecated since 1.22 (to be removed in 2.0) + */ + protected function writeCacheFile($file, $content) + { + $this->cache->write($file, $content); + } + + private function updateOptionsHash() + { + $hashParts = array_merge( + array_keys($this->extensions), + 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', false); diff --git a/vendor/twig/twig/lib/Twig/Error.php b/vendor/twig/twig/lib/Twig/Error.php new file mode 100644 index 0000000..787e0d0 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Error.php @@ -0,0 +1,363 @@ + + */ +class Twig_Error extends Exception +{ + protected $lineno; + // to be renamed to name in 2.0 + protected $filename; + protected $rawMessage; + protected $previous; + + private $sourcePath; + private $sourceCode; + + /** + * Constructor. + * + * Set both the line number and the name to false to + * disable automatic guessing of the original template name + * and line number. + * + * Set the line number to -1 to enable its automatic guessing. + * Set the name to null to enable its automatic guessing. + * + * By default, automatic guessing is enabled. + * + * @param string $message The error message + * @param int $lineno The template line where the error occurred + * @param Twig_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 Twig_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(); + } + if (PHP_VERSION_ID < 50300) { + $this->previous = $previous; + parent::__construct(''); + } else { + parent::__construct('', 0, $previous); + } + + $this->lineno = $lineno; + $this->filename = $name; + + if (-1 === $lineno || null === $name || null === $this->sourcePath) { + $this->guessTemplateInfo(); + } + + $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 Twig_Source|null + */ + public function getSourceContext() + { + return $this->filename ? new Twig_Source($this->sourceCode, $this->filename, $this->sourcePath) : null; + } + + /** + * Sets the source context of the Twig template where the error occurred. + */ + public function setSourceContext(Twig_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(); + } + + /** + * For PHP < 5.3.0, provides access to the getPrevious() method. + * + * @param string $method The method name + * @param array $arguments The parameters to be passed to the method + * + * @return Exception The previous exception or null + * + * @throws BadMethodCallException + */ + public function __call($method, $arguments) + { + if ('getprevious' == strtolower($method)) { + return $this->previous; + } + + throw new BadMethodCallException(sprintf('Method "Twig_Error::%s()" does not exist.', $method)); + } + + 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; + + if (PHP_VERSION_ID >= 50306) { + $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT); + } else { + $backtrace = debug_backtrace(); + } + + foreach ($backtrace as $trace) { + if (isset($trace['object']) && $trace['object'] instanceof Twig_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 = array($e = $this); + while (($e instanceof self || method_exists($e, 'getPrevious')) && $e = $e->getPrevious()) { + $exceptions[] = $e; + } + + while ($e = array_pop($exceptions)) { + $traces = $e->getTrace(); + array_unshift($traces, array('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', 'Twig\Error\Error', false); +class_exists('Twig_Source'); diff --git a/vendor/twig/twig/lib/Twig/Error/Loader.php b/vendor/twig/twig/lib/Twig/Error/Loader.php new file mode 100644 index 0000000..df566dd --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Error/Loader.php @@ -0,0 +1,40 @@ + + */ +class Twig_Error_Loader extends Twig_Error +{ + public function __construct($message, $lineno = -1, $source = null, Exception $previous = null) + { + if (PHP_VERSION_ID < 50300) { + $this->previous = $previous; + Exception::__construct(''); + } else { + Exception::__construct('', 0, $previous); + } + $this->appendMessage($message); + $this->setTemplateLine(false); + } +} + +class_alias('Twig_Error_Loader', 'Twig\Error\LoaderError', false); diff --git a/vendor/twig/twig/lib/Twig/Error/Runtime.php b/vendor/twig/twig/lib/Twig/Error/Runtime.php new file mode 100644 index 0000000..3b24ad3 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Error/Runtime.php @@ -0,0 +1,22 @@ + + */ +class Twig_Error_Runtime extends Twig_Error +{ +} + +class_alias('Twig_Error_Runtime', 'Twig\Error\RuntimeError', false); diff --git a/vendor/twig/twig/lib/Twig/Error/Syntax.php b/vendor/twig/twig/lib/Twig/Error/Syntax.php new file mode 100644 index 0000000..9d09f21 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Error/Syntax.php @@ -0,0 +1,55 @@ + + */ +class Twig_Error_Syntax extends Twig_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 = array(); + 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_Syntax', 'Twig\Error\SyntaxError', false); diff --git a/vendor/twig/twig/lib/Twig/ExistsLoaderInterface.php b/vendor/twig/twig/lib/Twig/ExistsLoaderInterface.php new file mode 100644 index 0000000..968cb21 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/ExistsLoaderInterface.php @@ -0,0 +1,31 @@ + + * + * @deprecated since 1.12 (to be removed in 3.0) + */ +interface Twig_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_ExistsLoaderInterface', 'Twig\Loader\ExistsLoaderInterface', false); diff --git a/vendor/twig/twig/lib/Twig/ExpressionParser.php b/vendor/twig/twig/lib/Twig/ExpressionParser.php new file mode 100644 index 0000000..fe4a9b4 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/ExpressionParser.php @@ -0,0 +1,744 @@ + + * + * @internal + */ +class Twig_ExpressionParser +{ + const OPERATOR_LEFT = 1; + const OPERATOR_RIGHT = 2; + + protected $parser; + protected $unaryOperators; + protected $binaryOperators; + + private $env; + + public function __construct(Twig_Parser $parser, $env = null) + { + $this->parser = $parser; + + if ($env instanceof Twig_Environment) { + $this->env = $env; + $this->unaryOperators = $env->getUnaryOperators(); + $this->binaryOperators = $env->getBinaryOperators(); + } else { + @trigger_error('Passing the operators as constructor arguments to '.__METHOD__.' is deprecated since version 1.27. Pass the environment instead.', E_USER_DEPRECATED); + + $this->env = $parser->getEnvironment(); + $this->unaryOperators = func_get_arg(1); + $this->binaryOperators = func_get_arg(2); + } + } + + public function parseExpression($precedence = 0) + { + $expr = $this->getPrimary(); + $token = $this->parser->getCurrentToken(); + while ($this->isBinary($token) && $this->binaryOperators[$token->getValue()]['precedence'] >= $precedence) { + $op = $this->binaryOperators[$token->getValue()]; + $this->parser->getStream()->next(); + + if ('is not' === $token->getValue()) { + $expr = $this->parseNotTestExpression($expr); + } elseif ('is' === $token->getValue()) { + $expr = $this->parseTestExpression($expr); + } elseif (isset($op['callable'])) { + $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']; + $expr = new $class($expr, $expr1, $token->getLine()); + } + + $token = $this->parser->getCurrentToken(); + } + + if (0 === $precedence) { + return $this->parseConditionalExpression($expr); + } + + return $expr; + } + + protected function getPrimary() + { + $token = $this->parser->getCurrentToken(); + + if ($this->isUnary($token)) { + $operator = $this->unaryOperators[$token->getValue()]; + $this->parser->getStream()->next(); + $expr = $this->parseExpression($operator['precedence']); + $class = $operator['class']; + + return $this->parsePostfixExpression(new $class($expr, $token->getLine())); + } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '(')) { + $this->parser->getStream()->next(); + $expr = $this->parseExpression(); + $this->parser->getStream()->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'An opened parenthesis is not properly closed'); + + return $this->parsePostfixExpression($expr); + } + + return $this->parsePrimaryExpression(); + } + + protected function parseConditionalExpression($expr) + { + 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(Twig_Token::PUNCTUATION_TYPE, ':')) { + $expr3 = $this->parseExpression(); + } else { + $expr3 = new Twig_Node_Expression_Constant('', $this->parser->getCurrentToken()->getLine()); + } + } else { + $expr2 = $expr; + $expr3 = $this->parseExpression(); + } + + $expr = new Twig_Node_Expression_Conditional($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine()); + } + + return $expr; + } + + protected function isUnary(Twig_Token $token) + { + return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->unaryOperators[$token->getValue()]); + } + + protected function isBinary(Twig_Token $token) + { + return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->binaryOperators[$token->getValue()]); + } + + public function parsePrimaryExpression() + { + $token = $this->parser->getCurrentToken(); + switch ($token->getType()) { + case Twig_Token::NAME_TYPE: + $this->parser->getStream()->next(); + switch ($token->getValue()) { + case 'true': + case 'TRUE': + $node = new Twig_Node_Expression_Constant(true, $token->getLine()); + break; + + case 'false': + case 'FALSE': + $node = new Twig_Node_Expression_Constant(false, $token->getLine()); + break; + + case 'none': + case 'NONE': + case 'null': + case 'NULL': + $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 Twig_Node_Expression_Name($token->getValue(), $token->getLine()); + } + } + break; + + case Twig_Token::NUMBER_TYPE: + $this->parser->getStream()->next(); + $node = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine()); + break; + + case Twig_Token::STRING_TYPE: + case Twig_Token::INTERPOLATION_START_TYPE: + $node = $this->parseStringExpression(); + break; + + 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 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_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(); + $expr = $this->parsePrimaryExpression(); + + $node = new $class($expr, $token->getLine()); + break; + } + + // no break + default: + if ($token->test(Twig_Token::PUNCTUATION_TYPE, '[')) { + $node = $this->parseArrayExpression(); + } elseif ($token->test(Twig_Token::PUNCTUATION_TYPE, '{')) { + $node = $this->parseHashExpression(); + } elseif ($token->test(Twig_Token::OPERATOR_TYPE, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) { + throw new Twig_Error_Syntax(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 Twig_Error_Syntax(sprintf('Unexpected token "%s" of value "%s".', Twig_Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); + } + } + + return $this->parsePostfixExpression($node); + } + + public function parseStringExpression() + { + $stream = $this->parser->getStream(); + + $nodes = array(); + // a string cannot be followed by another string in a single expression + $nextCanBeString = true; + while (true) { + if ($nextCanBeString && $token = $stream->nextIf(Twig_Token::STRING_TYPE)) { + $nodes[] = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine()); + $nextCanBeString = false; + } elseif ($stream->nextIf(Twig_Token::INTERPOLATION_START_TYPE)) { + $nodes[] = $this->parseExpression(); + $stream->expect(Twig_Token::INTERPOLATION_END_TYPE); + $nextCanBeString = true; + } else { + break; + } + } + + $expr = array_shift($nodes); + foreach ($nodes as $node) { + $expr = new Twig_Node_Expression_Binary_Concat($expr, $node, $node->getTemplateLine()); + } + + return $expr; + } + + public function parseArrayExpression() + { + $stream = $this->parser->getStream(); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, '[', 'An array element was expected'); + + $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine()); + $first = true; + while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { + if (!$first) { + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'An array element must be followed by a comma'); + + // trailing ,? + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ']')) { + break; + } + } + $first = false; + + $node->addElement($this->parseExpression()); + } + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']', 'An opened array is not properly closed'); + + return $node; + } + + public function parseHashExpression() + { + $stream = $this->parser->getStream(); + $stream->expect(Twig_Token::PUNCTUATION_TYPE, '{', 'A hash element was expected'); + + $node = new Twig_Node_Expression_Array(array(), $stream->getCurrent()->getLine()); + $first = true; + while (!$stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) { + if (!$first) { + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ',', 'A hash value must be followed by a comma'); + + // trailing ,? + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '}')) { + break; + } + } + $first = false; + + // a hash key can be: + // + // * a number -- 12 + // * 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(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 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(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)'); + $value = $this->parseExpression(); + + $node->addElement($value, $key); + } + $stream->expect(Twig_Token::PUNCTUATION_TYPE, '}', 'An opened hash is not properly closed'); + + return $node; + } + + public function parsePostfixExpression($node) + { + while (true) { + $token = $this->parser->getCurrentToken(); + if (Twig_Token::PUNCTUATION_TYPE == $token->getType()) { + if ('.' == $token->getValue() || '[' == $token->getValue()) { + $node = $this->parseSubscriptExpression($node); + } elseif ('|' == $token->getValue()) { + $node = $this->parseFilterExpression($node); + } else { + break; + } + } else { + break; + } + } + + return $node; + } + + public function getFunctionNode($name, $line) + { + switch ($name) { + case 'parent': + $this->parseArguments(); + 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 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 Twig_Node_Expression_Parent($this->parser->peekBlockStack(), $line); + case 'block': + $args = $this->parseArguments(); + 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 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 Twig_Error_Syntax('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext()); + } + + 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 Twig_Node_Expression_Array(array(), $line); + foreach ($this->parseArguments() as $n) { + $arguments->addElement($n); + } + + $node = new Twig_Node_Expression_MethodCall($alias['node'], $alias['name'], $arguments, $line); + $node->setAttribute('safe', true); + + return $node; + } + + $args = $this->parseArguments(true); + $class = $this->getFunctionNodeClass($name, $line); + + return new $class($name, $args, $line); + } + } + + public function parseSubscriptExpression($node) + { + $stream = $this->parser->getStream(); + $token = $stream->next(); + $lineno = $token->getLine(); + $arguments = new Twig_Node_Expression_Array(array(), $lineno); + $type = Twig_Template::ANY_CALL; + if ('.' == $token->getValue()) { + $token = $stream->next(); + if ( + Twig_Token::NAME_TYPE == $token->getType() + || + Twig_Token::NUMBER_TYPE == $token->getType() + || + (Twig_Token::OPERATOR_TYPE == $token->getType() && preg_match(Twig_Lexer::REGEX_NAME, $token->getValue())) + ) { + $arg = new Twig_Node_Expression_Constant($token->getValue(), $lineno); + + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) { + $type = Twig_Template::METHOD_CALL; + foreach ($this->parseArguments() as $n) { + $arguments->addElement($n); + } + } + } else { + throw new Twig_Error_Syntax('Expected name or number.', $lineno, $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 Twig_Error_Syntax(sprintf('"%s" cannot be called as macro as it is a reserved keyword.', $name), $token->getLine(), $stream->getSourceContext()); + } + + $node = new Twig_Node_Expression_MethodCall($node, 'get'.$name, $arguments, $lineno); + $node->setAttribute('safe', true); + + return $node; + } + } else { + $type = Twig_Template::ARRAY_CALL; + + // slice? + $slice = false; + if ($stream->test(Twig_Token::PUNCTUATION_TYPE, ':')) { + $slice = true; + $arg = new Twig_Node_Expression_Constant(0, $token->getLine()); + } else { + $arg = $this->parseExpression(); + } + + if ($stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ':')) { + $slice = true; + } + + if ($slice) { + 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 Twig_Node(array($arg, $length)); + $filter = new $class($node, new Twig_Node_Expression_Constant('slice', $token->getLine()), $arguments, $token->getLine()); + + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']'); + + return $filter; + } + + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ']'); + } + + return new Twig_Node_Expression_GetAttr($node, $arg, $arguments, $type, $lineno); + } + + public function parseFilterExpression($node) + { + $this->parser->getStream()->next(); + + return $this->parseFilterExpressionRaw($node); + } + + public function parseFilterExpressionRaw($node, $tag = null) + { + while (true) { + $token = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE); + + $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); + } + + $class = $this->getFilterNodeClass($name->getAttribute('value'), $token->getLine()); + + $node = new $class($node, $name, $arguments, $token->getLine(), $tag); + + if (!$this->parser->getStream()->test(Twig_Token::PUNCTUATION_TYPE, '|')) { + break; + } + + $this->parser->getStream()->next(); + } + + return $node; + } + + /** + * Parses arguments. + * + * @param bool $namedArguments Whether to allow named arguments or not + * @param bool $definition Whether we are parsing arguments for a function definition + * + * @return Twig_Node + * + * @throws Twig_Error_Syntax + */ + public function parseArguments($namedArguments = false, $definition = false) + { + $args = array(); + $stream = $this->parser->getStream(); + + $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(Twig_Token::PUNCTUATION_TYPE, ',', 'Arguments must be separated by a comma'); + } + + if ($definition) { + $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(); + } + + $name = null; + 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'); + + if ($definition) { + $value = $this->parsePrimaryExpression(); + + if (!$this->checkConstantExpression($value)) { + 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(); + } + } + + if ($definition) { + if (null === $name) { + $name = $value->getAttribute('name'); + $value = new Twig_Node_Expression_Constant(null, $this->parser->getCurrentToken()->getLine()); + } + $args[$name] = $value; + } else { + if (null === $name) { + $args[] = $value; + } else { + $args[$name] = $value; + } + } + } + $stream->expect(Twig_Token::PUNCTUATION_TYPE, ')', 'A list of arguments must be closed by a parenthesis'); + + return new Twig_Node($args); + } + + public function parseAssignmentExpression() + { + $stream = $this->parser->getStream(); + $targets = array(); + while (true) { + $token = $stream->expect(Twig_Token::NAME_TYPE, null, 'Only variables can be assigned to'); + $value = $token->getValue(); + 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 Twig_Node_Expression_AssignName($value, $token->getLine()); + + if (!$stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) { + break; + } + } + + return new Twig_Node($targets); + } + + public function parseMultitargetExpression() + { + $targets = array(); + while (true) { + $targets[] = $this->parseExpression(); + if (!$this->parser->getStream()->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) { + break; + } + } + + return new Twig_Node($targets); + } + + private function parseNotTestExpression(Twig_NodeInterface $node) + { + return new Twig_Node_Expression_Unary_Not($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine()); + } + + 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(Twig_Token::PUNCTUATION_TYPE, '(')) { + $arguments = $this->parser->getExpressionParser()->parseArguments(true); + } + + return new $class($node, $name, $arguments, $this->parser->getCurrentToken()->getLine()); + } + + private function getTest($line) + { + $stream = $this->parser->getStream(); + $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + + if ($test = $this->env->getTest($name)) { + return array($name, $test); + } + + 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 array($name, $test); + } + } + + $e = new Twig_Error_Syntax(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext()); + $e->addSuggestions($name, array_keys($this->env->getTests())); + + throw $e; + } + + private function getTestNodeClass($test) + { + 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())) { + $message .= sprintf(' since version %s', $test->getDeprecatedVersion()); + } + if ($test->getAlternative()) { + $message .= sprintf('. Use "%s" instead', $test->getAlternative()); + } + $src = $stream->getSourceContext(); + $message .= sprintf(' in %s at line %d.', $src->getPath() ? $src->getPath() : $src->getName(), $stream->getCurrent()->getLine()); + + @trigger_error($message, E_USER_DEPRECATED); + } + + if ($test instanceof Twig_SimpleTest) { + return $test->getNodeClass(); + } + + 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 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 Twig_SimpleFunction && $function->isDeprecated()) { + $message = sprintf('Twig Function "%s" is deprecated', $function->getName()); + if (!is_bool($function->getDeprecatedVersion())) { + $message .= sprintf(' since version %s', $function->getDeprecatedVersion()); + } + if ($function->getAlternative()) { + $message .= sprintf('. Use "%s" instead', $function->getAlternative()); + } + $src = $this->parser->getStream()->getSourceContext(); + $message .= sprintf(' in %s at line %d.', $src->getPath() ? $src->getPath() : $src->getName(), $line); + + @trigger_error($message, E_USER_DEPRECATED); + } + + if ($function instanceof Twig_SimpleFunction) { + return $function->getNodeClass(); + } + + 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 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 Twig_SimpleFilter && $filter->isDeprecated()) { + $message = sprintf('Twig Filter "%s" is deprecated', $filter->getName()); + if (!is_bool($filter->getDeprecatedVersion())) { + $message .= sprintf(' since version %s', $filter->getDeprecatedVersion()); + } + if ($filter->getAlternative()) { + $message .= sprintf('. Use "%s" instead', $filter->getAlternative()); + } + $src = $this->parser->getStream()->getSourceContext(); + $message .= sprintf(' in %s at line %d.', $src->getPath() ? $src->getPath() : $src->getName(), $line); + + @trigger_error($message, E_USER_DEPRECATED); + } + + if ($filter instanceof Twig_SimpleFilter) { + return $filter->getNodeClass(); + } + + 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) + { + 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; + } + + foreach ($node as $n) { + if (!$this->checkConstantExpression($n)) { + return false; + } + } + + return true; + } +} + +class_alias('Twig_ExpressionParser', 'Twig\ExpressionParser', false); diff --git a/vendor/twig/twig/lib/Twig/Extension.php b/vendor/twig/twig/lib/Twig/Extension.php new file mode 100644 index 0000000..3808449 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension.php @@ -0,0 +1,69 @@ +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 = array($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 array( + new Twig_TokenParser_For(), + new Twig_TokenParser_If(), + new Twig_TokenParser_Extends(), + new Twig_TokenParser_Include(), + new Twig_TokenParser_Block(), + new Twig_TokenParser_Use(), + new Twig_TokenParser_Filter(), + new Twig_TokenParser_Macro(), + new Twig_TokenParser_Import(), + new Twig_TokenParser_From(), + new Twig_TokenParser_Set(), + new Twig_TokenParser_Spaceless(), + new Twig_TokenParser_Flush(), + new Twig_TokenParser_Do(), + new Twig_TokenParser_Embed(), + new Twig_TokenParser_With(), + new Twig_TokenParser_Deprecated(), + ); + } + + public function getFilters() + { + $filters = array( + // formatting filters + new Twig_SimpleFilter('date', 'twig_date_format_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('date_modify', 'twig_date_modify_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('format', 'sprintf'), + new Twig_SimpleFilter('replace', 'twig_replace_filter'), + new Twig_SimpleFilter('number_format', 'twig_number_format_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('abs', 'abs'), + new Twig_SimpleFilter('round', 'twig_round'), + + // encoding + new Twig_SimpleFilter('url_encode', 'twig_urlencode_filter'), + new Twig_SimpleFilter('json_encode', 'twig_jsonencode_filter'), + new Twig_SimpleFilter('convert_encoding', 'twig_convert_encoding'), + + // string filters + new Twig_SimpleFilter('title', 'twig_title_string_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('capitalize', 'twig_capitalize_string_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('upper', 'strtoupper'), + new Twig_SimpleFilter('lower', 'strtolower'), + new Twig_SimpleFilter('striptags', 'strip_tags'), + new Twig_SimpleFilter('trim', 'twig_trim_filter'), + new Twig_SimpleFilter('nl2br', 'nl2br', array('pre_escape' => 'html', 'is_safe' => array('html'))), + + // array helpers + new Twig_SimpleFilter('join', 'twig_join_filter'), + new Twig_SimpleFilter('split', 'twig_split_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('sort', 'twig_sort_filter'), + new Twig_SimpleFilter('merge', 'twig_array_merge'), + new Twig_SimpleFilter('batch', 'twig_array_batch'), + + // string/array filters + new Twig_SimpleFilter('reverse', 'twig_reverse_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('length', 'twig_length_filter', array('needs_environment' => true)), + new Twig_SimpleFilter('slice', 'twig_slice', array('needs_environment' => true)), + new Twig_SimpleFilter('first', 'twig_first', array('needs_environment' => true)), + new Twig_SimpleFilter('last', 'twig_last', array('needs_environment' => true)), + + // iteration and runtime + new Twig_SimpleFilter('default', '_twig_default_filter', array('node_class' => 'Twig_Node_Expression_Filter_Default')), + new Twig_SimpleFilter('keys', 'twig_get_array_keys_filter'), + + // escaping + new Twig_SimpleFilter('escape', 'twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')), + new Twig_SimpleFilter('e', 'twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')), + ); + + if (function_exists('mb_get_info')) { + $filters[] = new Twig_SimpleFilter('upper', 'twig_upper_filter', array('needs_environment' => true)); + $filters[] = new Twig_SimpleFilter('lower', 'twig_lower_filter', array('needs_environment' => true)); + } + + return $filters; + } + + public function getFunctions() + { + return array( + new Twig_SimpleFunction('max', 'max'), + new Twig_SimpleFunction('min', 'min'), + new Twig_SimpleFunction('range', 'range'), + new Twig_SimpleFunction('constant', 'twig_constant'), + new Twig_SimpleFunction('cycle', 'twig_cycle'), + new Twig_SimpleFunction('random', 'twig_random', array('needs_environment' => true)), + new Twig_SimpleFunction('date', 'twig_date_converter', array('needs_environment' => true)), + new Twig_SimpleFunction('include', 'twig_include', array('needs_environment' => true, 'needs_context' => true, 'is_safe' => array('all'))), + new Twig_SimpleFunction('source', 'twig_source', array('needs_environment' => true, 'is_safe' => array('all'))), + ); + } + + public function getTests() + { + return array( + new Twig_SimpleTest('even', null, array('node_class' => 'Twig_Node_Expression_Test_Even')), + new Twig_SimpleTest('odd', null, array('node_class' => 'Twig_Node_Expression_Test_Odd')), + new Twig_SimpleTest('defined', null, array('node_class' => 'Twig_Node_Expression_Test_Defined')), + new Twig_SimpleTest('sameas', null, array('node_class' => 'Twig_Node_Expression_Test_Sameas', 'deprecated' => '1.21', 'alternative' => 'same as')), + new Twig_SimpleTest('same as', null, array('node_class' => 'Twig_Node_Expression_Test_Sameas')), + new Twig_SimpleTest('none', null, array('node_class' => 'Twig_Node_Expression_Test_Null')), + new Twig_SimpleTest('null', null, array('node_class' => 'Twig_Node_Expression_Test_Null')), + new Twig_SimpleTest('divisibleby', null, array('node_class' => 'Twig_Node_Expression_Test_Divisibleby', 'deprecated' => '1.21', 'alternative' => 'divisible by')), + new Twig_SimpleTest('divisible by', null, array('node_class' => 'Twig_Node_Expression_Test_Divisibleby')), + new Twig_SimpleTest('constant', null, array('node_class' => 'Twig_Node_Expression_Test_Constant')), + new Twig_SimpleTest('empty', 'twig_test_empty'), + new Twig_SimpleTest('iterable', 'twig_test_iterable'), + ); + } + + public function getOperators() + { + return array( + array( + 'not' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'), + '-' => array('precedence' => 500, 'class' => 'Twig_Node_Expression_Unary_Neg'), + '+' => array('precedence' => 500, 'class' => 'Twig_Node_Expression_Unary_Pos'), + ), + array( + 'or' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'and' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'b-or' => array('precedence' => 16, 'class' => 'Twig_Node_Expression_Binary_BitwiseOr', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'b-xor' => array('precedence' => 17, 'class' => 'Twig_Node_Expression_Binary_BitwiseXor', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'b-and' => array('precedence' => 18, 'class' => 'Twig_Node_Expression_Binary_BitwiseAnd', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '==' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Equal', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '!=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '<' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Less', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '>' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Greater', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '>=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_GreaterEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '<=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_LessEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'not in' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotIn', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'in' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_In', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'matches' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Matches', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'starts with' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_StartsWith', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'ends with' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_EndsWith', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '..' => array('precedence' => 25, 'class' => 'Twig_Node_Expression_Binary_Range', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '+' => array('precedence' => 30, 'class' => 'Twig_Node_Expression_Binary_Add', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '-' => array('precedence' => 30, 'class' => 'Twig_Node_Expression_Binary_Sub', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '~' => array('precedence' => 40, 'class' => 'Twig_Node_Expression_Binary_Concat', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '*' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Mul', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '/' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Div', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '//' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_FloorDiv', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '%' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Mod', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'is' => array('precedence' => 100, 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + 'is not' => array('precedence' => 100, 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT), + '**' => array('precedence' => 200, 'class' => 'Twig_Node_Expression_Binary_Power', 'associativity' => Twig_ExpressionParser::OPERATOR_RIGHT), + '??' => array('precedence' => 300, 'class' => 'Twig_Node_Expression_NullCoalesce', 'associativity' => Twig_ExpressionParser::OPERATOR_RIGHT), + ), + ); + } + + public function getName() + { + return 'core'; + } +} + +/** + * 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 Twig_Environment $env + * @param Traversable|array|int|float|string $values The values to pick a random item from + * + * @throws Twig_Error_Runtime 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(Twig_Environment $env, $values = null) +{ + if (null === $values) { + return mt_rand(); + } + + if (is_int($values) || is_float($values)) { + return $values < 0 ? mt_rand($values, 0) : mt_rand(0, $values); + } + + if ($values instanceof Traversable) { + $values = iterator_to_array($values); + } elseif (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 (!is_array($values)) { + return $values; + } + + if (0 === count($values)) { + throw new Twig_Error_Runtime('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 Twig_Environment $env + * @param DateTime|DateTimeInterface|DateInterval|string $date A date + * @param string|null $format The target format, null to use the default + * @param DateTimeZone|string|null|false $timezone The target timezone, null to use the default, false to leave unchanged + * + * @return string The formatted date + */ +function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null) +{ + if (null === $format) { + $formats = $env->getExtension('Twig_Extension_Core')->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 Twig_Environment $env + * @param DateTime|string $date A date + * @param string $modifier A modifier string + * + * @return DateTime A new date object + */ +function twig_date_modify_filter(Twig_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 Twig_Environment $env + * @param DateTime|DateTimeInterface|string|null $date A date + * @param DateTimeZone|string|null|false $timezone The target timezone, null to use the default, false to leave unchanged + * + * @return DateTime A DateTime instance + */ +function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null) +{ + // determine the timezone + if (false !== $timezone) { + if (null === $timezone) { + $timezone = $env->getExtension('Twig_Extension_Core')->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_Core')->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_Core')->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 ($from instanceof Traversable) { + $from = iterator_to_array($from); + } elseif (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); + } elseif (!is_array($from)) { + throw new Twig_Error_Runtime(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, $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 Twig_Error_Runtime('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 Twig_Environment $env + * @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(Twig_Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null) +{ + $defaults = $env->getExtension('Twig_Extension_Core')->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); +} + +if (PHP_VERSION_ID < 50300) { + /** + * JSON encodes a variable. + * + * @param mixed $value the value to encode + * @param int $options Not used on PHP 5.2.x + * + * @return mixed The JSON encoded value + */ + function twig_jsonencode_filter($value, $options = 0) + { + if ($value instanceof Twig_Markup) { + $value = (string) $value; + } elseif (is_array($value)) { + array_walk_recursive($value, '_twig_markup2string'); + } + + return json_encode($value); + } +} else { + /** + * 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 Twig_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 Twig_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 ($arr1 instanceof Traversable) { + $arr1 = iterator_to_array($arr1); + } elseif (!is_array($arr1)) { + throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', gettype($arr1))); + } + + if ($arr2 instanceof Traversable) { + $arr2 = iterator_to_array($arr2); + } elseif (!is_array($arr2)) { + throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', gettype($arr2))); + } + + return array_merge($arr1, $arr2); +} + +/** + * Slices a variable. + * + * @param Twig_Environment $env + * @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(Twig_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 $exception) { + return array(); + } + } + + $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 Twig_Environment $env + * @param mixed $item A variable + * + * @return mixed The first element of the item + */ +function twig_first(Twig_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 Twig_Environment $env + * @param mixed $item A variable + * + * @return mixed The last element of the item + */ +function twig_last(Twig_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 separator between elements is an empty string per default, you can define it with the optional parameter. + * + *
    + *  {{ [1, 2, 3]|join('|') }}
    + *  {# returns 1|2|3 #}
    + *
    + *  {{ [1, 2, 3]|join }}
    + *  {# returns 123 #}
    + * 
    + * + * @param array $value An array + * @param string $glue The separator + * + * @return string The concatenated string + */ +function twig_join_filter($value, $glue = '') +{ + if ($value instanceof Traversable) { + $value = iterator_to_array($value, false); + } + + return implode($glue, (array) $value); +} + +/** + * 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 Twig_Environment $env + * @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(Twig_Environment $env, $value, $delimiter, $limit = null) +{ + if (!empty($delimiter)) { + 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('/(? + * {% for key in array|keys %} + * {# ... #} + * {% endfor %} + * + * + * @param array $array An array + * + * @return array The keys + */ +function twig_get_array_keys_filter($array) +{ + if ($array instanceof Traversable) { + while ($array instanceof IteratorAggregate) { + $array = $array->getIterator(); + } + + if ($array instanceof Iterator) { + $keys = array(); + $array->rewind(); + while ($array->valid()) { + $keys[] = $array->key(); + $array->next(); + } + + return $keys; + } + + $keys = array(); + foreach ($array as $key => $item) { + $keys[] = $key; + } + + return $keys; + } + + if (!is_array($array)) { + return array(); + } + + return array_keys($array); +} + +/** + * Reverses a variable. + * + * @param Twig_Environment $env + * @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(Twig_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 Twig_Error_Runtime(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 (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 Twig_Error_Runtime 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 Twig_Error_Runtime('Trimming side must be "left", "right" or "both".'); + } +} + +/** + * Escapes a string. + * + * @param Twig_Environment $env + * @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(Twig_Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false) +{ + if ($autoescape && $string instanceof Twig_Markup) { + return $string; + } + + if (!is_string($string)) { + if (is_object($string) && method_exists($string, '__toString')) { + $string = (string) $string; + } elseif (in_array($strategy, array('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 = array( + '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 Twig_Error_Runtime('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 Twig_Error_Runtime('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 Twig_Error_Runtime('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': + if (PHP_VERSION_ID < 50300) { + return str_replace('%7E', '~', rawurlencode($string)); + } + + return rawurlencode($string); + + default: + static $escapers; + + if (null === $escapers) { + $escapers = $env->getExtension('Twig_Extension_Core')->getEscapers(); + } + + if (isset($escapers[$strategy])) { + return call_user_func($escapers[$strategy], $env, $string, $charset); + } + + $validStrategies = implode(', ', array_merge(array('html', 'js', 'url', 'css', 'html_attr'), array_keys($escapers))); + + throw new Twig_Error_Runtime(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies)); + } +} + +/** + * @internal + */ +function twig_escape_filter_is_safe(Twig_Node $filterArgs) +{ + foreach ($filterArgs as $arg) { + if ($arg instanceof Twig_Node_Expression_Constant) { + return array($arg->getAttribute('value')); + } + + return array(); + } + + return array('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 Twig_Error_Runtime('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 = array( + '\\' => '\\\\', + '/' => '\\/', + "\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 = array( + 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 Twig_Environment $env + * @param mixed $thing A variable + * + * @return int The length of the value + */ + function twig_length_filter(Twig_Environment $env, $thing) + { + if (null === $thing) { + return 0; + } + + if (is_scalar($thing)) { + return mb_strlen($thing, $env->getCharset()); + } + + if ($thing instanceof \SimpleXMLElement) { + return count($thing); + } + + if (is_object($thing) && method_exists($thing, '__toString') && !$thing instanceof \Countable) { + return mb_strlen((string) $thing, $env->getCharset()); + } + + if ($thing instanceof \Countable || is_array($thing)) { + return count($thing); + } + + if ($thing instanceof \IteratorAggregate) { + return iterator_count($thing); + } + + return 1; + } + + /** + * Converts a string to uppercase. + * + * @param Twig_Environment $env + * @param string $string A string + * + * @return string The uppercased string + */ + function twig_upper_filter(Twig_Environment $env, $string) + { + if (null !== $charset = $env->getCharset()) { + return mb_strtoupper($string, $charset); + } + + return strtoupper($string); + } + + /** + * Converts a string to lowercase. + * + * @param Twig_Environment $env + * @param string $string A string + * + * @return string The lowercased string + */ + function twig_lower_filter(Twig_Environment $env, $string) + { + if (null !== $charset = $env->getCharset()) { + return mb_strtolower($string, $charset); + } + + return strtolower($string); + } + + /** + * Returns a titlecased string. + * + * @param Twig_Environment $env + * @param string $string A string + * + * @return string The titlecased string + */ + function twig_title_string_filter(Twig_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 Twig_Environment $env + * @param string $string A string + * + * @return string The capitalized string + */ + function twig_capitalize_string_filter(Twig_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 Twig_Environment $env + * @param mixed $thing A variable + * + * @return int The length of the value + */ + function twig_length_filter(Twig_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 Twig_Environment $env + * @param string $string A string + * + * @return string The titlecased string + */ + function twig_title_string_filter(Twig_Environment $env, $string) + { + return ucwords(strtolower($string)); + } + + /** + * Returns a capitalized string. + * + * @param Twig_Environment $env + * @param string $string A string + * + * @return string The capitalized string + */ + function twig_capitalize_string_filter(Twig_Environment $env, $string) + { + return ucfirst(strtolower($string)); + } +} + +/** + * @internal + */ +function twig_ensure_traversable($seq) +{ + if ($seq instanceof Traversable || is_array($seq)) { + return $seq; + } + + return array(); +} + +/** + * 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 (is_object($value) && method_exists($value, '__toString')) { + return '' === (string) $value; + } + + return '' === $value || false === $value || null === $value || array() === $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 Twig_Environment $env + * @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(Twig_Environment $env, $context, $template, $variables = array(), $withContext = true, $ignoreMissing = false, $sandboxed = false) +{ + $alreadySandboxed = false; + $sandbox = null; + if ($withContext) { + $variables = array_merge($context, $variables); + } + + if ($isSandboxed = $sandboxed && $env->hasExtension('Twig_Extension_Sandbox')) { + $sandbox = $env->getExtension('Twig_Extension_Sandbox'); + if (!$alreadySandboxed = $sandbox->isSandboxed()) { + $sandbox->enableSandbox(); + } + } + + $result = ''; + try { + $result = $env->resolveTemplate($template)->render($variables); + } catch (Twig_Error_Loader $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; + } + + if ($isSandboxed && !$alreadySandboxed) { + $sandbox->disableSandbox(); + } + + return $result; +} + +/** + * Returns a template content without rendering it. + * + * @param Twig_Environment $env + * @param string $name The template name + * @param bool $ignoreMissing Whether to ignore missing templates or not + * + * @return string The template source + */ +function twig_source(Twig_Environment $env, $name, $ignoreMissing = false) +{ + $loader = $env->getLoader(); + try { + if (!$loader instanceof Twig_SourceContextLoaderInterface) { + return $loader->getSource($name); + } else { + return $loader->getSourceContext($name)->getCode(); + } + } catch (Twig_Error_Loader $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 null|object $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 null|object $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) +{ + if ($items instanceof Traversable) { + $items = iterator_to_array($items, false); + } + + $size = ceil($size); + + $result = array_chunk($items, $size, true); + + if (null !== $fill && !empty($result)) { + $last = count($result) - 1; + if ($fillCount = $size - count($result[$last])) { + $result[$last] = array_merge( + $result[$last], + array_fill(0, $fillCount, $fill) + ); + } + } + + return $result; +} + +class_alias('Twig_Extension_Core', 'Twig\Extension\CoreExtension', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/Debug.php b/vendor/twig/twig/lib/Twig/Extension/Debug.php new file mode 100644 index 0000000..d0cd196 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/Debug.php @@ -0,0 +1,67 @@ + $isDumpOutputHtmlSafe ? array('html') : array(), 'needs_context' => true, 'needs_environment' => true)), + ); + } + + public function getName() + { + return 'debug'; + } +} + +function twig_var_dump(Twig_Environment $env, $context) +{ + if (!$env->isDebug()) { + return; + } + + ob_start(); + + $count = func_num_args(); + if (2 === $count) { + $vars = array(); + foreach ($context as $key => $value) { + if (!$value instanceof Twig_Template) { + $vars[$key] = $value; + } + } + + var_dump($vars); + } else { + for ($i = 2; $i < $count; ++$i) { + var_dump(func_get_arg($i)); + } + } + + return ob_get_clean(); +} + +class_alias('Twig_Extension_Debug', 'Twig\Extension\DebugExtension', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/Escaper.php b/vendor/twig/twig/lib/Twig/Extension/Escaper.php new file mode 100644 index 0000000..46c2d84 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/Escaper.php @@ -0,0 +1,112 @@ +setDefaultStrategy($defaultStrategy); + } + + public function getTokenParsers() + { + return array(new Twig_TokenParser_AutoEscape()); + } + + public function getNodeVisitors() + { + return array(new Twig_NodeVisitor_Escaper()); + } + + public function getFilters() + { + return array( + new Twig_SimpleFilter('raw', 'twig_raw_filter', array('is_safe' => array('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 = array('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'; + } +} + +/** + * Marks a variable as being safe. + * + * @param string $string A PHP variable + * + * @return string + */ +function twig_raw_filter($string) +{ + return $string; +} + +class_alias('Twig_Extension_Escaper', 'Twig\Extension\EscaperExtension', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/GlobalsInterface.php b/vendor/twig/twig/lib/Twig/Extension/GlobalsInterface.php new file mode 100644 index 0000000..922cd2c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/GlobalsInterface.php @@ -0,0 +1,24 @@ + + */ +interface Twig_Extension_GlobalsInterface +{ +} + +class_alias('Twig_Extension_GlobalsInterface', 'Twig\Extension\GlobalsInterface', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/InitRuntimeInterface.php b/vendor/twig/twig/lib/Twig/Extension/InitRuntimeInterface.php new file mode 100644 index 0000000..1549862 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/InitRuntimeInterface.php @@ -0,0 +1,24 @@ + + */ +interface Twig_Extension_InitRuntimeInterface +{ +} + +class_alias('Twig_Extension_InitRuntimeInterface', 'Twig\Extension\InitRuntimeInterface', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/Optimizer.php b/vendor/twig/twig/lib/Twig/Extension/Optimizer.php new file mode 100644 index 0000000..6c62e3e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/Optimizer.php @@ -0,0 +1,35 @@ +optimizers = $optimizers; + } + + public function getNodeVisitors() + { + return array(new Twig_NodeVisitor_Optimizer($this->optimizers)); + } + + public function getName() + { + return 'optimizer'; + } +} + +class_alias('Twig_Extension_Optimizer', 'Twig\Extension\OptimizerExtension', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/Profiler.php b/vendor/twig/twig/lib/Twig/Extension/Profiler.php new file mode 100644 index 0000000..fcfc002 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/Profiler.php @@ -0,0 +1,49 @@ +actives[] = $profile; + } + + public function enter(Twig_Profiler_Profile $profile) + { + $this->actives[0]->addProfile($profile); + array_unshift($this->actives, $profile); + } + + public function leave(Twig_Profiler_Profile $profile) + { + $profile->leave(); + array_shift($this->actives); + + if (1 === count($this->actives)) { + $this->actives[0]->leave(); + } + } + + public function getNodeVisitors() + { + return array(new Twig_Profiler_NodeVisitor_Profiler(get_class($this))); + } + + public function getName() + { + return 'profiler'; + } +} + +class_alias('Twig_Extension_Profiler', 'Twig\Extension\ProfilerExtension', false); +class_exists('Twig_Profiler_Profile'); diff --git a/vendor/twig/twig/lib/Twig/Extension/Sandbox.php b/vendor/twig/twig/lib/Twig/Extension/Sandbox.php new file mode 100644 index 0000000..5cb80a7 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/Sandbox.php @@ -0,0 +1,103 @@ +policy = $policy; + $this->sandboxedGlobally = $sandboxed; + } + + public function getTokenParsers() + { + return array(new Twig_TokenParser_Sandbox()); + } + + public function getNodeVisitors() + { + return array(new Twig_NodeVisitor_Sandbox()); + } + + 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(Twig_Sandbox_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)) { + $this->policy->checkMethodAllowed($obj, '__toString'); + } + + return $obj; + } + + public function getName() + { + return 'sandbox'; + } +} + +class_alias('Twig_Extension_Sandbox', 'Twig\Extension\SandboxExtension', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/Staging.php b/vendor/twig/twig/lib/Twig/Extension/Staging.php new file mode 100644 index 0000000..d3a0f9c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/Staging.php @@ -0,0 +1,112 @@ + + * + * @internal + */ +class Twig_Extension_Staging extends Twig_Extension +{ + protected $functions = array(); + protected $filters = array(); + protected $visitors = array(); + protected $tokenParsers = array(); + protected $globals = array(); + protected $tests = array(); + + 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(Twig_NodeVisitorInterface $visitor) + { + $this->visitors[] = $visitor; + } + + public function getNodeVisitors() + { + return $this->visitors; + } + + public function addTokenParser(Twig_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_Staging', 'Twig\Extension\StagingExtension', false); diff --git a/vendor/twig/twig/lib/Twig/Extension/StringLoader.php b/vendor/twig/twig/lib/Twig/Extension/StringLoader.php new file mode 100644 index 0000000..2ce3c99 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Extension/StringLoader.php @@ -0,0 +1,47 @@ + true)), + ); + } + + public function getName() + { + return 'string_loader'; + } +} + +/** + * Loads a template from a string. + * + *
    + * {{ include(template_from_string("Hello {{ name }}")) }}
    + * 
    + * + * @param Twig_Environment $env A Twig_Environment instance + * @param string $template A template as a string or object implementing __toString() + * + * @return Twig_Template + */ +function twig_template_from_string(Twig_Environment $env, $template) +{ + return $env->createTemplate((string) $template); +} + +class_alias('Twig_Extension_StringLoader', 'Twig\Extension\StringLoaderExtension', false); diff --git a/vendor/twig/twig/lib/Twig/ExtensionInterface.php b/vendor/twig/twig/lib/Twig/ExtensionInterface.php new file mode 100644 index 0000000..946df50 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/ExtensionInterface.php @@ -0,0 +1,90 @@ + + */ +interface Twig_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(Twig_Environment $environment); + + /** + * Returns the token parser instances to add to the existing list. + * + * @return Twig_TokenParserInterface[] + */ + public function getTokenParsers(); + + /** + * Returns the node visitor instances to add to the existing list. + * + * @return Twig_NodeVisitorInterface[] + */ + public function getNodeVisitors(); + + /** + * Returns a list of filters to add to the existing list. + * + * @return Twig_SimpleFilter[] + */ + public function getFilters(); + + /** + * Returns a list of tests to add to the existing list. + * + * @return Twig_SimpleTest[] + */ + public function getTests(); + + /** + * Returns a list of functions to add to the existing list. + * + * @return Twig_SimpleFunction[] + */ + 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_ExtensionInterface', 'Twig\Extension\ExtensionInterface', false); +class_exists('Twig_Environment'); diff --git a/vendor/twig/twig/lib/Twig/FactoryRuntimeLoader.php b/vendor/twig/twig/lib/Twig/FactoryRuntimeLoader.php new file mode 100644 index 0000000..2cdaded --- /dev/null +++ b/vendor/twig/twig/lib/Twig/FactoryRuntimeLoader.php @@ -0,0 +1,39 @@ + + */ +class Twig_FactoryRuntimeLoader implements Twig_RuntimeLoaderInterface +{ + private $map; + + /** + * @param array $map An array where keys are class names and values factory callables + */ + public function __construct($map = array()) + { + $this->map = $map; + } + + public function load($class) + { + if (isset($this->map[$class])) { + $runtimeFactory = $this->map[$class]; + + return $runtimeFactory(); + } + } +} + +class_alias('Twig_FactoryRuntimeLoader', 'Twig\RuntimeLoader\FactoryRuntimeLoader', false); diff --git a/vendor/twig/twig/lib/Twig/FileExtensionEscapingStrategy.php b/vendor/twig/twig/lib/Twig/FileExtensionEscapingStrategy.php new file mode 100644 index 0000000..8f8cd2e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/FileExtensionEscapingStrategy.php @@ -0,0 +1,60 @@ + + */ +class Twig_FileExtensionEscapingStrategy +{ + /** + * Guesses the best autoescaping strategy based on the file name. + * + * @param string $name The template name + * + * @return string|false The escaping strategy name to use or false to disable + */ + public static function guess($name) + { + if (in_array(substr($name, -1), array('/', '\\'))) { + return 'html'; // return html for directories + } + + if ('.twig' === substr($name, -5)) { + $name = substr($name, 0, -5); + } + + $extension = pathinfo($name, PATHINFO_EXTENSION); + + switch ($extension) { + case 'js': + return 'js'; + + case 'css': + return 'css'; + + case 'txt': + return false; + + default: + return 'html'; + } + } +} + +class_alias('Twig_FileExtensionEscapingStrategy', 'Twig\FileExtensionEscapingStrategy', false); diff --git a/vendor/twig/twig/lib/Twig/Filter.php b/vendor/twig/twig/lib/Twig/Filter.php new file mode 100644 index 0000000..893d75d --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Filter.php @@ -0,0 +1,84 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +abstract class Twig_Filter implements Twig_FilterInterface, Twig_FilterCallableInterface +{ + protected $options; + protected $arguments = array(); + + public function __construct(array $options = array()) + { + $this->options = array_merge(array( + 'needs_environment' => false, + 'needs_context' => false, + 'pre_escape' => null, + 'preserves_safety' => null, + 'callable' => null, + ), $options); + } + + 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(Twig_Node $filterArgs) + { + if (isset($this->options['is_safe'])) { + return $this->options['is_safe']; + } + + if (isset($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 getCallable() + { + return $this->options['callable']; + } +} diff --git a/vendor/twig/twig/lib/Twig/Filter/Function.php b/vendor/twig/twig/lib/Twig/Filter/Function.php new file mode 100644 index 0000000..71b1655 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Filter/Function.php @@ -0,0 +1,40 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Filter_Function extends Twig_Filter +{ + protected $function; + + public function __construct($function, array $options = array()) + { + $options['callable'] = $function; + + parent::__construct($options); + + $this->function = $function; + } + + public function compile() + { + return $this->function; + } +} diff --git a/vendor/twig/twig/lib/Twig/Filter/Method.php b/vendor/twig/twig/lib/Twig/Filter/Method.php new file mode 100644 index 0000000..1b75676 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Filter/Method.php @@ -0,0 +1,42 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Filter_Method extends Twig_Filter +{ + protected $extension; + protected $method; + + public function __construct(Twig_ExtensionInterface $extension, $method, array $options = array()) + { + $options['callable'] = array($extension, $method); + + parent::__construct($options); + + $this->extension = $extension; + $this->method = $method; + } + + public function compile() + { + return sprintf('$this->env->getExtension(\'%s\')->%s', get_class($this->extension), $this->method); + } +} diff --git a/vendor/twig/twig/lib/Twig/Filter/Node.php b/vendor/twig/twig/lib/Twig/Filter/Node.php new file mode 100644 index 0000000..3e6b12e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Filter/Node.php @@ -0,0 +1,42 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Filter_Node extends Twig_Filter +{ + protected $class; + + public function __construct($class, array $options = array()) + { + parent::__construct($options); + + $this->class = $class; + } + + public function getClass() + { + return $this->class; + } + + public function compile() + { + } +} diff --git a/vendor/twig/twig/lib/Twig/FilterCallableInterface.php b/vendor/twig/twig/lib/Twig/FilterCallableInterface.php new file mode 100644 index 0000000..21b028c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/FilterCallableInterface.php @@ -0,0 +1,24 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +interface Twig_FilterCallableInterface +{ + public function getCallable(); +} diff --git a/vendor/twig/twig/lib/Twig/FilterInterface.php b/vendor/twig/twig/lib/Twig/FilterInterface.php new file mode 100644 index 0000000..9d7e9ab --- /dev/null +++ b/vendor/twig/twig/lib/Twig/FilterInterface.php @@ -0,0 +1,43 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +interface Twig_FilterInterface +{ + /** + * Compiles a filter. + * + * @return string The PHP code for the filter + */ + public function compile(); + + public function needsEnvironment(); + + public function needsContext(); + + public function getSafe(Twig_Node $filterArgs); + + public function getPreservesSafety(); + + public function getPreEscape(); + + public function setArguments($arguments); + + public function getArguments(); +} diff --git a/vendor/twig/twig/lib/Twig/Function.php b/vendor/twig/twig/lib/Twig/Function.php new file mode 100644 index 0000000..9dc16e9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Function.php @@ -0,0 +1,74 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +abstract class Twig_Function implements Twig_FunctionInterface, Twig_FunctionCallableInterface +{ + protected $options; + protected $arguments = array(); + + public function __construct(array $options = array()) + { + $this->options = array_merge(array( + 'needs_environment' => false, + 'needs_context' => false, + 'callable' => null, + ), $options); + } + + 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(Twig_Node $functionArgs) + { + if (isset($this->options['is_safe'])) { + return $this->options['is_safe']; + } + + if (isset($this->options['is_safe_callback'])) { + return call_user_func($this->options['is_safe_callback'], $functionArgs); + } + + return array(); + } + + public function getCallable() + { + return $this->options['callable']; + } +} diff --git a/vendor/twig/twig/lib/Twig/Function/Function.php b/vendor/twig/twig/lib/Twig/Function/Function.php new file mode 100644 index 0000000..97c0eb7 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Function/Function.php @@ -0,0 +1,41 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Function_Function extends Twig_Function +{ + protected $function; + + public function __construct($function, array $options = array()) + { + $options['callable'] = $function; + + parent::__construct($options); + + $this->function = $function; + } + + public function compile() + { + return $this->function; + } +} diff --git a/vendor/twig/twig/lib/Twig/Function/Method.php b/vendor/twig/twig/lib/Twig/Function/Method.php new file mode 100644 index 0000000..4299e11 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Function/Method.php @@ -0,0 +1,43 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Function_Method extends Twig_Function +{ + protected $extension; + protected $method; + + public function __construct(Twig_ExtensionInterface $extension, $method, array $options = array()) + { + $options['callable'] = array($extension, $method); + + parent::__construct($options); + + $this->extension = $extension; + $this->method = $method; + } + + public function compile() + { + return sprintf('$this->env->getExtension(\'%s\')->%s', get_class($this->extension), $this->method); + } +} diff --git a/vendor/twig/twig/lib/Twig/Function/Node.php b/vendor/twig/twig/lib/Twig/Function/Node.php new file mode 100644 index 0000000..0adc5d9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Function/Node.php @@ -0,0 +1,42 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Function_Node extends Twig_Function +{ + protected $class; + + public function __construct($class, array $options = array()) + { + parent::__construct($options); + + $this->class = $class; + } + + public function getClass() + { + return $this->class; + } + + public function compile() + { + } +} diff --git a/vendor/twig/twig/lib/Twig/FunctionCallableInterface.php b/vendor/twig/twig/lib/Twig/FunctionCallableInterface.php new file mode 100644 index 0000000..d23d691 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/FunctionCallableInterface.php @@ -0,0 +1,24 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +interface Twig_FunctionCallableInterface +{ + public function getCallable(); +} diff --git a/vendor/twig/twig/lib/Twig/FunctionInterface.php b/vendor/twig/twig/lib/Twig/FunctionInterface.php new file mode 100644 index 0000000..00d4f95 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/FunctionInterface.php @@ -0,0 +1,40 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +interface Twig_FunctionInterface +{ + /** + * Compiles a function. + * + * @return string The PHP code for the function + */ + public function compile(); + + public function needsEnvironment(); + + public function needsContext(); + + public function getSafe(Twig_Node $filterArgs); + + public function setArguments($arguments); + + public function getArguments(); +} diff --git a/vendor/twig/twig/lib/Twig/Lexer.php b/vendor/twig/twig/lib/Twig/Lexer.php new file mode 100644 index 0000000..41211eb --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Lexer.php @@ -0,0 +1,427 @@ + + */ +class Twig_Lexer implements Twig_LexerInterface +{ + protected $tokens; + protected $code; + protected $cursor; + protected $lineno; + protected $end; + protected $state; + protected $states; + protected $brackets; + protected $env; + // to be renamed to $name in 2.0 (where it is private) + protected $filename; + protected $options; + protected $regexes; + protected $position; + protected $positions; + protected $currentVarBlockLine; + + private $source; + + const STATE_DATA = 0; + const STATE_BLOCK = 1; + const STATE_VAR = 2; + const STATE_STRING = 3; + 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]+)?/A'; + const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As'; + const REGEX_DQ_STRING_DELIM = '/"/A'; + const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As'; + const PUNCTUATION = '()[]{}?:.,|'; + + public function __construct(Twig_Environment $env, array $options = array()) + { + $this->env = $env; + + $this->options = array_merge(array( + 'tag_comment' => array('{#', '#}'), + 'tag_block' => array('{%', '%}'), + 'tag_variable' => array('{{', '}}'), + 'whitespace_trim' => '-', + '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*|'.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', + ); + } + + public function tokenize($code, $name = null) + { + 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; + } + + if (((int) ini_get('mbstring.func_overload')) & 2) { + @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) { + $mbEncoding = mb_internal_encoding(); + mb_internal_encoding('ASCII'); + } else { + $mbEncoding = null; + } + + $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 = array(); + $this->state = self::STATE_DATA; + $this->states = array(); + $this->brackets = array(); + $this->position = -1; + + // find all token starts in one go + preg_match_all($this->regexes['lex_tokens_start'], $this->code, $matches, PREG_OFFSET_CAPTURE); + $this->positions = $matches; + + while ($this->cursor < $this->end) { + // dispatch to the lexing functions depending + // on the current state + switch ($this->state) { + case self::STATE_DATA: + $this->lexData(); + break; + + case self::STATE_BLOCK: + $this->lexBlock(); + break; + + case self::STATE_VAR: + $this->lexVar(); + break; + + case self::STATE_STRING: + $this->lexString(); + break; + + case self::STATE_INTERPOLATION: + $this->lexInterpolation(); + break; + } + } + + $this->pushToken(Twig_Token::EOF_TYPE); + + if (!empty($this->brackets)) { + list($expect, $lineno) = array_pop($this->brackets); + throw new Twig_Error_Syntax(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + } + + if ($mbEncoding) { + mb_internal_encoding($mbEncoding); + } + + 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(Twig_Token::TEXT_TYPE, substr($this->code, $this->cursor)); + $this->cursor = $this->end; + + return; + } + + // 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) { + return; + } + $position = $this->positions[0][++$this->position]; + } + + // push the template text first + $text = $textContent = substr($this->code, $this->cursor, $position[1] - $this->cursor); + if (isset($this->positions[2][$this->position][0])) { + $text = rtrim($text); + } + $this->pushToken(Twig_Token::TEXT_TYPE, $text); + $this->moveCursor($textContent.$position[0]); + + switch ($this->positions[1][$this->position][0]) { + case $this->options['tag_comment'][0]: + $this->lexComment(); + break; + + case $this->options['tag_block'][0]: + // raw data? + 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, null, $this->cursor)) { + $this->moveCursor($match[0]); + $this->lineno = (int) $match[1]; + } else { + $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(Twig_Token::VAR_START_TYPE); + $this->pushState(self::STATE_VAR); + $this->currentVarBlockLine = $this->lineno; + break; + } + } + + protected function lexBlock() + { + 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 { + $this->lexExpression(); + } + } + + protected function lexVar() + { + 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 { + $this->lexExpression(); + } + } + + protected function lexExpression() + { + // whitespace + if (preg_match('/\s+/A', $this->code, $match, null, $this->cursor)) { + $this->moveCursor($match[0]); + + if ($this->cursor >= $this->end) { + throw new Twig_Error_Syntax(sprintf('Unclosed "%s".', self::STATE_BLOCK === $this->state ? 'block' : 'variable'), $this->currentVarBlockLine, $this->source); + } + } + + // operators + 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, 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, 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(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[] = array($this->code[$this->cursor], $this->lineno); + } + // closing bracket + elseif (false !== strpos(')]}', $this->code[$this->cursor])) { + if (empty($this->brackets)) { + 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 Twig_Error_Syntax(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); + } + } + + $this->pushToken(Twig_Token::PUNCTUATION_TYPE, $this->code[$this->cursor]); + ++$this->cursor; + } + // strings + 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, null, $this->cursor)) { + $this->brackets[] = array('"', $this->lineno); + $this->pushState(self::STATE_STRING); + $this->moveCursor($match[0]); + } + // unlexable + else { + throw new Twig_Error_Syntax(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); + } + } + + protected function lexRawData($tag) + { + if ('raw' === $tag) { + @trigger_error(sprintf('Twig Tag "raw" is deprecated since version 1.21. Use "verbatim" instead in %s at line %d.', $this->filename, $this->lineno), E_USER_DEPRECATED); + } + + if (!preg_match(str_replace('%s', $tag, $this->regexes['lex_raw_data']), $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { + 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]); + + if (false !== strpos($match[1][0], $this->options['whitespace_trim'])) { + $text = rtrim($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 Twig_Error_Syntax('Unclosed comment.', $this->lineno, $this->source); + } + + $this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]); + } + + protected function lexString() + { + 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, 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, null, $this->cursor)) { + list($expect, $lineno) = array_pop($this->brackets); + 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 Twig_Error_Syntax(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, null, $this->cursor)) { + array_pop($this->brackets); + $this->pushToken(Twig_Token::INTERPOLATION_END_TYPE); + $this->moveCursor($match[0]); + $this->popState(); + } else { + $this->lexExpression(); + } + } + + protected function pushToken($type, $value = '') + { + // do not push empty text tokens + if (Twig_Token::TEXT_TYPE === $type && '' === $value) { + return; + } + + $this->tokens[] = new Twig_Token($type, $value, $this->lineno); + } + + protected function moveCursor($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()) + ); + + $operators = array_combine($operators, array_map('strlen', $operators)); + arsort($operators); + + $regex = array(); + foreach ($operators as $operator => $length) { + // an operator that ends with a character must be followed by + // a whitespace or a parenthesis + if (ctype_alpha($operator[$length - 1])) { + $r = preg_quote($operator, '/').'(?=[\s()])'; + } else { + $r = preg_quote($operator, '/'); + } + + // an operator with a space can be any amount of whitespaces + $r = preg_replace('/\s+/', '\s+', $r); + + $regex[] = $r; + } + + return '/'.implode('|', $regex).'/A'; + } + + protected function pushState($state) + { + $this->states[] = $this->state; + $this->state = $state; + } + + protected function popState() + { + 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', false); diff --git a/vendor/twig/twig/lib/Twig/LexerInterface.php b/vendor/twig/twig/lib/Twig/LexerInterface.php new file mode 100644 index 0000000..c10bbfe --- /dev/null +++ b/vendor/twig/twig/lib/Twig/LexerInterface.php @@ -0,0 +1,32 @@ + + * + * @deprecated since 1.12 (to be removed in 3.0) + */ +interface Twig_LexerInterface +{ + /** + * Tokenizes a source code. + * + * @param string|Twig_Source $code The source code + * @param string $name A unique identifier for the source code + * + * @return Twig_TokenStream + * + * @throws Twig_Error_Syntax When the code is syntactically wrong + */ + public function tokenize($code, $name = null); +} diff --git a/vendor/twig/twig/lib/Twig/Loader/Array.php b/vendor/twig/twig/lib/Twig/Loader/Array.php new file mode 100644 index 0000000..0aac769 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Loader/Array.php @@ -0,0 +1,97 @@ + + */ +class Twig_Loader_Array implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface +{ + protected $templates = array(); + + /** + * @param array $templates An array of templates (keys are the names, and values are the source code) + */ + public function __construct(array $templates = array()) + { + $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 Twig_Error_Loader(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 Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name)); + } + + return new Twig_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 Twig_Error_Loader(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 Twig_Error_Loader(sprintf('Template "%s" is not defined.', $name)); + } + + return true; + } +} + +class_alias('Twig_Loader_Array', 'Twig\Loader\ArrayLoader', false); diff --git a/vendor/twig/twig/lib/Twig/Loader/Chain.php b/vendor/twig/twig/lib/Twig/Loader/Chain.php new file mode 100644 index 0000000..59a3379 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Loader/Chain.php @@ -0,0 +1,151 @@ + + */ +class Twig_Loader_Chain implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface +{ + private $hasSourceCache = array(); + protected $loaders = array(); + + /** + * @param Twig_LoaderInterface[] $loaders + */ + public function __construct(array $loaders = array()) + { + foreach ($loaders as $loader) { + $this->addLoader($loader); + } + } + + public function addLoader(Twig_LoaderInterface $loader) + { + $this->loaders[] = $loader; + $this->hasSourceCache = array(); + } + + 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 = array(); + foreach ($this->loaders as $loader) { + if ($loader instanceof Twig_ExistsLoaderInterface && !$loader->exists($name)) { + continue; + } + + try { + return $loader->getSource($name); + } catch (Twig_Error_Loader $e) { + $exceptions[] = $e->getMessage(); + } + } + + throw new Twig_Error_Loader(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); + } + + public function getSourceContext($name) + { + $exceptions = array(); + foreach ($this->loaders as $loader) { + if ($loader instanceof Twig_ExistsLoaderInterface && !$loader->exists($name)) { + continue; + } + + try { + if ($loader instanceof Twig_SourceContextLoaderInterface) { + return $loader->getSourceContext($name); + } + + return new Twig_Source($loader->getSource($name), $name); + } catch (Twig_Error_Loader $e) { + $exceptions[] = $e->getMessage(); + } + } + + throw new Twig_Error_Loader(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 Twig_ExistsLoaderInterface) { + if ($loader->exists($name)) { + return $this->hasSourceCache[$name] = true; + } + + continue; + } + + try { + if ($loader instanceof Twig_SourceContextLoaderInterface) { + $loader->getSourceContext($name); + } else { + $loader->getSource($name); + } + + return $this->hasSourceCache[$name] = true; + } catch (Twig_Error_Loader $e) { + } + } + + return $this->hasSourceCache[$name] = false; + } + + public function getCacheKey($name) + { + $exceptions = array(); + foreach ($this->loaders as $loader) { + if ($loader instanceof Twig_ExistsLoaderInterface && !$loader->exists($name)) { + continue; + } + + try { + return $loader->getCacheKey($name); + } catch (Twig_Error_Loader $e) { + $exceptions[] = get_class($loader).': '.$e->getMessage(); + } + } + + throw new Twig_Error_Loader(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); + } + + public function isFresh($name, $time) + { + $exceptions = array(); + foreach ($this->loaders as $loader) { + if ($loader instanceof Twig_ExistsLoaderInterface && !$loader->exists($name)) { + continue; + } + + try { + return $loader->isFresh($name, $time); + } catch (Twig_Error_Loader $e) { + $exceptions[] = get_class($loader).': '.$e->getMessage(); + } + } + + throw new Twig_Error_Loader(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); + } +} + +class_alias('Twig_Loader_Chain', 'Twig\Loader\ChainLoader', false); diff --git a/vendor/twig/twig/lib/Twig/Loader/Filesystem.php b/vendor/twig/twig/lib/Twig/Loader/Filesystem.php new file mode 100644 index 0000000..f80d67d --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Loader/Filesystem.php @@ -0,0 +1,298 @@ + + */ +class Twig_Loader_Filesystem implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface +{ + /** Identifier of the main namespace. */ + const MAIN_NAMESPACE = '__main__'; + + protected $paths = array(); + protected $cache = array(); + protected $errorCache = array(); + + 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 = array(), $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] : array(); + } + + /** + * 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 = array($paths); + } + + $this->paths[$namespace] = array(); + 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 Twig_Error_Loader + */ + public function addPath($path, $namespace = self::MAIN_NAMESPACE) + { + // invalidate the cache + $this->cache = $this->errorCache = array(); + + $checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path; + if (!is_dir($checkPath)) { + throw new Twig_Error_Loader(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 Twig_Error_Loader + */ + public function prependPath($path, $namespace = self::MAIN_NAMESPACE) + { + // invalidate the cache + $this->cache = $this->errorCache = array(); + + $checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path; + if (!is_dir($checkPath)) { + throw new Twig_Error_Loader(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); + + return file_get_contents($this->findTemplate($name)); + } + + public function getSourceContext($name) + { + $path = $this->findTemplate($name); + + return new Twig_Source(file_get_contents($path), $name, $path); + } + + public function getCacheKey($name) + { + $path = $this->findTemplate($name); + $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 false !== $this->findTemplate($name, false); + } catch (Twig_Error_Loader $exception) { + @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) + { + return filemtime($this->findTemplate($name)) < $time; + } + + 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 Twig_Error_Loader($this->errorCache[$name]); + } + + try { + $this->validateName($name); + + list($namespace, $shortname) = $this->parseName($name); + } catch (Twig_Error_Loader $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 Twig_Error_Loader($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 Twig_Error_Loader($this->errorCache[$name]); + } + + protected function parseName($name, $default = self::MAIN_NAMESPACE) + { + if (isset($name[0]) && '@' == $name[0]) { + if (false === $pos = strpos($name, '/')) { + throw new Twig_Error_Loader(sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name)); + } + + $namespace = substr($name, 1, $pos - 1); + $shortname = substr($name, $pos + 1); + + return array($namespace, $shortname); + } + + return array($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 Twig_Error_Loader('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 Twig_Error_Loader(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_Filesystem', 'Twig\Loader\FilesystemLoader', false); diff --git a/vendor/twig/twig/lib/Twig/Loader/String.php b/vendor/twig/twig/lib/Twig/Loader/String.php new file mode 100644 index 0000000..950bd35 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Loader/String.php @@ -0,0 +1,58 @@ + + */ +class Twig_Loader_String implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface +{ + 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); + + return $name; + } + + public function getSourceContext($name) + { + return new Twig_Source($name, $name); + } + + public function exists($name) + { + return true; + } + + public function getCacheKey($name) + { + return $name; + } + + public function isFresh($name, $time) + { + return true; + } +} diff --git a/vendor/twig/twig/lib/Twig/LoaderInterface.php b/vendor/twig/twig/lib/Twig/LoaderInterface.php new file mode 100644 index 0000000..459a70a --- /dev/null +++ b/vendor/twig/twig/lib/Twig/LoaderInterface.php @@ -0,0 +1,57 @@ + + */ +interface Twig_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 Twig_Error_Loader When $name is not found + * + * @deprecated since 1.27 (to be removed in 2.0), implement Twig_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 Twig_Error_Loader 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 Twig_Error_Loader When $name is not found + */ + public function isFresh($name, $time); +} + +class_alias('Twig_LoaderInterface', 'Twig\Loader\LoaderInterface', false); diff --git a/vendor/twig/twig/lib/Twig/Markup.php b/vendor/twig/twig/lib/Twig/Markup.php new file mode 100644 index 0000000..8591d1f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Markup.php @@ -0,0 +1,39 @@ + + */ +class Twig_Markup implements Countable +{ + protected $content; + protected $charset; + + public function __construct($content, $charset) + { + $this->content = (string) $content; + $this->charset = $charset; + } + + public function __toString() + { + return $this->content; + } + + public function count() + { + return function_exists('mb_get_info') ? mb_strlen($this->content, $this->charset) : strlen($this->content); + } +} + +class_alias('Twig_Markup', 'Twig\Markup', false); diff --git a/vendor/twig/twig/lib/Twig/Node.php b/vendor/twig/twig/lib/Twig/Node.php new file mode 100644 index 0000000..89ada14 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node.php @@ -0,0 +1,256 @@ + + */ +class Twig_Node implements Twig_NodeInterface +{ + protected $nodes; + protected $attributes; + protected $lineno; + protected $tag; + + private $name; + + /** + * Constructor. + * + * The nodes are automatically made available as properties ($this->node). + * The attributes are automatically made available as array items ($this['name']). + * + * @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(), array $attributes = array(), $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 = array(); + foreach ($this->attributes as $name => $value) { + $attributes[] = sprintf('%s: %s', $name, str_replace("\n", '', var_export($value, true))); + } + + $repr = array(get_class($this).'('.implode(', ', $attributes)); + + if (count($this->nodes)) { + foreach ($this->nodes as $name => $node) { + $len = strlen($name) + 4; + $noderepr = array(); + 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(Twig_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 Twig_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; + } + + /** + * @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', 'Twig\Node\Node', false); +class_exists('Twig_Compiler'); diff --git a/vendor/twig/twig/lib/Twig/Node/AutoEscape.php b/vendor/twig/twig/lib/Twig/Node/AutoEscape.php new file mode 100644 index 0000000..17e4e38 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/AutoEscape.php @@ -0,0 +1,36 @@ + + */ +class Twig_Node_AutoEscape extends Twig_Node +{ + public function __construct($value, Twig_NodeInterface $body, $lineno, $tag = 'autoescape') + { + parent::__construct(array('body' => $body), array('value' => $value), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->subcompile($this->getNode('body')); + } +} + +class_alias('Twig_Node_AutoEscape', 'Twig\Node\AutoEscapeNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Block.php b/vendor/twig/twig/lib/Twig/Node/Block.php new file mode 100644 index 0000000..91752ad --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Block.php @@ -0,0 +1,41 @@ + + */ +class Twig_Node_Block extends Twig_Node +{ + public function __construct($name, Twig_NodeInterface $body, $lineno, $tag = null) + { + parent::__construct(array('body' => $body), array('name' => $name), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write(sprintf("public function block_%s(\$context, array \$blocks = array())\n", $this->getAttribute('name')), "{\n") + ->indent() + ; + + $compiler + ->subcompile($this->getNode('body')) + ->outdent() + ->write("}\n\n") + ; + } +} + +class_alias('Twig_Node_Block', 'Twig\Node\BlockNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/BlockReference.php b/vendor/twig/twig/lib/Twig/Node/BlockReference.php new file mode 100644 index 0000000..92a9f39 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/BlockReference.php @@ -0,0 +1,34 @@ + + */ +class Twig_Node_BlockReference extends Twig_Node implements Twig_NodeOutputInterface +{ + public function __construct($name, $lineno, $tag = null) + { + parent::__construct(array(), array('name' => $name), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write(sprintf("\$this->displayBlock('%s', \$context, \$blocks);\n", $this->getAttribute('name'))) + ; + } +} + +class_alias('Twig_Node_BlockReference', 'Twig\Node\BlockReferenceNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Body.php b/vendor/twig/twig/lib/Twig/Node/Body.php new file mode 100644 index 0000000..07dfef8 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Body.php @@ -0,0 +1,21 @@ + + */ +class Twig_Node_Body extends Twig_Node +{ +} + +class_alias('Twig_Node_Body', 'Twig\Node\BodyNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/CheckSecurity.php b/vendor/twig/twig/lib/Twig/Node/CheckSecurity.php new file mode 100644 index 0000000..7258acb --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/CheckSecurity.php @@ -0,0 +1,80 @@ + + */ +class Twig_Node_CheckSecurity extends Twig_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(Twig_Compiler $compiler) + { + $tags = $filters = $functions = array(); + foreach (array('tags', 'filters', 'functions') as $type) { + foreach ($this->{'used'.ucfirst($type)} as $name => $node) { + if ($node instanceof Twig_Node) { + ${$type}[$name] = $node->getTemplateLine(); + } else { + ${$type}[$node] = null; + } + } + } + + $compiler + ->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->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(\n") + ->indent() + ->write(!$tags ? "array(),\n" : "array('".implode("', '", array_keys($tags))."'),\n") + ->write(!$filters ? "array(),\n" : "array('".implode("', '", array_keys($filters))."'),\n") + ->write(!$functions ? "array()\n" : "array('".implode("', '", array_keys($functions))."')\n") + ->outdent() + ->write(");\n") + ->outdent() + ->write("} catch (Twig_Sandbox_SecurityError \$e) {\n") + ->indent() + ->write("\$e->setSourceContext(\$this->getSourceContext());\n\n") + ->write("if (\$e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset(\$tags[\$e->getTagName()])) {\n") + ->indent() + ->write("\$e->setTemplateLine(\$tags[\$e->getTagName()]);\n") + ->outdent() + ->write("} elseif (\$e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset(\$filters[\$e->getFilterName()])) {\n") + ->indent() + ->write("\$e->setTemplateLine(\$filters[\$e->getFilterName()]);\n") + ->outdent() + ->write("} elseif (\$e instanceof Twig_Sandbox_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_CheckSecurity', 'Twig\Node\CheckSecurityNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Deprecated.php b/vendor/twig/twig/lib/Twig/Node/Deprecated.php new file mode 100644 index 0000000..e2bc553 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Deprecated.php @@ -0,0 +1,49 @@ + + */ +class Twig_Node_Deprecated extends Twig_Node +{ + public function __construct(Twig_Node_Expression $expr, $lineno, $tag = null) + { + parent::__construct(array('expr' => $expr), array(), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + $expr = $this->getNode('expr'); + + if ($expr instanceof Twig_Node_Expression_Constant) { + $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_Deprecated', 'Twig\Node\DeprecatedNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Do.php b/vendor/twig/twig/lib/Twig/Node/Do.php new file mode 100644 index 0000000..cdd7e77 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Do.php @@ -0,0 +1,35 @@ + + */ +class Twig_Node_Do extends Twig_Node +{ + public function __construct(Twig_Node_Expression $expr, $lineno, $tag = null) + { + parent::__construct(array('expr' => $expr), array(), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('') + ->subcompile($this->getNode('expr')) + ->raw(";\n") + ; + } +} + +class_alias('Twig_Node_Do', 'Twig\Node\DoNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Embed.php b/vendor/twig/twig/lib/Twig/Node/Embed.php new file mode 100644 index 0000000..3785d3a --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Embed.php @@ -0,0 +1,46 @@ + + */ +class Twig_Node_Embed extends Twig_Node_Include +{ + // 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, Twig_Node_Expression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null) + { + parent::__construct(new Twig_Node_Expression_Constant('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(Twig_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_Embed', 'Twig\Node\EmbedNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression.php b/vendor/twig/twig/lib/Twig/Node/Expression.php new file mode 100644 index 0000000..a99c4e6 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression.php @@ -0,0 +1,22 @@ + + */ +abstract class Twig_Node_Expression extends Twig_Node +{ +} + +class_alias('Twig_Node_Expression', 'Twig\Node\Expression\AbstractExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Array.php b/vendor/twig/twig/lib/Twig/Node/Expression/Array.php new file mode 100644 index 0000000..0e77bb0 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Array.php @@ -0,0 +1,83 @@ +index = -1; + foreach ($this->getKeyValuePairs() as $pair) { + if ($pair['key'] instanceof Twig_Node_Expression_Constant && ctype_digit((string) $pair['key']->getAttribute('value')) && $pair['key']->getAttribute('value') > $this->index) { + $this->index = $pair['key']->getAttribute('value'); + } + } + } + + public function getKeyValuePairs() + { + $pairs = array(); + + foreach (array_chunk($this->nodes, 2) as $pair) { + $pairs[] = array( + 'key' => $pair[0], + 'value' => $pair[1], + ); + } + + return $pairs; + } + + public function hasElement(Twig_Node_Expression $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(Twig_Node_Expression $value, Twig_Node_Expression $key = null) + { + if (null === $key) { + $key = new Twig_Node_Expression_Constant(++$this->index, $value->getTemplateLine()); + } + + array_push($this->nodes, $key, $value); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->raw('array('); + $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_Array', 'Twig\Node\Expression\ArrayExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/AssignName.php b/vendor/twig/twig/lib/Twig/Node/Expression/AssignName.php new file mode 100644 index 0000000..2e6b4c7 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/AssignName.php @@ -0,0 +1,25 @@ +raw('$context[') + ->string($this->getAttribute('name')) + ->raw(']') + ; + } +} + +class_alias('Twig_Node_Expression_AssignName', 'Twig\Node\Expression\AssignNameExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary.php new file mode 100644 index 0000000..2b545d9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary.php @@ -0,0 +1,37 @@ + $left, 'right' => $right), array(), $lineno); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('(') + ->subcompile($this->getNode('left')) + ->raw(' ') + ; + $this->operator($compiler); + $compiler + ->raw(' ') + ->subcompile($this->getNode('right')) + ->raw(')') + ; + } + + abstract public function operator(Twig_Compiler $compiler); +} + +class_alias('Twig_Node_Expression_Binary', 'Twig\Node\Expression\Binary\AbstractBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Add.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Add.php new file mode 100644 index 0000000..5a09d83 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Add.php @@ -0,0 +1,20 @@ +raw('+'); + } +} + +class_alias('Twig_Node_Expression_Binary_Add', 'Twig\Node\Expression\Binary\AddBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/And.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/And.php new file mode 100644 index 0000000..9ffddce --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/And.php @@ -0,0 +1,20 @@ +raw('&&'); + } +} + +class_alias('Twig_Node_Expression_Binary_And', 'Twig\Node\Expression\Binary\AndBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseAnd.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseAnd.php new file mode 100644 index 0000000..e46e9eb --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseAnd.php @@ -0,0 +1,20 @@ +raw('&'); + } +} + +class_alias('Twig_Node_Expression_Binary_BitwiseAnd', 'Twig\Node\Expression\Binary\BitwiseAndBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseOr.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseOr.php new file mode 100644 index 0000000..5d7f1b7 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseOr.php @@ -0,0 +1,20 @@ +raw('|'); + } +} + +class_alias('Twig_Node_Expression_Binary_BitwiseOr', 'Twig\Node\Expression\Binary\BitwiseOrBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseXor.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseXor.php new file mode 100644 index 0000000..82edf51 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/BitwiseXor.php @@ -0,0 +1,20 @@ +raw('^'); + } +} + +class_alias('Twig_Node_Expression_Binary_BitwiseXor', 'Twig\Node\Expression\Binary\BitwiseXorBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Concat.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Concat.php new file mode 100644 index 0000000..91abca6 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Concat.php @@ -0,0 +1,20 @@ +raw('.'); + } +} + +class_alias('Twig_Node_Expression_Binary_Concat', 'Twig\Node\Expression\Binary\ConcatBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Div.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Div.php new file mode 100644 index 0000000..38ffa30 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Div.php @@ -0,0 +1,20 @@ +raw('/'); + } +} + +class_alias('Twig_Node_Expression_Binary_Div', 'Twig\Node\Expression\Binary\DivBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/EndsWith.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/EndsWith.php new file mode 100644 index 0000000..85c5293 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/EndsWith.php @@ -0,0 +1,32 @@ +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(Twig_Compiler $compiler) + { + return $compiler->raw(''); + } +} + +class_alias('Twig_Node_Expression_Binary_EndsWith', 'Twig\Node\Expression\Binary\EndsWithBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Equal.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Equal.php new file mode 100644 index 0000000..a6a6946 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Equal.php @@ -0,0 +1,19 @@ +raw('=='); + } +} + +class_alias('Twig_Node_Expression_Binary_Equal', 'Twig\Node\Expression\Binary\EqualBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/FloorDiv.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/FloorDiv.php new file mode 100644 index 0000000..7393bcb --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/FloorDiv.php @@ -0,0 +1,26 @@ +raw('(int) floor('); + parent::compile($compiler); + $compiler->raw(')'); + } + + public function operator(Twig_Compiler $compiler) + { + return $compiler->raw('/'); + } +} + +class_alias('Twig_Node_Expression_Binary_FloorDiv', 'Twig\Node\Expression\Binary\FloorDivBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Greater.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Greater.php new file mode 100644 index 0000000..832f979 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Greater.php @@ -0,0 +1,19 @@ +raw('>'); + } +} + +class_alias('Twig_Node_Expression_Binary_Greater', 'Twig\Node\Expression\Binary\GreaterBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/GreaterEqual.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/GreaterEqual.php new file mode 100644 index 0000000..c5f7624 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/GreaterEqual.php @@ -0,0 +1,19 @@ +raw('>='); + } +} + +class_alias('Twig_Node_Expression_Binary_GreaterEqual', 'Twig\Node\Expression\Binary\GreaterEqualBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/In.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/In.php new file mode 100644 index 0000000..af11244 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/In.php @@ -0,0 +1,30 @@ +raw('twig_in_filter(') + ->subcompile($this->getNode('left')) + ->raw(', ') + ->subcompile($this->getNode('right')) + ->raw(')') + ; + } + + public function operator(Twig_Compiler $compiler) + { + return $compiler->raw('in'); + } +} + +class_alias('Twig_Node_Expression_Binary_In', 'Twig\Node\Expression\Binary\InBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Less.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Less.php new file mode 100644 index 0000000..ab8fc1f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Less.php @@ -0,0 +1,19 @@ +raw('<'); + } +} + +class_alias('Twig_Node_Expression_Binary_Less', 'Twig\Node\Expression\Binary\LessBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/LessEqual.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/LessEqual.php new file mode 100644 index 0000000..71a279e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/LessEqual.php @@ -0,0 +1,19 @@ +raw('<='); + } +} + +class_alias('Twig_Node_Expression_Binary_LessEqual', 'Twig\Node\Expression\Binary\LessEqualBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Matches.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Matches.php new file mode 100644 index 0000000..5cb8558 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Matches.php @@ -0,0 +1,30 @@ +raw('preg_match(') + ->subcompile($this->getNode('right')) + ->raw(', ') + ->subcompile($this->getNode('left')) + ->raw(')') + ; + } + + public function operator(Twig_Compiler $compiler) + { + return $compiler->raw(''); + } +} + +class_alias('Twig_Node_Expression_Binary_Matches', 'Twig\Node\Expression\Binary\MatchesBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Mod.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Mod.php new file mode 100644 index 0000000..2810963 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Mod.php @@ -0,0 +1,20 @@ +raw('%'); + } +} + +class_alias('Twig_Node_Expression_Binary_Mod', 'Twig\Node\Expression\Binary\ModBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Mul.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Mul.php new file mode 100644 index 0000000..790c6a2 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Mul.php @@ -0,0 +1,20 @@ +raw('*'); + } +} + +class_alias('Twig_Node_Expression_Binary_Mul', 'Twig\Node\Expression\Binary\MulBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/NotEqual.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/NotEqual.php new file mode 100644 index 0000000..bb45c9e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/NotEqual.php @@ -0,0 +1,19 @@ +raw('!='); + } +} + +class_alias('Twig_Node_Expression_Binary_NotEqual', 'Twig\Node\Expression\Binary\NotEqualBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/NotIn.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/NotIn.php new file mode 100644 index 0000000..9dedf92 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/NotIn.php @@ -0,0 +1,30 @@ +raw('!twig_in_filter(') + ->subcompile($this->getNode('left')) + ->raw(', ') + ->subcompile($this->getNode('right')) + ->raw(')') + ; + } + + public function operator(Twig_Compiler $compiler) + { + return $compiler->raw('not in'); + } +} + +class_alias('Twig_Node_Expression_Binary_NotIn', 'Twig\Node\Expression\Binary\NotInBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Or.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Or.php new file mode 100644 index 0000000..dc9eece --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Or.php @@ -0,0 +1,20 @@ +raw('||'); + } +} + +class_alias('Twig_Node_Expression_Binary_Or', 'Twig\Node\Expression\Binary\OrBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Power.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Power.php new file mode 100644 index 0000000..d24777b --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Power.php @@ -0,0 +1,34 @@ += 50600) { + return parent::compile($compiler); + } + + $compiler + ->raw('pow(') + ->subcompile($this->getNode('left')) + ->raw(', ') + ->subcompile($this->getNode('right')) + ->raw(')') + ; + } + + public function operator(Twig_Compiler $compiler) + { + return $compiler->raw('**'); + } +} + +class_alias('Twig_Node_Expression_Binary_Power', 'Twig\Node\Expression\Binary\PowerBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Range.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Range.php new file mode 100644 index 0000000..187f676 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Range.php @@ -0,0 +1,30 @@ +raw('range(') + ->subcompile($this->getNode('left')) + ->raw(', ') + ->subcompile($this->getNode('right')) + ->raw(')') + ; + } + + public function operator(Twig_Compiler $compiler) + { + return $compiler->raw('..'); + } +} + +class_alias('Twig_Node_Expression_Binary_Range', 'Twig\Node\Expression\Binary\RangeBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/StartsWith.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/StartsWith.php new file mode 100644 index 0000000..7e43b8d --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/StartsWith.php @@ -0,0 +1,32 @@ +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(Twig_Compiler $compiler) + { + return $compiler->raw(''); + } +} + +class_alias('Twig_Node_Expression_Binary_StartsWith', 'Twig\Node\Expression\Binary\StartsWithBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Sub.php b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Sub.php new file mode 100644 index 0000000..cff8ed0 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Binary/Sub.php @@ -0,0 +1,20 @@ +raw('-'); + } +} + +class_alias('Twig_Node_Expression_Binary_Sub', 'Twig\Node\Expression\Binary\SubBinary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/BlockReference.php b/vendor/twig/twig/lib/Twig/Node/Expression/BlockReference.php new file mode 100644 index 0000000..37a3983 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/BlockReference.php @@ -0,0 +1,93 @@ + + */ +class Twig_Node_Expression_BlockReference extends Twig_Node_Expression +{ + /** + * @param Twig_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 = array('name' => $name); + if (null !== $template) { + $nodes['template'] = $template; + } + + parent::__construct($nodes, array('is_defined_test' => false, 'output' => false), $lineno, $tag); + } + + public function compile(Twig_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(Twig_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(Twig_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_BlockReference', 'Twig\Node\Expression\BlockReferenceExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Call.php b/vendor/twig/twig/lib/Twig/Node/Expression/Call.php new file mode 100644 index 0000000..ec20348 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Call.php @@ -0,0 +1,291 @@ +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 Twig_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(), array', $type, $this->getAttribute('name'))); + $closingParenthesis = true; + } + } + } else { + $compiler->raw($this->getAttribute('thing')->compile()); + } + + $this->compileArguments($compiler); + + if ($closingParenthesis) { + $compiler->raw(')'); + } + } + + protected function compileArguments(Twig_Compiler $compiler) + { + $compiler->raw('('); + + $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(')'); + } + + protected function getArguments($callable, $arguments) + { + $callType = $this->getAttribute('type'); + $callName = $this->getAttribute('name'); + + $parameters = array(); + $named = false; + foreach ($arguments as $name => $node) { + if (!is_int($name)) { + $named = true; + $name = $this->normalizeName($name); + } elseif ($named) { + throw new Twig_Error_Syntax(sprintf('Positional arguments cannot be used after named arguments for %s "%s".', $callType, $callName), $this->getTemplateLine()); + } + + $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 = array(); + $names = array(); + $missingArguments = array(); + $optionalArguments = array(); + $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 Twig_Error_Syntax(sprintf('Argument "%s" is defined twice for %s "%s".', $name, $callType, $callName), $this->getTemplateLine()); + } + + if (count($missingArguments)) { + throw new Twig_Error_Syntax(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()); + } + + $arguments = array_merge($arguments, $optionalArguments); + $arguments[] = $parameters[$name]; + unset($parameters[$name]); + $optionalArguments = array(); + } elseif (array_key_exists($pos, $parameters)) { + $arguments = array_merge($arguments, $optionalArguments); + $arguments[] = $parameters[$pos]; + unset($parameters[$pos]); + $optionalArguments = array(); + ++$pos; + } elseif ($callableParameter->isDefaultValueAvailable()) { + $optionalArguments[] = new Twig_Node_Expression_Constant($callableParameter->getDefaultValue(), -1); + } elseif ($callableParameter->isOptional()) { + if (empty($parameters)) { + break; + } else { + $missingArguments[] = $name; + } + } else { + throw new Twig_Error_Syntax(sprintf('Value for argument "%s" is required for %s "%s".', $name, $callType, $callName), $this->getTemplateLine()); + } + } + + if ($isVariadic) { + $arbitraryArguments = new Twig_Node_Expression_Array(array(), -1); + foreach ($parameters as $key => $value) { + if (is_int($key)) { + $arbitraryArguments->addElement($value); + } else { + $arbitraryArguments->addElement($value, new Twig_Node_Expression_Constant($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 Twig_Node) { + $unknownParameter = $parameter; + break; + } + } + + throw new Twig_Error_Syntax(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()); + } + + return $arguments; + } + + protected function normalizeName($name) + { + return strtolower(preg_replace(array('/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'), array('\\1_\\2', '\\1_\\2'), $name)); + } + + private function getCallableParameters($callable, $isVariadic) + { + list($r) = $this->reflectCallable($callable); + if (null === $r) { + return array(); + } + + $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() && array() === $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 = array()".', $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 array(null, array()); + } + $r = new ReflectionMethod($callable[0], $callable[1]); + } elseif (is_object($callable) && !$callable instanceof Closure) { + $r = new ReflectionObject($callable); + $r = $r->getMethod('__invoke'); + $callable = array($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 array(null, array()); + } + $r = new ReflectionMethod($callable); + $callable = array($class, $method); + } else { + $r = new ReflectionFunction($callable); + } + + return $this->reflector = array($r, $callable); + } +} + +class_alias('Twig_Node_Expression_Call', 'Twig\Node\Expression\CallExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Conditional.php b/vendor/twig/twig/lib/Twig/Node/Expression/Conditional.php new file mode 100644 index 0000000..c339d77 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Conditional.php @@ -0,0 +1,33 @@ + $expr1, 'expr2' => $expr2, 'expr3' => $expr3), array(), $lineno); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('((') + ->subcompile($this->getNode('expr1')) + ->raw(') ? (') + ->subcompile($this->getNode('expr2')) + ->raw(') : (') + ->subcompile($this->getNode('expr3')) + ->raw('))') + ; + } +} + +class_alias('Twig_Node_Expression_Conditional', 'Twig\Node\Expression\ConditionalExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Constant.php b/vendor/twig/twig/lib/Twig/Node/Expression/Constant.php new file mode 100644 index 0000000..bf4d031 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Constant.php @@ -0,0 +1,25 @@ + $value), $lineno); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->repr($this->getAttribute('value')); + } +} + +class_alias('Twig_Node_Expression_Constant', 'Twig\Node\Expression\ConstantExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/ExtensionReference.php b/vendor/twig/twig/lib/Twig/Node/Expression/ExtensionReference.php new file mode 100644 index 0000000..114b5cd --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/ExtensionReference.php @@ -0,0 +1,32 @@ + + * + * @deprecated since 1.23 and will be removed in 2.0. + */ +class Twig_Node_Expression_ExtensionReference extends Twig_Node_Expression +{ + public function __construct($name, $lineno, $tag = null) + { + parent::__construct(array(), array('name' => $name), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->raw(sprintf("\$this->env->getExtension('%s')", $this->getAttribute('name'))); + } +} diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Filter.php b/vendor/twig/twig/lib/Twig/Node/Expression/Filter.php new file mode 100644 index 0000000..12da1d6 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Filter.php @@ -0,0 +1,41 @@ + $node, 'filter' => $filterName, 'arguments' => $arguments), array(), $lineno, $tag); + } + + public function compile(Twig_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 Twig_SimpleFilter) { + $this->setAttribute('callable', $filter->getCallable()); + } + if ($filter instanceof Twig_SimpleFilter) { + $this->setAttribute('is_variadic', $filter->isVariadic()); + } + + $this->compileCallable($compiler); + } +} + +class_alias('Twig_Node_Expression_Filter', 'Twig\Node\Expression\FilterExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Filter/Default.php b/vendor/twig/twig/lib/Twig/Node/Expression/Filter/Default.php new file mode 100644 index 0000000..d2e19d5 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Filter/Default.php @@ -0,0 +1,45 @@ + + * {{ var.foo|default('foo item on var is not defined') }} + * + * + * @author Fabien Potencier + */ +class Twig_Node_Expression_Filter_Default extends Twig_Node_Expression_Filter +{ + public function __construct(Twig_NodeInterface $node, Twig_Node_Expression_Constant $filterName, Twig_NodeInterface $arguments, $lineno, $tag = null) + { + $default = new Twig_Node_Expression_Filter($node, new Twig_Node_Expression_Constant('default', $node->getTemplateLine()), $arguments, $node->getTemplateLine()); + + if ('default' === $filterName->getAttribute('value') && ($node instanceof Twig_Node_Expression_Name || $node instanceof Twig_Node_Expression_GetAttr)) { + $test = new Twig_Node_Expression_Test_Defined(clone $node, 'defined', new Twig_Node(), $node->getTemplateLine()); + $false = count($arguments) ? $arguments->getNode(0) : new Twig_Node_Expression_Constant('', $node->getTemplateLine()); + + $node = new Twig_Node_Expression_Conditional($test, $default, $false, $node->getTemplateLine()); + } else { + $node = $default; + } + + parent::__construct($node, $filterName, $arguments, $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->subcompile($this->getNode('node')); + } +} + +class_alias('Twig_Node_Expression_Filter_Default', 'Twig\Node\Expression\Filter\DefaultFilter', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Function.php b/vendor/twig/twig/lib/Twig/Node/Expression/Function.php new file mode 100644 index 0000000..cdee7c9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Function.php @@ -0,0 +1,45 @@ + $arguments), array('name' => $name, 'is_defined_test' => false), $lineno); + } + + public function compile(Twig_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 Twig_SimpleFunction) { + $callable = $function->getCallable(); + if ('constant' === $name && $this->getAttribute('is_defined_test')) { + $callable = 'twig_constant_is_defined'; + } + + $this->setAttribute('callable', $callable); + } + if ($function instanceof Twig_SimpleFunction) { + $this->setAttribute('is_variadic', $function->isVariadic()); + } + + $this->compileCallable($compiler); + } +} + +class_alias('Twig_Node_Expression_Function', 'Twig\Node\Expression\FunctionExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/GetAttr.php b/vendor/twig/twig/lib/Twig/Node/Expression/GetAttr.php new file mode 100644 index 0000000..b7823ac --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/GetAttr.php @@ -0,0 +1,74 @@ + $node, 'attribute' => $attribute); + if (null !== $arguments) { + $nodes['arguments'] = $arguments; + } + + parent::__construct($nodes, array('type' => $type, 'is_defined_test' => false, 'ignore_strict_check' => false, 'disable_c_ext' => false), $lineno); + } + + public function compile(Twig_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 || Twig_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(', array()'); + } + } + + 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_GetAttr', 'Twig\Node\Expression\GetAttrExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/MethodCall.php b/vendor/twig/twig/lib/Twig/Node/Expression/MethodCall.php new file mode 100644 index 0000000..709016e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/MethodCall.php @@ -0,0 +1,43 @@ + $node, 'arguments' => $arguments), array('method' => $method, 'safe' => false), $lineno); + + if ($node instanceof Twig_Node_Expression_Name) { + $node->setAttribute('always_defined', true); + } + } + + public function compile(Twig_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_MethodCall', 'Twig\Node\Expression\MethodCallExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Name.php b/vendor/twig/twig/lib/Twig/Node/Expression/Name.php new file mode 100644 index 0000000..7d3d622 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Name.php @@ -0,0 +1,107 @@ + '$this', + '_context' => '$context', + '_charset' => '$this->env->getCharset()', + ); + + public function __construct($name, $lineno) + { + parent::__construct(array(), array('name' => $name, 'is_defined_test' => false, 'ignore_strict_check' => false, 'always_defined' => false), $lineno); + } + + public function compile(Twig_Compiler $compiler) + { + $name = $this->getAttribute('name'); + + $compiler->addDebugInfo($this); + + if ($this->getAttribute('is_defined_test')) { + if ($this->isSpecial()) { + $compiler->repr(true); + } 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_Name', 'Twig\Node\Expression\NameExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/NullCoalesce.php b/vendor/twig/twig/lib/Twig/Node/Expression/NullCoalesce.php new file mode 100644 index 0000000..eaafa4c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/NullCoalesce.php @@ -0,0 +1,48 @@ +getTemplateLine()), + new Twig_Node_Expression_Unary_Not(new Twig_Node_Expression_Test_Null($left, 'null', new Twig_Node(), $left->getTemplateLine()), $left->getTemplateLine()), + $left->getTemplateLine() + ); + + parent::__construct($test, $left, $right, $lineno); + } + + public function compile(Twig_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 Twig_Node_Expression_Name) { + $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_NullCoalesce', 'Twig\Node\Expression\NullCoalesceExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Parent.php b/vendor/twig/twig/lib/Twig/Node/Expression/Parent.php new file mode 100644 index 0000000..78692db --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Parent.php @@ -0,0 +1,44 @@ + + */ +class Twig_Node_Expression_Parent extends Twig_Node_Expression +{ + public function __construct($name, $lineno, $tag = null) + { + parent::__construct(array(), array('output' => false, 'name' => $name), $lineno, $tag); + } + + public function compile(Twig_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_Parent', 'Twig\Node\Expression\ParentExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/TempName.php b/vendor/twig/twig/lib/Twig/Node/Expression/TempName.php new file mode 100644 index 0000000..0a86e00 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/TempName.php @@ -0,0 +1,28 @@ + $name), $lineno); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('$_') + ->raw($this->getAttribute('name')) + ->raw('_') + ; + } +} + +class_alias('Twig_Node_Expression_TempName', 'Twig\Node\Expression\TempNameExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test.php new file mode 100644 index 0000000..4a369d6 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test.php @@ -0,0 +1,45 @@ + $node); + if (null !== $arguments) { + $nodes['arguments'] = $arguments; + } + + parent::__construct($nodes, array('name' => $name), $lineno); + } + + public function compile(Twig_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 Twig_SimpleTest) { + $this->setAttribute('arguments', $test->getArguments()); + } + if ($test instanceof Twig_TestCallableInterface || $test instanceof Twig_SimpleTest) { + $this->setAttribute('callable', $test->getCallable()); + } + if ($test instanceof Twig_SimpleTest) { + $this->setAttribute('is_variadic', $test->isVariadic()); + } + + $this->compileCallable($compiler); + } +} + +class_alias('Twig_Node_Expression_Test', 'Twig\Node\Expression\TestExpression', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test/Constant.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Constant.php new file mode 100644 index 0000000..a51a4ba --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Constant.php @@ -0,0 +1,48 @@ + + * {% if post.status is constant('Post::PUBLISHED') %} + * the status attribute is exactly the same as Post::PUBLISHED + * {% endif %} + * + * + * @author Fabien Potencier + */ +class Twig_Node_Expression_Test_Constant extends Twig_Node_Expression_Test +{ + public function compile(Twig_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_Constant', 'Twig\Node\Expression\Test\ConstantTest', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test/Defined.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Defined.php new file mode 100644 index 0000000..2136c39 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Defined.php @@ -0,0 +1,61 @@ + + * {# defined works with variable names and variable attributes #} + * {% if foo is defined %} + * {# ... #} + * {% endif %} + * + * + * @author Fabien Potencier + */ +class Twig_Node_Expression_Test_Defined extends Twig_Node_Expression_Test +{ + public function __construct(Twig_NodeInterface $node, $name, Twig_NodeInterface $arguments = null, $lineno) + { + if ($node instanceof Twig_Node_Expression_Name) { + $node->setAttribute('is_defined_test', true); + } elseif ($node instanceof Twig_Node_Expression_GetAttr) { + $node->setAttribute('is_defined_test', true); + $this->changeIgnoreStrictCheck($node); + } elseif ($node instanceof Twig_Node_Expression_BlockReference) { + $node->setAttribute('is_defined_test', true); + } elseif ($node instanceof Twig_Node_Expression_Function && 'constant' === $node->getAttribute('name')) { + $node->setAttribute('is_defined_test', true); + } elseif ($node instanceof Twig_Node_Expression_Constant || $node instanceof Twig_Node_Expression_Array) { + $node = new Twig_Node_Expression_Constant(true, $node->getTemplateLine()); + } else { + throw new Twig_Error_Syntax('The "defined" test only works with simple variables.', $this->getTemplateLine()); + } + + parent::__construct($node, $name, $arguments, $lineno); + } + + protected function changeIgnoreStrictCheck(Twig_Node_Expression_GetAttr $node) + { + $node->setAttribute('ignore_strict_check', true); + + if ($node->getNode('node') instanceof Twig_Node_Expression_GetAttr) { + $this->changeIgnoreStrictCheck($node->getNode('node')); + } + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->subcompile($this->getNode('node')); + } +} + +class_alias('Twig_Node_Expression_Test_Defined', 'Twig\Node\Expression\Test\DefinedTest', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test/Divisibleby.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Divisibleby.php new file mode 100644 index 0000000..a5d7196 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Divisibleby.php @@ -0,0 +1,35 @@ + + * {% if loop.index is divisible by(3) %} + * + * + * @author Fabien Potencier + */ +class Twig_Node_Expression_Test_Divisibleby extends Twig_Node_Expression_Test +{ + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('(0 == ') + ->subcompile($this->getNode('node')) + ->raw(' % ') + ->subcompile($this->getNode('arguments')->getNode(0)) + ->raw(')') + ; + } +} + +class_alias('Twig_Node_Expression_Test_Divisibleby', 'Twig\Node\Expression\Test\DivisiblebyTest', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test/Even.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Even.php new file mode 100644 index 0000000..7e198be --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Even.php @@ -0,0 +1,34 @@ + + * {{ var is even }} + * + * + * @author Fabien Potencier + */ +class Twig_Node_Expression_Test_Even extends Twig_Node_Expression_Test +{ + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('(') + ->subcompile($this->getNode('node')) + ->raw(' % 2 == 0') + ->raw(')') + ; + } +} + +class_alias('Twig_Node_Expression_Test_Even', 'Twig\Node\Expression\Test\EvenTest', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test/Null.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Null.php new file mode 100644 index 0000000..3746e4c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Null.php @@ -0,0 +1,33 @@ + + * {{ var is none }} + * + * + * @author Fabien Potencier + */ +class Twig_Node_Expression_Test_Null extends Twig_Node_Expression_Test +{ + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('(null === ') + ->subcompile($this->getNode('node')) + ->raw(')') + ; + } +} + +class_alias('Twig_Node_Expression_Test_Null', 'Twig\Node\Expression\Test\NullTest', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test/Odd.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Odd.php new file mode 100644 index 0000000..0c6c099 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Odd.php @@ -0,0 +1,34 @@ + + * {{ var is odd }} + * + * + * @author Fabien Potencier + */ +class Twig_Node_Expression_Test_Odd extends Twig_Node_Expression_Test +{ + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('(') + ->subcompile($this->getNode('node')) + ->raw(' % 2 == 1') + ->raw(')') + ; + } +} + +class_alias('Twig_Node_Expression_Test_Odd', 'Twig\Node\Expression\Test\OddTest', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Test/Sameas.php b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Sameas.php new file mode 100644 index 0000000..e95ff1f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Test/Sameas.php @@ -0,0 +1,31 @@ + + */ +class Twig_Node_Expression_Test_Sameas extends Twig_Node_Expression_Test +{ + public function compile(Twig_Compiler $compiler) + { + $compiler + ->raw('(') + ->subcompile($this->getNode('node')) + ->raw(' === ') + ->subcompile($this->getNode('arguments')->getNode(0)) + ->raw(')') + ; + } +} + +class_alias('Twig_Node_Expression_Test_Sameas', 'Twig\Node\Expression\Test\SameasTest', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Unary.php b/vendor/twig/twig/lib/Twig/Node/Expression/Unary.php new file mode 100644 index 0000000..5804485 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Unary.php @@ -0,0 +1,29 @@ + $node), array(), $lineno); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->raw(' '); + $this->operator($compiler); + $compiler->subcompile($this->getNode('node')); + } + + abstract public function operator(Twig_Compiler $compiler); +} + +class_alias('Twig_Node_Expression_Unary', 'Twig\Node\Expression\Unary\AbstractUnary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Neg.php b/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Neg.php new file mode 100644 index 0000000..039d933 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Neg.php @@ -0,0 +1,20 @@ +raw('-'); + } +} + +class_alias('Twig_Node_Expression_Unary_Neg', 'Twig\Node\Expression\Unary\NegUnary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Not.php b/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Not.php new file mode 100644 index 0000000..a0860b1 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Not.php @@ -0,0 +1,20 @@ +raw('!'); + } +} + +class_alias('Twig_Node_Expression_Unary_Not', 'Twig\Node\Expression\Unary\NotUnary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Pos.php b/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Pos.php new file mode 100644 index 0000000..eeff545 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Expression/Unary/Pos.php @@ -0,0 +1,20 @@ +raw('+'); + } +} + +class_alias('Twig_Node_Expression_Unary_Pos', 'Twig\Node\Expression\Unary\PosUnary', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Flush.php b/vendor/twig/twig/lib/Twig/Node/Flush.php new file mode 100644 index 0000000..fcc461a --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Flush.php @@ -0,0 +1,33 @@ + + */ +class Twig_Node_Flush extends Twig_Node +{ + public function __construct($lineno, $tag) + { + parent::__construct(array(), array(), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write("flush();\n") + ; + } +} + +class_alias('Twig_Node_Flush', 'Twig\Node\FlushNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/For.php b/vendor/twig/twig/lib/Twig/Node/For.php new file mode 100644 index 0000000..914b70c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/For.php @@ -0,0 +1,113 @@ + + */ +class Twig_Node_For extends Twig_Node +{ + protected $loop; + + public function __construct(Twig_Node_Expression_AssignName $keyTarget, Twig_Node_Expression_AssignName $valueTarget, Twig_Node_Expression $seq, Twig_Node_Expression $ifexpr = null, Twig_NodeInterface $body, Twig_NodeInterface $else = null, $lineno, $tag = null) + { + $body = new Twig_Node(array($body, $this->loop = new Twig_Node_ForLoop($lineno, $tag))); + + if (null !== $ifexpr) { + $body = new Twig_Node_If(new Twig_Node(array($ifexpr, $body)), null, $lineno, $tag); + } + + $nodes = array('key_target' => $keyTarget, 'value_target' => $valueTarget, 'seq' => $seq, 'body' => $body); + if (null !== $else) { + $nodes['else'] = $else; + } + + parent::__construct($nodes, array('with_loop' => true, 'ifexpr' => null !== $ifexpr), $lineno, $tag); + } + + public function compile(Twig_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'] = array(\n") + ->write(" 'parent' => \$context['_parent'],\n") + ->write(" 'index0' => 0,\n") + ->write(" 'index' => 1,\n") + ->write(" 'first' => true,\n") + ->write(");\n") + ; + + if (!$this->getAttribute('ifexpr')) { + $compiler + ->write("if (is_array(\$context['_seq']) || (is_object(\$context['_seq']) && \$context['_seq'] instanceof Countable)) {\n") + ->indent() + ->write("\$length = count(\$context['_seq']);\n") + ->write("\$context['loop']['revindex0'] = \$length - 1;\n") + ->write("\$context['loop']['revindex'] = \$length;\n") + ->write("\$context['loop']['length'] = \$length;\n") + ->write("\$context['loop']['last'] = 1 === \$length;\n") + ->outdent() + ->write("}\n") + ; + } + } + + $this->loop->setAttribute('else', $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_For', 'Twig\Node\ForNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/ForLoop.php b/vendor/twig/twig/lib/Twig/Node/ForLoop.php new file mode 100644 index 0000000..06477cf --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/ForLoop.php @@ -0,0 +1,52 @@ + + */ +class Twig_Node_ForLoop extends Twig_Node +{ + public function __construct($lineno, $tag = null) + { + parent::__construct(array(), array('with_loop' => false, 'ifexpr' => false, 'else' => false), $lineno, $tag); + } + + public function compile(Twig_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_ForLoop', 'Twig\Node\ForLoopNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/If.php b/vendor/twig/twig/lib/Twig/Node/If.php new file mode 100644 index 0000000..d82edec --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/If.php @@ -0,0 +1,68 @@ + + */ +class Twig_Node_If extends Twig_Node +{ + public function __construct(Twig_NodeInterface $tests, Twig_NodeInterface $else = null, $lineno, $tag = null) + { + $nodes = array('tests' => $tests); + if (null !== $else) { + $nodes['else'] = $else; + } + + parent::__construct($nodes, array(), $lineno, $tag); + } + + public function compile(Twig_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_If', 'Twig\Node\IfNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Import.php b/vendor/twig/twig/lib/Twig/Node/Import.php new file mode 100644 index 0000000..c77e320 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Import.php @@ -0,0 +1,51 @@ + + */ +class Twig_Node_Import extends Twig_Node +{ + public function __construct(Twig_Node_Expression $expr, Twig_Node_Expression $var, $lineno, $tag = null) + { + parent::__construct(array('expr' => $expr, 'var' => $var), array(), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('') + ->subcompile($this->getNode('var')) + ->raw(' = ') + ; + + if ($this->getNode('expr') instanceof Twig_Node_Expression_Name && '_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(')') + ; + } + + $compiler->raw(";\n"); + } +} + +class_alias('Twig_Node_Import', 'Twig\Node\ImportNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Include.php b/vendor/twig/twig/lib/Twig/Node/Include.php new file mode 100644 index 0000000..2a5114c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Include.php @@ -0,0 +1,90 @@ + + */ +class Twig_Node_Include extends Twig_Node implements Twig_NodeOutputInterface +{ + public function __construct(Twig_Node_Expression $expr, Twig_Node_Expression $variables = null, $only = false, $ignoreMissing = false, $lineno, $tag = null) + { + $nodes = array('expr' => $expr); + if (null !== $variables) { + $nodes['variables'] = $variables; + } + + parent::__construct($nodes, array('only' => (bool) $only, 'ignore_missing' => (bool) $ignoreMissing), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + if ($this->getAttribute('ignore_missing')) { + $compiler + ->write("try {\n") + ->indent() + ; + } + + $this->addGetTemplate($compiler); + + $compiler->raw('->display('); + + $this->addTemplateArguments($compiler); + + $compiler->raw(");\n"); + + if ($this->getAttribute('ignore_missing')) { + $compiler + ->outdent() + ->write("} catch (Twig_Error_Loader \$e) {\n") + ->indent() + ->write("// ignore missing template\n") + ->outdent() + ->write("}\n\n") + ; + } + } + + protected function addGetTemplate(Twig_Compiler $compiler) + { + $compiler + ->write('$this->loadTemplate(') + ->subcompile($this->getNode('expr')) + ->raw(', ') + ->repr($this->getTemplateName()) + ->raw(', ') + ->repr($this->getTemplateLine()) + ->raw(')') + ; + } + + protected function addTemplateArguments(Twig_Compiler $compiler) + { + if (!$this->hasNode('variables')) { + $compiler->raw(false === $this->getAttribute('only') ? '$context' : 'array()'); + } elseif (false === $this->getAttribute('only')) { + $compiler + ->raw('array_merge($context, ') + ->subcompile($this->getNode('variables')) + ->raw(')') + ; + } else { + $compiler->subcompile($this->getNode('variables')); + } + } +} + +class_alias('Twig_Node_Include', 'Twig\Node\IncludeNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Macro.php b/vendor/twig/twig/lib/Twig/Node/Macro.php new file mode 100644 index 0000000..3cf5497 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Macro.php @@ -0,0 +1,125 @@ + + */ +class Twig_Node_Macro extends Twig_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 Twig_Error_Syntax(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()); + } + } + + parent::__construct(array('body' => $body, 'arguments' => $arguments), array('name' => $name), $lineno, $tag); + } + + public function compile(Twig_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(array(\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(") : array(),\n") + ; + } + + $compiler + ->outdent() + ->write("));\n\n") + ->write("\$blocks = array();\n\n") + ->write("ob_start();\n") + ->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 Twig_Markup(\$tmp, \$this->env->getCharset());\n") + ->outdent() + ->write("}\n\n") + ; + } +} + +class_alias('Twig_Node_Macro', 'Twig\Node\MacroNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Module.php b/vendor/twig/twig/lib/Twig/Node/Module.php new file mode 100644 index 0000000..5cd8d05 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Module.php @@ -0,0 +1,461 @@ + + */ +class Twig_Node_Module extends Twig_Node +{ + private $source; + + public function __construct(Twig_NodeInterface $body, Twig_Node_Expression $parent = null, Twig_NodeInterface $blocks, Twig_NodeInterface $macros, Twig_NodeInterface $traits, $embeddedTemplates, $name, $source = '') + { + if (!$name instanceof Twig_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); + $this->source = new Twig_Source($source, $name); + } else { + $this->source = $name; + } + + $nodes = array( + 'body' => $body, + 'blocks' => $blocks, + 'macros' => $macros, + 'traits' => $traits, + 'display_start' => new Twig_Node(), + 'display_end' => new Twig_Node(), + 'constructor_start' => new Twig_Node(), + 'constructor_end' => new Twig_Node(), + 'class_end' => new Twig_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, array( + // source to be remove in 2.0 + 'source' => $this->source->getCode(), + // filename to be remove in 2.0 (use getTemplateName() instead) + 'filename' => $this->source->getName(), + 'index' => null, + 'embedded_templates' => $embeddedTemplates, + ), 1); + + // populate the template name of all node children + $this->setTemplateName($this->source->getName()); + } + + public function setIndex($index) + { + $this->setAttribute('index', $index); + } + + public function compile(Twig_Compiler $compiler) + { + $this->compileTemplate($compiler); + + foreach ($this->getAttribute('embedded_templates') as $template) { + $compiler->subcompile($template); + } + } + + protected function compileTemplate(Twig_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 Twig_Node_Expression_Constant + || 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(Twig_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 Twig_Node_Expression_Constant) { + $compiler->subcompile($parent); + } else { + $compiler + ->raw('$this->loadTemplate(') + ->subcompile($parent) + ->raw(', ') + ->repr($this->source->getName()) + ->raw(', ') + ->repr($parent->getTemplateLine()) + ->raw(')') + ; + } + + $compiler + ->raw(";\n") + ->outdent() + ->write("}\n\n") + ; + } + + protected function compileClassHeader(Twig_Compiler $compiler) + { + $compiler + ->write("\n\n") + // if the template name contains */, add a blank to avoid a PHP parse error + ->write('/* '.str_replace('*/', '* /', $this->source->getName())." */\n") + ->write('class '.$compiler->getEnvironment()->getTemplateClass($this->source->getName(), $this->getAttribute('index'))) + ->raw(sprintf(" extends %s\n", $compiler->getEnvironment()->getBaseTemplateClass())) + ->write("{\n") + ->indent() + ; + } + + protected function compileConstructor(Twig_Compiler $compiler) + { + $compiler + ->write("public function __construct(Twig_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"); + } elseif (($parent = $this->getNode('parent')) && $parent instanceof Twig_Node_Expression_Constant) { + $compiler + ->addDebugInfo($parent) + ->write('$this->parent = $this->loadTemplate(') + ->subcompile($parent) + ->raw(', ') + ->repr($this->source->getName()) + ->raw(', ') + ->repr($parent->getTemplateLine()) + ->raw(");\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)); + + $compiler + ->addDebugInfo($trait->getNode('template')) + ->write(sprintf("if (!\$_trait_%s->isTraitable()) {\n", $i)) + ->indent() + ->write("throw new Twig_Error_Runtime('Template \"'.") + ->subcompile($trait->getNode('template')) + ->raw(".'\" cannot be used as a trait.');\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 Twig_Error_Runtime(sprintf('Block ") + ->string($key) + ->raw(' is not defined in trait ') + ->subcompile($trait->getNode('template')) + ->raw(".'));\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("array(\n") + ; + } else { + $compiler + ->write("\$this->blocks = array(\n") + ; + } + + // blocks + $compiler + ->indent() + ; + + foreach ($this->getNode('blocks') as $name => $node) { + $compiler + ->write(sprintf("'%s' => array(\$this, 'block_%s'),\n", $name, $name)) + ; + } + + if ($countTraits) { + $compiler + ->outdent() + ->write(")\n") + ; + } + + $compiler + ->outdent() + ->write(");\n") + ->outdent() + ->subcompile($this->getNode('constructor_end')) + ->write("}\n\n") + ; + } + + protected function compileDisplay(Twig_Compiler $compiler) + { + $compiler + ->write("protected function doDisplay(array \$context, array \$blocks = array())\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 Twig_Node_Expression_Constant) { + $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(Twig_Compiler $compiler) + { + $compiler + ->subcompile($this->getNode('class_end')) + ->outdent() + ->write("}\n") + ; + } + + protected function compileMacros(Twig_Compiler $compiler) + { + $compiler->subcompile($this->getNode('macros')); + } + + protected function compileGetTemplateName(Twig_Compiler $compiler) + { + $compiler + ->write("public function getTemplateName()\n", "{\n") + ->indent() + ->write('return ') + ->repr($this->source->getName()) + ->raw(";\n") + ->outdent() + ->write("}\n\n") + ; + } + + protected function compileIsTraitable(Twig_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 Twig_Node_Body) { + $nodes = $this->getNode('body')->getNode(0); + } else { + $nodes = $this->getNode('body'); + } + + if (!count($nodes)) { + $nodes = new Twig_Node(array($nodes)); + } + + foreach ($nodes as $node) { + if (!count($node)) { + continue; + } + + if ($node instanceof Twig_Node_Text && ctype_space($node->getAttribute('data'))) { + continue; + } + + if ($node instanceof Twig_Node_BlockReference) { + 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(Twig_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(Twig_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(Twig_Compiler $compiler) + { + $compiler + ->write("public function getSourceContext()\n", "{\n") + ->indent() + ->write('return new Twig_Source(') + ->string($compiler->getEnvironment()->isDebug() ? $this->source->getCode() : '') + ->raw(', ') + ->string($this->source->getName()) + ->raw(', ') + ->string($this->source->getPath()) + ->raw(");\n") + ->outdent() + ->write("}\n") + ; + } + + protected function compileLoadTemplate(Twig_Compiler $compiler, $node, $var) + { + if ($node instanceof Twig_Node_Expression_Constant) { + $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_Module', 'Twig\Node\ModuleNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Print.php b/vendor/twig/twig/lib/Twig/Node/Print.php new file mode 100644 index 0000000..374db89 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Print.php @@ -0,0 +1,36 @@ + + */ +class Twig_Node_Print extends Twig_Node implements Twig_NodeOutputInterface +{ + public function __construct(Twig_Node_Expression $expr, $lineno, $tag = null) + { + parent::__construct(array('expr' => $expr), array(), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('echo ') + ->subcompile($this->getNode('expr')) + ->raw(";\n") + ; + } +} + +class_alias('Twig_Node_Print', 'Twig\Node\PrintNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Sandbox.php b/vendor/twig/twig/lib/Twig/Node/Sandbox.php new file mode 100644 index 0000000..44b30ab --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Sandbox.php @@ -0,0 +1,44 @@ + + */ +class Twig_Node_Sandbox extends Twig_Node +{ + public function __construct(Twig_NodeInterface $body, $lineno, $tag = null) + { + parent::__construct(array('body' => $body), array(), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write("\$sandbox = \$this->env->getExtension('Twig_Extension_Sandbox');\n") + ->write("if (!\$alreadySandboxed = \$sandbox->isSandboxed()) {\n") + ->indent() + ->write("\$sandbox->enableSandbox();\n") + ->outdent() + ->write("}\n") + ->subcompile($this->getNode('body')) + ->write("if (!\$alreadySandboxed) {\n") + ->indent() + ->write("\$sandbox->disableSandbox();\n") + ->outdent() + ->write("}\n") + ; + } +} + +class_alias('Twig_Node_Sandbox', 'Twig\Node\SandboxNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/SandboxedPrint.php b/vendor/twig/twig/lib/Twig/Node/SandboxedPrint.php new file mode 100644 index 0000000..a08f21f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/SandboxedPrint.php @@ -0,0 +1,51 @@ + + */ +class Twig_Node_SandboxedPrint extends Twig_Node_Print +{ + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('echo $this->env->getExtension(\'Twig_Extension_Sandbox\')->ensureToStringAllowed(') + ->subcompile($this->getNode('expr')) + ->raw(");\n") + ; + } + + /** + * Removes node filters. + * + * This is mostly needed when another visitor adds filters (like the escaper one). + * + * @return Twig_Node + */ + protected function removeNodeFilter(Twig_Node $node) + { + if ($node instanceof Twig_Node_Expression_Filter) { + return $this->removeNodeFilter($node->getNode('node')); + } + + return $node; + } +} + +class_alias('Twig_Node_SandboxedPrint', 'Twig\Node\SandboxedPrintNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Set.php b/vendor/twig/twig/lib/Twig/Node/Set.php new file mode 100644 index 0000000..6c6743e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Set.php @@ -0,0 +1,98 @@ + + */ +class Twig_Node_Set extends Twig_Node implements Twig_NodeCaptureInterface +{ + public function __construct($capture, Twig_NodeInterface $names, Twig_NodeInterface $values, $lineno, $tag = null) + { + parent::__construct(array('names' => $names, 'values' => $values), array('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 Twig_Node_Text) { + $this->setNode('values', new Twig_Node_Expression_Constant($values->getAttribute('data'), $values->getTemplateLine())); + $this->setAttribute('capture', false); + } + } + } + + public function compile(Twig_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')) { + $compiler + ->write("ob_start();\n") + ->subcompile($this->getNode('values')) + ; + } + + $compiler->subcompile($this->getNode('names'), false); + + if ($this->getAttribute('capture')) { + $compiler->raw(" = ('' === \$tmp = ob_get_clean()) ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset())"); + } + } + + if (!$this->getAttribute('capture')) { + $compiler->raw(' = '); + + if (count($this->getNode('names')) > 1) { + $compiler->write('array('); + 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 Twig_Markup(\$tmp, \$this->env->getCharset())") + ; + } else { + $compiler->subcompile($this->getNode('values')); + } + } + } + + $compiler->raw(";\n"); + } +} + +class_alias('Twig_Node_Set', 'Twig\Node\SetNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/SetTemp.php b/vendor/twig/twig/lib/Twig/Node/SetTemp.php new file mode 100644 index 0000000..996fdcd --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/SetTemp.php @@ -0,0 +1,40 @@ + $name), $lineno); + } + + public function compile(Twig_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_SetTemp', 'Twig\Node\SetTempNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Spaceless.php b/vendor/twig/twig/lib/Twig/Node/Spaceless.php new file mode 100644 index 0000000..76f90cd --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Spaceless.php @@ -0,0 +1,37 @@ + + */ +class Twig_Node_Spaceless extends Twig_Node +{ + public function __construct(Twig_NodeInterface $body, $lineno, $tag = 'spaceless') + { + parent::__construct(array('body' => $body), array(), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write("ob_start();\n") + ->subcompile($this->getNode('body')) + ->write("echo trim(preg_replace('/>\s+<', ob_get_clean()));\n") + ; + } +} + +class_alias('Twig_Node_Spaceless', 'Twig\Node\SpacelessNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/Text.php b/vendor/twig/twig/lib/Twig/Node/Text.php new file mode 100644 index 0000000..f4577fe --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/Text.php @@ -0,0 +1,36 @@ + + */ +class Twig_Node_Text extends Twig_Node implements Twig_NodeOutputInterface +{ + public function __construct($data, $lineno) + { + parent::__construct(array(), array('data' => $data), $lineno); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler + ->addDebugInfo($this) + ->write('echo ') + ->string($this->getAttribute('data')) + ->raw(";\n") + ; + } +} + +class_alias('Twig_Node_Text', 'Twig\Node\TextNode', false); diff --git a/vendor/twig/twig/lib/Twig/Node/With.php b/vendor/twig/twig/lib/Twig/Node/With.php new file mode 100644 index 0000000..2ab0ea5 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Node/With.php @@ -0,0 +1,64 @@ + + */ +class Twig_Node_With extends Twig_Node +{ + public function __construct(Twig_Node $body, Twig_Node $variables = null, $only = false, $lineno, $tag = null) + { + $nodes = array('body' => $body); + if (null !== $variables) { + $nodes['variables'] = $variables; + } + + parent::__construct($nodes, array('only' => (bool) $only), $lineno, $tag); + } + + public function compile(Twig_Compiler $compiler) + { + $compiler->addDebugInfo($this); + + if ($this->hasNode('variables')) { + $varsName = $compiler->getVarName(); + $compiler + ->write(sprintf('$%s = ', $varsName)) + ->subcompile($this->getNode('variables')) + ->raw(";\n") + ->write(sprintf("if (!is_array(\$%s)) {\n", $varsName)) + ->indent() + ->write("throw new Twig_Error_Runtime('Variables passed to the \"with\" tag must be a hash.');\n") + ->outdent() + ->write("}\n") + ; + + if ($this->getAttribute('only')) { + $compiler->write("\$context = array('_parent' => \$context);\n"); + } else { + $compiler->write("\$context['_parent'] = \$context;\n"); + } + + $compiler->write(sprintf("\$context = 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_With', 'Twig\Node\WithNode', false); diff --git a/vendor/twig/twig/lib/Twig/NodeCaptureInterface.php b/vendor/twig/twig/lib/Twig/NodeCaptureInterface.php new file mode 100644 index 0000000..6638834 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeCaptureInterface.php @@ -0,0 +1,21 @@ + + */ +interface Twig_NodeCaptureInterface +{ +} + +class_alias('Twig_NodeCaptureInterface', 'Twig\Node\NodeCaptureInterface', false); diff --git a/vendor/twig/twig/lib/Twig/NodeInterface.php b/vendor/twig/twig/lib/Twig/NodeInterface.php new file mode 100644 index 0000000..78e758b --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeInterface.php @@ -0,0 +1,32 @@ + + * + * @deprecated since 1.12 (to be removed in 3.0) + */ +interface Twig_NodeInterface extends Countable, IteratorAggregate +{ + /** + * Compiles the node to PHP. + */ + public function compile(Twig_Compiler $compiler); + + /** + * @deprecated since 1.27 (to be removed in 2.0) + */ + public function getLine(); + + public function getNodeTag(); +} diff --git a/vendor/twig/twig/lib/Twig/NodeOutputInterface.php b/vendor/twig/twig/lib/Twig/NodeOutputInterface.php new file mode 100644 index 0000000..5a8eaa9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeOutputInterface.php @@ -0,0 +1,21 @@ + + */ +interface Twig_NodeOutputInterface +{ +} + +class_alias('Twig_NodeOutputInterface', 'Twig\Node\NodeOutputInterface', false); diff --git a/vendor/twig/twig/lib/Twig/NodeTraverser.php b/vendor/twig/twig/lib/Twig/NodeTraverser.php new file mode 100644 index 0000000..f00a0bf --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeTraverser.php @@ -0,0 +1,86 @@ + + */ +class Twig_NodeTraverser +{ + protected $env; + protected $visitors = array(); + + /** + * @param Twig_Environment $env + * @param Twig_NodeVisitorInterface[] $visitors + */ + public function __construct(Twig_Environment $env, array $visitors = array()) + { + $this->env = $env; + foreach ($visitors as $visitor) { + $this->addVisitor($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 + */ + public function traverse(Twig_NodeInterface $node) + { + ksort($this->visitors); + foreach ($this->visitors as $visitors) { + foreach ($visitors as $visitor) { + $node = $this->traverseForVisitor($visitor, $node); + } + } + + return $node; + } + + protected function traverseForVisitor(Twig_NodeVisitorInterface $visitor, Twig_NodeInterface $node = null) + { + if (null === $node) { + return; + } + + $node = $visitor->enterNode($node, $this->env); + + foreach ($node as $k => $n) { + if (false !== $m = $this->traverseForVisitor($visitor, $n)) { + if ($m !== $n) { + $node->setNode($k, $m); + } + } else { + $node->removeNode($k); + } + } + + return $visitor->leaveNode($node, $this->env); + } +} + +class_alias('Twig_NodeTraverser', 'Twig\NodeTraverser', false); diff --git a/vendor/twig/twig/lib/Twig/NodeVisitor/Escaper.php b/vendor/twig/twig/lib/Twig/NodeVisitor/Escaper.php new file mode 100644 index 0000000..1a1ae66 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeVisitor/Escaper.php @@ -0,0 +1,154 @@ + + */ +class Twig_NodeVisitor_Escaper extends Twig_BaseNodeVisitor +{ + protected $statusStack = array(); + protected $blocks = array(); + protected $safeAnalysis; + protected $traverser; + protected $defaultStrategy = false; + protected $safeVars = array(); + + public function __construct() + { + $this->safeAnalysis = new Twig_NodeVisitor_SafeAnalysis(); + } + + protected function doEnterNode(Twig_Node $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Module) { + if ($env->hasExtension('Twig_Extension_Escaper') && $defaultStrategy = $env->getExtension('Twig_Extension_Escaper')->getDefaultStrategy($node->getTemplateName())) { + $this->defaultStrategy = $defaultStrategy; + } + $this->safeVars = array(); + $this->blocks = array(); + } elseif ($node instanceof Twig_Node_AutoEscape) { + $this->statusStack[] = $node->getAttribute('value'); + } elseif ($node instanceof Twig_Node_Block) { + $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env); + } elseif ($node instanceof Twig_Node_Import) { + $this->safeVars[] = $node->getNode('var')->getAttribute('name'); + } + + return $node; + } + + protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Module) { + $this->defaultStrategy = false; + $this->safeVars = array(); + $this->blocks = array(); + } elseif ($node instanceof Twig_Node_Expression_Filter) { + return $this->preEscapeFilterNode($node, $env); + } elseif ($node instanceof Twig_Node_Print) { + return $this->escapePrintNode($node, $env, $this->needEscaping($env)); + } + + if ($node instanceof Twig_Node_AutoEscape || $node instanceof Twig_Node_Block) { + array_pop($this->statusStack); + } elseif ($node instanceof Twig_Node_BlockReference) { + $this->blocks[$node->getAttribute('name')] = $this->needEscaping($env); + } + + return $node; + } + + protected function escapePrintNode(Twig_Node_Print $node, Twig_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(Twig_Node_Expression_Filter $filter, Twig_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 Twig_NodeTraverser($env, array($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(Twig_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 Twig_Node_Expression_Constant('escape', $line); + $args = new Twig_Node(array(new Twig_Node_Expression_Constant((string) $type, $line), new Twig_Node_Expression_Constant(null, $line), new Twig_Node_Expression_Constant(true, $line))); + + return new Twig_Node_Expression_Filter($node, $name, $args, $line); + } + + public function getPriority() + { + return 0; + } +} + +class_alias('Twig_NodeVisitor_Escaper', 'Twig\NodeVisitor\EscaperNodeVisitor', false); diff --git a/vendor/twig/twig/lib/Twig/NodeVisitor/Optimizer.php b/vendor/twig/twig/lib/Twig/NodeVisitor/Optimizer.php new file mode 100644 index 0000000..c55e40f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeVisitor/Optimizer.php @@ -0,0 +1,253 @@ + + */ +class Twig_NodeVisitor_Optimizer extends Twig_BaseNodeVisitor +{ + const OPTIMIZE_ALL = -1; + const OPTIMIZE_NONE = 0; + const OPTIMIZE_FOR = 2; + const OPTIMIZE_RAW_FILTER = 4; + const OPTIMIZE_VAR_ACCESS = 8; + + protected $loops = array(); + protected $loopsTargets = array(); + protected $optimizers; + protected $prependedNodes = array(); + 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(Twig_Node $node, Twig_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_Sandbox')) { + if ($this->inABody) { + if (!$node instanceof Twig_Node_Expression) { + if ('Twig_Node' !== get_class($node)) { + array_unshift($this->prependedNodes, array()); + } + } else { + $node = $this->optimizeVariables($node, $env); + } + } elseif ($node instanceof Twig_Node_Body) { + $this->inABody = true; + } + } + + return $node; + } + + protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) + { + $expression = $node instanceof Twig_Node_Expression; + + 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_Sandbox')) { + if ($node instanceof Twig_Node_Body) { + $this->inABody = false; + } elseif ($this->inABody) { + if (!$expression && 'Twig_Node' !== get_class($node) && $prependedNodes = array_shift($this->prependedNodes)) { + $nodes = array(); + foreach (array_unique($prependedNodes) as $name) { + $nodes[] = new Twig_Node_SetTemp($name, $node->getTemplateLine()); + } + + $nodes[] = $node; + $node = new Twig_Node($nodes); + } + } + } + + return $node; + } + + protected function optimizeVariables(Twig_NodeInterface $node, Twig_Environment $env) + { + if ('Twig_Node_Expression_Name' === get_class($node) && $node->isSimple()) { + $this->prependedNodes[0][] = $node->getAttribute('name'); + + return new Twig_Node_Expression_TempName($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, Twig_Environment $env) + { + if (!$node instanceof Twig_Node_Print) { + return $node; + } + + $exprNode = $node->getNode('expr'); + if ( + $exprNode instanceof Twig_Node_Expression_BlockReference || + $exprNode instanceof Twig_Node_Expression_Parent + ) { + $exprNode->setAttribute('output', true); + + return $exprNode; + } + + return $node; + } + + /** + * Removes "raw" filters. + * + * @return Twig_NodeInterface + */ + protected function optimizeRawFilter(Twig_NodeInterface $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Expression_Filter && '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, Twig_Environment $env) + { + if ($node instanceof Twig_Node_For) { + // disable the loop variable by default + $node->setAttribute('with_loop', false); + array_unshift($this->loops, $node); + 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 Twig_Node_Expression_Name && 'loop' === $node->getAttribute('name')) { + $node->setAttribute('always_defined', true); + $this->addLoopToCurrent(); + } + + // optimize access to loop targets + elseif ($node instanceof Twig_Node_Expression_Name && in_array($node->getAttribute('name'), $this->loopsTargets)) { + $node->setAttribute('always_defined', true); + } + + // block reference + elseif ($node instanceof Twig_Node_BlockReference || $node instanceof Twig_Node_Expression_BlockReference) { + $this->addLoopToCurrent(); + } + + // include without the only attribute + elseif ($node instanceof Twig_Node_Include && !$node->getAttribute('only')) { + $this->addLoopToAll(); + } + + // include function without the with_context=false parameter + elseif ($node instanceof Twig_Node_Expression_Function + && '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 Twig_Node_Expression_GetAttr + && (!$node->getNode('attribute') instanceof Twig_Node_Expression_Constant + || 'parent' === $node->getNode('attribute')->getAttribute('value') + ) + && (true === $this->loops[0]->getAttribute('with_loop') + || ($node->getNode('node') instanceof Twig_Node_Expression_Name + && 'loop' === $node->getNode('node')->getAttribute('name') + ) + ) + ) { + $this->addLoopToAll(); + } + } + + /** + * Optimizes "for" tag by removing the "loop" variable creation whenever possible. + */ + protected function leaveOptimizeFor(Twig_NodeInterface $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_For) { + 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_Optimizer', 'Twig\NodeVisitor\OptimizerNodeVisitor', false); diff --git a/vendor/twig/twig/lib/Twig/NodeVisitor/SafeAnalysis.php b/vendor/twig/twig/lib/Twig/NodeVisitor/SafeAnalysis.php new file mode 100644 index 0000000..ca31c8f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeVisitor/SafeAnalysis.php @@ -0,0 +1,150 @@ +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][] = array( + 'key' => $node, + 'value' => $safe, + ); + } + + protected function doEnterNode(Twig_Node $node, Twig_Environment $env) + { + return $node; + } + + protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Expression_Constant) { + // constants are marked safe for all + $this->setSafe($node, array('all')); + } elseif ($node instanceof Twig_Node_Expression_BlockReference) { + // blocks are safe by definition + $this->setSafe($node, array('all')); + } elseif ($node instanceof Twig_Node_Expression_Parent) { + // parent block is safe by definition + $this->setSafe($node, array('all')); + } elseif ($node instanceof Twig_Node_Expression_Conditional) { + // 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 Twig_Node_Expression_Filter) { + // 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, array()); + } + } elseif ($node instanceof Twig_Node_Expression_Function) { + // 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, array()); + } + } elseif ($node instanceof Twig_Node_Expression_MethodCall) { + if ($node->getAttribute('safe')) { + $this->setSafe($node, array('all')); + } else { + $this->setSafe($node, array()); + } + } elseif ($node instanceof Twig_Node_Expression_GetAttr && $node->getNode('node') instanceof Twig_Node_Expression_Name) { + $name = $node->getNode('node')->getAttribute('name'); + // attributes on template instances are safe + if ('_self' == $name || in_array($name, $this->safeVars)) { + $this->setSafe($node, array('all')); + } else { + $this->setSafe($node, array()); + } + } else { + $this->setSafe($node, array()); + } + + return $node; + } + + protected function intersectSafe(array $a = null, array $b = null) + { + if (null === $a || null === $b) { + return array(); + } + + 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_SafeAnalysis', 'Twig\NodeVisitor\SafeAnalysisNodeVisitor', false); diff --git a/vendor/twig/twig/lib/Twig/NodeVisitor/Sandbox.php b/vendor/twig/twig/lib/Twig/NodeVisitor/Sandbox.php new file mode 100644 index 0000000..71aa4f0 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeVisitor/Sandbox.php @@ -0,0 +1,82 @@ + + */ +class Twig_NodeVisitor_Sandbox extends Twig_BaseNodeVisitor +{ + protected $inAModule = false; + protected $tags; + protected $filters; + protected $functions; + + protected function doEnterNode(Twig_Node $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Module) { + $this->inAModule = true; + $this->tags = array(); + $this->filters = array(); + $this->functions = array(); + + 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 Twig_Node_Expression_Filter && !isset($this->filters[$node->getNode('filter')->getAttribute('value')])) { + $this->filters[$node->getNode('filter')->getAttribute('value')] = $node; + } + + // look for functions + if ($node instanceof Twig_Node_Expression_Function && !isset($this->functions[$node->getAttribute('name')])) { + $this->functions[$node->getAttribute('name')] = $node; + } + + // the .. operator is equivalent to the range() function + if ($node instanceof Twig_Node_Expression_Binary_Range && !isset($this->functions['range'])) { + $this->functions['range'] = $node; + } + + // wrap print to check __toString() calls + if ($node instanceof Twig_Node_Print) { + return new Twig_Node_SandboxedPrint($node->getNode('expr'), $node->getTemplateLine(), $node->getNodeTag()); + } + } + + return $node; + } + + protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Module) { + $this->inAModule = false; + + $node->setNode('display_start', new Twig_Node(array(new Twig_Node_CheckSecurity($this->filters, $this->tags, $this->functions), $node->getNode('display_start')))); + } + + return $node; + } + + public function getPriority() + { + return 0; + } +} + +class_alias('Twig_NodeVisitor_Sandbox', 'Twig\NodeVisitor\SandboxNodeVisitor', false); diff --git a/vendor/twig/twig/lib/Twig/NodeVisitorInterface.php b/vendor/twig/twig/lib/Twig/NodeVisitorInterface.php new file mode 100644 index 0000000..1270a37 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/NodeVisitorInterface.php @@ -0,0 +1,45 @@ + + */ +interface Twig_NodeVisitorInterface +{ + /** + * Called before child nodes are visited. + * + * @return Twig_NodeInterface The modified node + */ + public function enterNode(Twig_NodeInterface $node, Twig_Environment $env); + + /** + * Called after child nodes are visited. + * + * @return Twig_NodeInterface|false The modified node or false if the node must be removed + */ + public function leaveNode(Twig_NodeInterface $node, Twig_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_NodeVisitorInterface', 'Twig\NodeVisitor\NodeVisitorInterface', false); +class_exists('Twig_Environment'); +class_exists('Twig_Node'); diff --git a/vendor/twig/twig/lib/Twig/Parser.php b/vendor/twig/twig/lib/Twig/Parser.php new file mode 100644 index 0000000..6de879a --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Parser.php @@ -0,0 +1,412 @@ + + */ +class Twig_Parser implements Twig_ParserInterface +{ + protected $stack = array(); + protected $stream; + protected $parent; + protected $handlers; + protected $visitors; + protected $expressionParser; + protected $blocks; + protected $blockStack; + protected $macros; + protected $env; + protected $reservedMacroNames; + protected $importedSymbols; + protected $traits; + protected $embeddedTemplates = array(); + private $varNameSalt = 0; + + public function __construct(Twig_Environment $env) + { + $this->env = $env; + } + + /** + * @deprecated since 1.27 (to be removed in 2.0) + */ + public function getEnvironment() + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED); + + return $this->env; + } + + public function getVarName() + { + return sprintf('__internal_%s', hash('sha256', __METHOD__.$this->stream->getSourceContext()->getCode().$this->varNameSalt++)); + } + + /** + * @deprecated since 1.27 (to be removed in 2.0). Use $parser->getStream()->getSourceContext()->getPath() instead. + */ + public function getFilename() + { + @trigger_error(sprintf('The "%s" method is deprecated since version 1.27 and will be removed in 2.0. Use $parser->getStream()->getSourceContext()->getPath() instead.', __METHOD__), E_USER_DEPRECATED); + + return $this->stream->getSourceContext()->getName(); + } + + 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 = array(); + foreach ($this as $k => $v) { + $vars[$k] = $v; + } + + unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames']); + $this->stack[] = $vars; + + // tag handlers + if (null === $this->handlers) { + $this->handlers = $this->env->getTokenParsers(); + $this->handlers->setParser($this); + } + + // node visitors + if (null === $this->visitors) { + $this->visitors = $this->env->getNodeVisitors(); + } + + if (null === $this->expressionParser) { + $this->expressionParser = new Twig_ExpressionParser($this, $this->env); + } + + $this->stream = $stream; + $this->parent = null; + $this->blocks = array(); + $this->macros = array(); + $this->traits = array(); + $this->blockStack = array(); + $this->importedSymbols = array(array()); + $this->embeddedTemplates = array(); + $this->varNameSalt = 0; + + try { + $body = $this->subparse($test, $dropNeedle); + + if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) { + $body = new Twig_Node(); + } + } catch (Twig_Error_Syntax $e) { + if (!$e->getSourceContext()) { + $e->setSourceContext($this->stream->getSourceContext()); + } + + if (!$e->getTemplateLine()) { + $e->setTemplateLine($this->stream->getCurrent()->getLine()); + } + + throw $e; + } + + $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 Twig_NodeTraverser($this->env, $this->visitors); + + $node = $traverser->traverse($node); + + // restore previous stack so previous parse() call can resume working + foreach (array_pop($this->stack) as $key => $val) { + $this->$key = $val; + } + + return $node; + } + + public function subparse($test, $dropNeedle = false) + { + $lineno = $this->getCurrentToken()->getLine(); + $rv = array(); + while (!$this->stream->isEOF()) { + switch ($this->getCurrentToken()->getType()) { + case Twig_Token::TEXT_TYPE: + $token = $this->stream->next(); + $rv[] = new Twig_Node_Text($token->getValue(), $token->getLine()); + break; + + case Twig_Token::VAR_START_TYPE: + $token = $this->stream->next(); + $expr = $this->expressionParser->parseExpression(); + $this->stream->expect(Twig_Token::VAR_END_TYPE); + $rv[] = new Twig_Node_Print($expr, $token->getLine()); + break; + + case Twig_Token::BLOCK_START_TYPE: + $this->stream->next(); + $token = $this->getCurrentToken(); + + if (Twig_Token::NAME_TYPE !== $token->getType()) { + 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 ($dropNeedle) { + $this->stream->next(); + } + + if (1 === count($rv)) { + return $rv[0]; + } + + return new Twig_Node($rv, array(), $lineno); + } + + $subparser = $this->handlers->getTokenParser($token->getValue()); + if (null === $subparser) { + if (null !== $test) { + $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 Twig_TokenParserInterface) { + $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno)); + } + } else { + $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())); + } + + throw $e; + } + + $this->stream->next(); + + $node = $subparser->parse($token); + if (null !== $node) { + $rv[] = $node; + } + break; + + default: + throw new Twig_Error_Syntax('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext()); + } + } + + if (1 === count($rv)) { + return $rv[0]; + } + + return new Twig_Node($rv, array(), $lineno); + } + + /** + * @deprecated since 1.27 (to be removed in 2.0) + */ + public function addHandler($name, $class) + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0.', E_USER_DEPRECATED); + + $this->handlers[$name] = $class; + } + + /** + * @deprecated since 1.27 (to be removed in 2.0) + */ + 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); + + $this->visitors[] = $visitor; + } + + public function getBlockStack() + { + return $this->blockStack; + } + + public function peekBlockStack() + { + return $this->blockStack[count($this->blockStack) - 1]; + } + + public function popBlockStack() + { + array_pop($this->blockStack); + } + + public function pushBlockStack($name) + { + $this->blockStack[] = $name; + } + + public function hasBlock($name) + { + return isset($this->blocks[$name]); + } + + public function getBlock($name) + { + return $this->blocks[$name]; + } + + public function setBlock($name, Twig_Node_Block $value) + { + $this->blocks[$name] = new Twig_Node_Body(array($value), array(), $value->getTemplateLine()); + } + + public function hasMacro($name) + { + return isset($this->macros[$name]); + } + + public function setMacro($name, Twig_Node_Macro $node) + { + if ($this->isReservedMacroName($name)) { + 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; + } + + public function isReservedMacroName($name) + { + if (null === $this->reservedMacroNames) { + $this->reservedMacroNames = array(); + $r = new ReflectionClass($this->env->getBaseTemplateClass()); + foreach ($r->getMethods() as $method) { + $methodName = strtolower($method->getName()); + + if ('get' === substr($methodName, 0, 3) && isset($methodName[3])) { + $this->reservedMacroNames[] = substr($methodName, 3); + } + } + } + + return in_array(strtolower($name), $this->reservedMacroNames); + } + + public function addTrait($trait) + { + $this->traits[] = $trait; + } + + public function hasTraits() + { + return count($this->traits) > 0; + } + + public function embedTemplate(Twig_Node_Module $template) + { + $template->setIndex(mt_rand()); + + $this->embeddedTemplates[] = $template; + } + + public function addImportedSymbol($type, $alias, $name = null, Twig_Node_Expression $node = null) + { + $this->importedSymbols[0][$type][$alias] = array('name' => $name, 'node' => $node); + } + + public function getImportedSymbol($type, $alias) + { + foreach ($this->importedSymbols as $functions) { + if (isset($functions[$type][$alias])) { + return $functions[$type][$alias]; + } + } + } + + public function isMainScope() + { + return 1 === count($this->importedSymbols); + } + + public function pushLocalScope() + { + array_unshift($this->importedSymbols, array()); + } + + public function popLocalScope() + { + array_shift($this->importedSymbols); + } + + /** + * @return Twig_ExpressionParser + */ + public function getExpressionParser() + { + return $this->expressionParser; + } + + public function getParent() + { + return $this->parent; + } + + public function setParent($parent) + { + $this->parent = $parent; + } + + /** + * @return Twig_TokenStream + */ + public function getStream() + { + return $this->stream; + } + + /** + * @return Twig_Token + */ + public function getCurrentToken() + { + return $this->stream->getCurrent(); + } + + protected function filterBodyNodes(Twig_NodeInterface $node) + { + // check that the body does not contain non-empty output nodes + if ( + ($node instanceof Twig_Node_Text && !ctype_space($node->getAttribute('data'))) + || + (!$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))) { + 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 Twig_Error_Syntax('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()); + } + + // bypass nodes that will "capture" the output + if ($node instanceof Twig_NodeCaptureInterface) { + return $node; + } + + if ($node instanceof Twig_NodeOutputInterface) { + return; + } + + foreach ($node as $k => $n) { + if (null !== $n && null === $this->filterBodyNodes($n)) { + $node->removeNode($k); + } + } + + return $node; + } +} + +class_alias('Twig_Parser', 'Twig\Parser', false); +class_exists('Twig_Node'); +class_exists('Twig_TokenStream'); diff --git a/vendor/twig/twig/lib/Twig/ParserInterface.php b/vendor/twig/twig/lib/Twig/ParserInterface.php new file mode 100644 index 0000000..85c6e67 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/ParserInterface.php @@ -0,0 +1,29 @@ + + * + * @deprecated since 1.12 (to be removed in 3.0) + */ +interface Twig_ParserInterface +{ + /** + * Converts a token stream to a node tree. + * + * @return Twig_Node_Module + * + * @throws Twig_Error_Syntax When the token stream is syntactically or semantically wrong + */ + public function parse(Twig_TokenStream $stream); +} diff --git a/vendor/twig/twig/lib/Twig/Profiler/Dumper/Base.php b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Base.php new file mode 100644 index 0000000..913afd4 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Base.php @@ -0,0 +1,62 @@ + + */ +abstract class Twig_Profiler_Dumper_Base +{ + private $root; + + public function dump(Twig_Profiler_Profile $profile) + { + return $this->dumpProfile($profile); + } + + abstract protected function formatTemplate(Twig_Profiler_Profile $profile, $prefix); + + abstract protected function formatNonTemplate(Twig_Profiler_Profile $profile, $prefix); + + abstract protected function formatTime(Twig_Profiler_Profile $profile, $percent); + + private function dumpProfile(Twig_Profiler_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_Base', 'Twig\Profiler\Dumper\BaseDumper', false); +class_exists('Twig_Profiler_Profile'); diff --git a/vendor/twig/twig/lib/Twig/Profiler/Dumper/Blackfire.php b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Blackfire.php new file mode 100644 index 0000000..7a33baf --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Blackfire.php @@ -0,0 +1,72 @@ + + * + * @final + */ +class Twig_Profiler_Dumper_Blackfire +{ + public function dump(Twig_Profiler_Profile $profile) + { + $data = array(); + $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, Twig_Profiler_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, Twig_Profiler_Profile $profile, &$data) + { + if (isset($data[$edge])) { + $data[$edge]['ct'] += 1; + $data[$edge]['wt'] += floor($profile->getDuration() * 1000000); + $data[$edge]['mu'] += $profile->getMemoryUsage(); + $data[$edge]['pmu'] += $profile->getPeakMemoryUsage(); + } else { + $data[$edge] = array( + 'ct' => 1, + 'wt' => floor($profile->getDuration() * 1000000), + 'mu' => $profile->getMemoryUsage(), + 'pmu' => $profile->getPeakMemoryUsage(), + ); + } + } +} + +class_alias('Twig_Profiler_Dumper_Blackfire', 'Twig\Profiler\Dumper\BlackfireDumper', false); diff --git a/vendor/twig/twig/lib/Twig/Profiler/Dumper/Html.php b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Html.php new file mode 100644 index 0000000..b57a255 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Html.php @@ -0,0 +1,47 @@ + + * + * @final + */ +class Twig_Profiler_Dumper_Html extends Twig_Profiler_Dumper_Base +{ + private static $colors = array( + 'block' => '#dfd', + 'macro' => '#ddf', + 'template' => '#ffd', + 'big' => '#d44', + ); + + public function dump(Twig_Profiler_Profile $profile) + { + return '
    '.parent::dump($profile).'
    '; + } + + protected function formatTemplate(Twig_Profiler_Profile $profile, $prefix) + { + return sprintf('%s└ %s', $prefix, self::$colors['template'], $profile->getTemplate()); + } + + protected function formatNonTemplate(Twig_Profiler_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(Twig_Profiler_Profile $profile, $percent) + { + return sprintf('%.2fms/%.0f%%', $percent > 20 ? self::$colors['big'] : 'auto', $profile->getDuration() * 1000, $percent); + } +} + +class_alias('Twig_Profiler_Dumper_Html', 'Twig\Profiler\Dumper\HtmlDumper', false); diff --git a/vendor/twig/twig/lib/Twig/Profiler/Dumper/Text.php b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Text.php new file mode 100644 index 0000000..69d2c4b --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/Dumper/Text.php @@ -0,0 +1,35 @@ + + * + * @final + */ +class Twig_Profiler_Dumper_Text extends Twig_Profiler_Dumper_Base +{ + protected function formatTemplate(Twig_Profiler_Profile $profile, $prefix) + { + return sprintf('%s└ %s', $prefix, $profile->getTemplate()); + } + + protected function formatNonTemplate(Twig_Profiler_Profile $profile, $prefix) + { + return sprintf('%s└ %s::%s(%s)', $prefix, $profile->getTemplate(), $profile->getType(), $profile->getName()); + } + + protected function formatTime(Twig_Profiler_Profile $profile, $percent) + { + return sprintf('%.2fms/%.0f%%', $profile->getDuration() * 1000, $percent); + } +} + +class_alias('Twig_Profiler_Dumper_Text', 'Twig\Profiler\Dumper\TextDumper', false); diff --git a/vendor/twig/twig/lib/Twig/Profiler/Node/EnterProfile.php b/vendor/twig/twig/lib/Twig/Profiler/Node/EnterProfile.php new file mode 100644 index 0000000..69c8f79 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/Node/EnterProfile.php @@ -0,0 +1,39 @@ + + */ +class Twig_Profiler_Node_EnterProfile extends Twig_Node +{ + public function __construct($extensionName, $type, $name, $varName) + { + parent::__construct(array(), array('extension_name' => $extensionName, 'name' => $name, 'type' => $type, 'var_name' => $varName)); + } + + public function compile(Twig_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_EnterProfile', 'Twig\Profiler\Node\EnterProfileNode', false); diff --git a/vendor/twig/twig/lib/Twig/Profiler/Node/LeaveProfile.php b/vendor/twig/twig/lib/Twig/Profiler/Node/LeaveProfile.php new file mode 100644 index 0000000..d1d6a7c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/Node/LeaveProfile.php @@ -0,0 +1,33 @@ + + */ +class Twig_Profiler_Node_LeaveProfile extends Twig_Node +{ + public function __construct($varName) + { + parent::__construct(array(), array('var_name' => $varName)); + } + + public function compile(Twig_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_LeaveProfile', 'Twig\Profiler\Node\LeaveProfileNode', false); diff --git a/vendor/twig/twig/lib/Twig/Profiler/NodeVisitor/Profiler.php b/vendor/twig/twig/lib/Twig/Profiler/NodeVisitor/Profiler.php new file mode 100644 index 0000000..5db41fe --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/NodeVisitor/Profiler.php @@ -0,0 +1,67 @@ + + * + * @final + */ +class Twig_Profiler_NodeVisitor_Profiler extends Twig_BaseNodeVisitor +{ + private $extensionName; + + public function __construct($extensionName) + { + $this->extensionName = $extensionName; + } + + protected function doEnterNode(Twig_Node $node, Twig_Environment $env) + { + return $node; + } + + protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Module) { + $varName = $this->getVarName(); + $node->setNode('display_start', new Twig_Node(array(new Twig_Profiler_Node_EnterProfile($this->extensionName, Twig_Profiler_Profile::TEMPLATE, $node->getTemplateName(), $varName), $node->getNode('display_start')))); + $node->setNode('display_end', new Twig_Node(array(new Twig_Profiler_Node_LeaveProfile($varName), $node->getNode('display_end')))); + } elseif ($node instanceof Twig_Node_Block) { + $varName = $this->getVarName(); + $node->setNode('body', new Twig_Node_Body(array( + new Twig_Profiler_Node_EnterProfile($this->extensionName, Twig_Profiler_Profile::BLOCK, $node->getAttribute('name'), $varName), + $node->getNode('body'), + new Twig_Profiler_Node_LeaveProfile($varName), + ))); + } elseif ($node instanceof Twig_Node_Macro) { + $varName = $this->getVarName(); + $node->setNode('body', new Twig_Node_Body(array( + new Twig_Profiler_Node_EnterProfile($this->extensionName, Twig_Profiler_Profile::MACRO, $node->getAttribute('name'), $varName), + $node->getNode('body'), + new Twig_Profiler_Node_LeaveProfile($varName), + ))); + } + + return $node; + } + + private function getVarName() + { + return sprintf('__internal_%s', hash('sha256', $this->extensionName)); + } + + public function getPriority() + { + return 0; + } +} + +class_alias('Twig_Profiler_NodeVisitor_Profiler', 'Twig\Profiler\NodeVisitor\ProfilerNodeVisitor', false); diff --git a/vendor/twig/twig/lib/Twig/Profiler/Profile.php b/vendor/twig/twig/lib/Twig/Profiler/Profile.php new file mode 100644 index 0000000..3fdc1a8 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Profiler/Profile.php @@ -0,0 +1,170 @@ + + * + * @final + */ +class Twig_Profiler_Profile implements IteratorAggregate, Serializable +{ + const ROOT = 'ROOT'; + const BLOCK = 'block'; + const TEMPLATE = 'template'; + const MACRO = 'macro'; + + private $template; + private $name; + private $type; + private $starts = array(); + private $ends = array(); + private $profiles = array(); + + public function __construct($template = 'main', $type = self::ROOT, $name = 'main') + { + $this->template = $template; + $this->type = $type; + $this->name = 0 === strpos($name, '__internal_') ? 'INTERNAL' : $name; + $this->enter(); + } + + public function getTemplate() + { + return $this->template; + } + + public function getType() + { + return $this->type; + } + + public function getName() + { + return $this->name; + } + + public function isRoot() + { + return self::ROOT === $this->type; + } + + public function isTemplate() + { + return self::TEMPLATE === $this->type; + } + + public function isBlock() + { + return self::BLOCK === $this->type; + } + + public function isMacro() + { + return self::MACRO === $this->type; + } + + public function getProfiles() + { + return $this->profiles; + } + + public function addProfile(Twig_Profiler_Profile $profile) + { + $this->profiles[] = $profile; + } + + /** + * Returns the duration in microseconds. + * + * @return int + */ + public function getDuration() + { + if ($this->isRoot() && $this->profiles) { + // for the root node with children, duration is the sum of all child durations + $duration = 0; + foreach ($this->profiles as $profile) { + $duration += $profile->getDuration(); + } + + return $duration; + } + + return isset($this->ends['wt']) && isset($this->starts['wt']) ? $this->ends['wt'] - $this->starts['wt'] : 0; + } + + /** + * Returns the memory usage in bytes. + * + * @return int + */ + public function getMemoryUsage() + { + return isset($this->ends['mu']) && isset($this->starts['mu']) ? $this->ends['mu'] - $this->starts['mu'] : 0; + } + + /** + * Returns the peak memory usage in bytes. + * + * @return int + */ + public function getPeakMemoryUsage() + { + return isset($this->ends['pmu']) && isset($this->starts['pmu']) ? $this->ends['pmu'] - $this->starts['pmu'] : 0; + } + + /** + * Starts the profiling. + */ + public function enter() + { + $this->starts = array( + 'wt' => microtime(true), + 'mu' => memory_get_usage(), + 'pmu' => memory_get_peak_usage(), + ); + } + + /** + * Stops the profiling. + */ + public function leave() + { + $this->ends = array( + 'wt' => microtime(true), + 'mu' => memory_get_usage(), + 'pmu' => memory_get_peak_usage(), + ); + } + + public function reset() + { + $this->starts = $this->ends = $this->profiles = array(); + $this->enter(); + } + + public function getIterator() + { + return new ArrayIterator($this->profiles); + } + + public function serialize() + { + return serialize(array($this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles)); + } + + public function unserialize($data) + { + list($this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles) = unserialize($data); + } +} + +class_alias('Twig_Profiler_Profile', 'Twig\Profiler\Profile', false); diff --git a/vendor/twig/twig/lib/Twig/RuntimeLoaderInterface.php b/vendor/twig/twig/lib/Twig/RuntimeLoaderInterface.php new file mode 100644 index 0000000..f5eb14e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/RuntimeLoaderInterface.php @@ -0,0 +1,29 @@ + + */ +interface Twig_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_RuntimeLoaderInterface', 'Twig\RuntimeLoader\RuntimeLoaderInterface', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityError.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityError.php new file mode 100644 index 0000000..b6707e3 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityError.php @@ -0,0 +1,21 @@ + + */ +class Twig_Sandbox_SecurityError extends Twig_Error +{ +} + +class_alias('Twig_Sandbox_SecurityError', 'Twig\Sandbox\SecurityError', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFilterError.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFilterError.php new file mode 100644 index 0000000..0ba3327 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFilterError.php @@ -0,0 +1,33 @@ + + */ +class Twig_Sandbox_SecurityNotAllowedFilterError extends Twig_Sandbox_SecurityError +{ + private $filterName; + + public function __construct($message, $functionName, $lineno = -1, $filename = null, Exception $previous = null) + { + parent::__construct($message, $lineno, $filename, $previous); + $this->filterName = $functionName; + } + + public function getFilterName() + { + return $this->filterName; + } +} + +class_alias('Twig_Sandbox_SecurityNotAllowedFilterError', 'Twig\Sandbox\SecurityNotAllowedFilterError', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFunctionError.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFunctionError.php new file mode 100644 index 0000000..aa39142 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedFunctionError.php @@ -0,0 +1,33 @@ + + */ +class Twig_Sandbox_SecurityNotAllowedFunctionError extends Twig_Sandbox_SecurityError +{ + private $functionName; + + public function __construct($message, $functionName, $lineno = -1, $filename = null, Exception $previous = null) + { + parent::__construct($message, $lineno, $filename, $previous); + $this->functionName = $functionName; + } + + public function getFunctionName() + { + return $this->functionName; + } +} + +class_alias('Twig_Sandbox_SecurityNotAllowedFunctionError', 'Twig\Sandbox\SecurityNotAllowedFunctionError', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedMethodError.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedMethodError.php new file mode 100644 index 0000000..93012fe --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedMethodError.php @@ -0,0 +1,40 @@ + + */ +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) + { + parent::__construct($message, $lineno, $filename, $previous); + $this->className = $className; + $this->methodName = $methodName; + } + + public function getClassName() + { + return $this->className; + } + + public function getMethodName() + { + return $this->methodName; + } +} + +class_alias('Twig_Sandbox_SecurityNotAllowedMethodError', 'Twig\Sandbox\SecurityNotAllowedMethodError', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedPropertyError.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedPropertyError.php new file mode 100644 index 0000000..f27969c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedPropertyError.php @@ -0,0 +1,40 @@ + + */ +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) + { + parent::__construct($message, $lineno, $filename, $previous); + $this->className = $className; + $this->propertyName = $propertyName; + } + + public function getClassName() + { + return $this->className; + } + + public function getPropertyName() + { + return $this->propertyName; + } +} + +class_alias('Twig_Sandbox_SecurityNotAllowedPropertyError', 'Twig\Sandbox\SecurityNotAllowedPropertyError', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedTagError.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedTagError.php new file mode 100644 index 0000000..4bbd223 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityNotAllowedTagError.php @@ -0,0 +1,33 @@ + + */ +class Twig_Sandbox_SecurityNotAllowedTagError extends Twig_Sandbox_SecurityError +{ + private $tagName; + + public function __construct($message, $tagName, $lineno = -1, $filename = null, Exception $previous = null) + { + parent::__construct($message, $lineno, $filename, $previous); + $this->tagName = $tagName; + } + + public function getTagName() + { + return $this->tagName; + } +} + +class_alias('Twig_Sandbox_SecurityNotAllowedTagError', 'Twig\Sandbox\SecurityNotAllowedTagError', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityPolicy.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityPolicy.php new file mode 100644 index 0000000..dca0b82 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityPolicy.php @@ -0,0 +1,125 @@ + + */ +class Twig_Sandbox_SecurityPolicy implements Twig_Sandbox_SecurityPolicyInterface +{ + protected $allowedTags; + protected $allowedFilters; + protected $allowedMethods; + protected $allowedProperties; + protected $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; + $this->setAllowedMethods($allowedMethods); + $this->allowedProperties = $allowedProperties; + $this->allowedFunctions = $allowedFunctions; + } + + public function setAllowedTags(array $tags) + { + $this->allowedTags = $tags; + } + + public function setAllowedFilters(array $filters) + { + $this->allowedFilters = $filters; + } + + public function setAllowedMethods(array $methods) + { + $this->allowedMethods = array(); + foreach ($methods as $class => $m) { + $this->allowedMethods[$class] = array_map('strtolower', is_array($m) ? $m : array($m)); + } + } + + public function setAllowedProperties(array $properties) + { + $this->allowedProperties = $properties; + } + + public function setAllowedFunctions(array $functions) + { + $this->allowedFunctions = $functions; + } + + public function checkSecurity($tags, $filters, $functions) + { + foreach ($tags as $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 Twig_Sandbox_SecurityNotAllowedFilterError(sprintf('Filter "%s" is not allowed.', $filter), $filter); + } + } + + foreach ($functions as $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 Twig_Markup) { + return true; + } + + $allowed = false; + $method = strtolower($method); + foreach ($this->allowedMethods as $class => $methods) { + if ($obj instanceof $class) { + $allowed = in_array($method, $methods); + + break; + } + } + + if (!$allowed) { + $class = get_class($obj); + throw new Twig_Sandbox_SecurityNotAllowedMethodError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method); + } + } + + 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 : array($properties)); + + break; + } + } + + if (!$allowed) { + $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', false); diff --git a/vendor/twig/twig/lib/Twig/Sandbox/SecurityPolicyInterface.php b/vendor/twig/twig/lib/Twig/Sandbox/SecurityPolicyInterface.php new file mode 100644 index 0000000..88f6444 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Sandbox/SecurityPolicyInterface.php @@ -0,0 +1,26 @@ + + */ +interface Twig_Sandbox_SecurityPolicyInterface +{ + public function checkSecurity($tags, $filters, $functions); + + public function checkMethodAllowed($obj, $method); + + public function checkPropertyAllowed($obj, $method); +} + +class_alias('Twig_Sandbox_SecurityPolicyInterface', 'Twig\Sandbox\SecurityPolicyInterface', false); diff --git a/vendor/twig/twig/lib/Twig/SimpleFilter.php b/vendor/twig/twig/lib/Twig/SimpleFilter.php new file mode 100644 index 0000000..ee4c0ae --- /dev/null +++ b/vendor/twig/twig/lib/Twig/SimpleFilter.php @@ -0,0 +1,121 @@ + + */ +class Twig_SimpleFilter +{ + protected $name; + protected $callable; + protected $options; + protected $arguments = array(); + + public function __construct($name, $callable, array $options = array()) + { + $this->name = $name; + $this->callable = $callable; + $this->options = array_merge(array( + '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_Filter', + '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(Twig_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_SimpleFilter', 'Twig\TwigFilter', false); diff --git a/vendor/twig/twig/lib/Twig/SimpleFunction.php b/vendor/twig/twig/lib/Twig/SimpleFunction.php new file mode 100644 index 0000000..a6aa7ca --- /dev/null +++ b/vendor/twig/twig/lib/Twig/SimpleFunction.php @@ -0,0 +1,111 @@ + + */ +class Twig_SimpleFunction +{ + protected $name; + protected $callable; + protected $options; + protected $arguments = array(); + + public function __construct($name, $callable, array $options = array()) + { + $this->name = $name; + $this->callable = $callable; + $this->options = array_merge(array( + 'needs_environment' => false, + 'needs_context' => false, + 'is_variadic' => false, + 'is_safe' => null, + 'is_safe_callback' => null, + 'node_class' => 'Twig_Node_Expression_Function', + '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(Twig_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 array(); + } + + 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_SimpleFunction', 'Twig\TwigFunction', false); diff --git a/vendor/twig/twig/lib/Twig/SimpleTest.php b/vendor/twig/twig/lib/Twig/SimpleTest.php new file mode 100644 index 0000000..79fd234 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/SimpleTest.php @@ -0,0 +1,85 @@ + + */ +class Twig_SimpleTest +{ + protected $name; + protected $callable; + protected $options; + + private $arguments = array(); + + public function __construct($name, $callable, array $options = array()) + { + $this->name = $name; + $this->callable = $callable; + $this->options = array_merge(array( + 'is_variadic' => false, + 'node_class' => 'Twig_Node_Expression_Test', + '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_SimpleTest', 'Twig\TwigTest', false); diff --git a/vendor/twig/twig/lib/Twig/Source.php b/vendor/twig/twig/lib/Twig/Source.php new file mode 100644 index 0000000..bd8d869 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Source.php @@ -0,0 +1,53 @@ + + */ +class Twig_Source +{ + private $code; + private $name; + private $path; + + /** + * @param string $code The template source code + * @param string $name The template logical name + * @param string $path The filesystem path of the template if any + */ + public function __construct($code, $name, $path = '') + { + $this->code = $code; + $this->name = $name; + $this->path = $path; + } + + public function getCode() + { + return $this->code; + } + + public function getName() + { + return $this->name; + } + + public function getPath() + { + return $this->path; + } +} + +class_alias('Twig_Source', 'Twig\Source', false); diff --git a/vendor/twig/twig/lib/Twig/SourceContextLoaderInterface.php b/vendor/twig/twig/lib/Twig/SourceContextLoaderInterface.php new file mode 100644 index 0000000..a6e8c42 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/SourceContextLoaderInterface.php @@ -0,0 +1,33 @@ + + * + * @deprecated since 1.27 (to be removed in 3.0) + */ +interface Twig_SourceContextLoaderInterface +{ + /** + * Returns the source context for a given template logical name. + * + * @param string $name The template logical name + * + * @return Twig_Source + * + * @throws Twig_Error_Loader When $name is not found + */ + public function getSourceContext($name); +} + +class_alias('Twig_SourceContextLoaderInterface', 'Twig\Loader\SourceContextLoaderInterface', false); diff --git a/vendor/twig/twig/lib/Twig/Template.php b/vendor/twig/twig/lib/Twig/Template.php new file mode 100644 index 0000000..3709232 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Template.php @@ -0,0 +1,708 @@ +load() + * instead, which returns an instance of Twig_TemplateWrapper. + * + * @author Fabien Potencier + * + * @internal + */ +abstract class Twig_Template implements Twig_TemplateInterface +{ + /** + * @internal + */ + protected static $cache = array(); + + protected $parent; + protected $parents = array(); + protected $env; + protected $blocks = array(); + protected $traits = array(); + + public function __construct(Twig_Environment $env) + { + $this->env = $env; + } + + /** + * @internal this method will be removed in 2.0 and is only used internally to provide an upgrade path from 1.x to 2.0 + */ + public function __toString() + { + return $this->getTemplateName(); + } + + /** + * Returns the template name. + * + * @return string The template name + */ + abstract public function getTemplateName(); + + /** + * Returns debug information about the template. + * + * @return array Debug information + * + * @internal + */ + public function getDebugInfo() + { + return array(); + } + + /** + * Returns the template source code. + * + * @return string The template source code + * + * @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead + */ + public function getSource() + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); + + return ''; + } + + /** + * Returns information about the original template source code. + * + * @return Twig_Source + */ + public function getSourceContext() + { + return new Twig_Source('', $this->getTemplateName()); + } + + /** + * @deprecated since 1.20 (to be removed in 2.0) + */ + public function getEnvironment() + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.20 and will be removed in 2.0.', E_USER_DEPRECATED); + + return $this->env; + } + + /** + * Returns the parent template. + * + * This method is for internal use only and should never be called + * directly. + * + * @param array $context + * + * @return Twig_TemplateInterface|false The parent template or false if there is no parent + * + * @internal + */ + public function getParent(array $context) + { + if (null !== $this->parent) { + return $this->parent; + } + + try { + $parent = $this->doGetParent($context); + + if (false === $parent) { + return false; + } + + if ($parent instanceof self) { + return $this->parents[$parent->getTemplateName()] = $parent; + } + + if (!isset($this->parents[$parent])) { + $this->parents[$parent] = $this->loadTemplate($parent); + } + } catch (Twig_Error_Loader $e) { + $e->setSourceContext(null); + $e->guess(); + + throw $e; + } + + return $this->parents[$parent]; + } + + protected function doGetParent(array $context) + { + return false; + } + + public function isTraitable() + { + return true; + } + + /** + * Displays a parent block. + * + * This method is for internal use only and should never be called + * directly. + * + * @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 = array()) + { + $name = (string) $name; + + if (isset($this->traits[$name])) { + $this->traits[$name][0]->displayBlock($name, $context, $blocks, false); + } elseif (false !== $parent = $this->getParent($context)) { + $parent->displayBlock($name, $context, $blocks, false); + } else { + throw new Twig_Error_Runtime(sprintf('The template has no parent and no traits defining the "%s" block.', $name), -1, $this->getSourceContext()); + } + } + + /** + * Displays a block. + * + * This method is for internal use only and should never be called + * directly. + * + * @param string $name The block name to display + * @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 = array(), $useBlocks = true) + { + $name = (string) $name; + + if ($useBlocks && isset($blocks[$name])) { + $template = $blocks[$name][0]; + $block = $blocks[$name][1]; + } elseif (isset($this->blocks[$name])) { + $template = $this->blocks[$name][0]; + $block = $this->blocks[$name][1]; + } else { + $template = null; + $block = null; + } + + // 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.'); + } + + if (null !== $template) { + try { + $template->$block($context, $blocks); + } catch (Twig_Error $e) { + if (!$e->getSourceContext()) { + $e->setSourceContext($template->getSourceContext()); + } + + // 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) { + 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); + } + } + + /** + * Renders a parent block. + * + * This method is for internal use only and should never be called + * directly. + * + * @param string $name The block name to render from the parent + * @param array $context The context + * @param array $blocks The current set of blocks + * + * @return string The rendered block + * + * @internal + */ + public function renderParentBlock($name, array $context, array $blocks = array()) + { + ob_start(); + $this->displayParentBlock($name, $context, $blocks); + + return ob_get_clean(); + } + + /** + * Renders a block. + * + * This method is for internal use only and should never be called + * directly. + * + * @param string $name The block name to render + * @param array $context The context + * @param array $blocks The current set of 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 = array(), $useBlocks = true) + { + ob_start(); + $this->displayBlock($name, $context, $blocks, $useBlocks); + + return ob_get_clean(); + } + + /** + * Returns whether a block exists or not in the current context of the template. + * + * This method checks blocks defined in the current template + * or defined in "used" traits or defined in parent templates. + * + * @param string $name The block name + * @param array $context The context + * @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 = 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); + + return isset($this->blocks[(string) $name]); + } + + if (isset($blocks[$name])) { + return $blocks[$name][0] instanceof self; + } + + if (isset($this->blocks[$name])) { + return true; + } + + if (false !== $parent = $this->getParent($context)) { + return $parent->hasBlock($name, $context); + } + + return false; + } + + /** + * Returns all block names in the current context of the template. + * + * This method checks blocks defined in the current template + * or defined in "used" traits or defined in parent templates. + * + * @param array $context The context + * @param array $blocks The current set of blocks + * + * @return array An array of block names + * + * @internal + */ + 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); + + return array_keys($this->blocks); + } + + $names = array_merge(array_keys($blocks), array_keys($this->blocks)); + + if (false !== $parent = $this->getParent($context)) { + $names = array_merge($names, $parent->getBlockNames($context)); + } + + return array_unique($names); + } + + protected function loadTemplate($template, $templateName = null, $line = null, $index = null) + { + try { + if (is_array($template)) { + return $this->env->resolveTemplate($template); + } + + if ($template instanceof self) { + return $template; + } + + if ($template instanceof Twig_TemplateWrapper) { + return $template; + } + + return $this->env->loadTemplate($template, $index); + } catch (Twig_Error $e) { + if (!$e->getSourceContext()) { + $e->setSourceContext($templateName ? new Twig_Source('', $templateName) : $this->getSourceContext()); + } + + if ($e->getTemplateLine()) { + throw $e; + } + + if (!$line) { + $e->guess(); + } else { + $e->setTemplateLine($line); + } + + throw $e; + } + } + + /** + * Returns all blocks. + * + * This method is for internal use only and should never be called + * directly. + * + * @return array An array of blocks + * + * @internal + */ + public function getBlocks() + { + return $this->blocks; + } + + public function display(array $context, array $blocks = array()) + { + $this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks)); + } + + public function render(array $context) + { + $level = ob_get_level(); + ob_start(); + try { + $this->display($context); + } catch (Exception $e) { + while (ob_get_level() > $level) { + ob_end_clean(); + } + + throw $e; + } catch (Throwable $e) { + while (ob_get_level() > $level) { + ob_end_clean(); + } + + throw $e; + } + + return ob_get_clean(); + } + + protected function displayWithErrorHandling(array $context, array $blocks = array()) + { + try { + $this->doDisplay($context, $blocks); + } catch (Twig_Error $e) { + if (!$e->getSourceContext()) { + $e->setSourceContext($this->getSourceContext()); + } + + // 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) { + throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getSourceContext(), $e); + } + } + + /** + * Auto-generated method to display the template with the given context. + * + * @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 = array()); + + /** + * Returns a variable from the context. + * + * This method is for internal use only and should never be called + * directly. + * + * This method should not be overridden in a sub-class as this is an + * implementation detail that has been introduced to optimize variable + * access for versions of PHP before 5.4. This is not a way to override + * the way to get a variable value. + * + * @param array $context The context + * @param string $item The variable to return from the context + * @param bool $ignoreStrictCheck Whether to ignore the strict variable check or not + * + * @return mixed The content of the context variable + * + * @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 ($ignoreStrictCheck || !$this->env->isStrictVariables()) { + return; + } + + throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist.', $item), -1, $this->getSourceContext()); + } + + return $context[$item]; + } + + /** + * Returns the attribute value for a given array/object. + * + * @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 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 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 = 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; + + if ((is_array($object) && (isset($object[$arrayItem]) || array_key_exists($arrayItem, $object))) + || ($object instanceof ArrayAccess && isset($object[$arrayItem])) + ) { + if ($isDefinedTest) { + return true; + } + + return $object[$arrayItem]; + } + + if (self::ARRAY_CALL === $type || !is_object($object)) { + if ($isDefinedTest) { + return false; + } + + if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { + 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 (empty($object)) { + $message = sprintf('Key "%s" does not exist as the array is empty.', $arrayItem); + } else { + $message = sprintf('Key "%s" for array with keys "%s" does not exist.', $arrayItem, implode(', ', array_keys($object))); + } + } elseif (self::ARRAY_CALL === $type) { + 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); + } + } 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); + } + + throw new Twig_Error_Runtime($message, -1, $this->getSourceContext()); + } + } + + if (!is_object($object)) { + if ($isDefinedTest) { + return false; + } + + if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { + return; + } + + 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); + } + + 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, $object)) { + if ($isDefinedTest) { + return true; + } + + if ($this->env->hasExtension('Twig_Extension_Sandbox')) { + $this->env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item); + } + + return $object->$item; + } + } + + $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 = array(); + + 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; + } + } + } else { + $methods = get_class_methods($object); + } + // sort values to have consistent behavior, so that "get" methods win precedence over "is" methods + sort($methods); + + $cache = array(); + + foreach ($methods as $method) { + $cache[$method] = $method; + $cache[$lcName = strtolower($method)] = $method; + + if ('g' === $lcName[0] && 0 === strpos($lcName, 'get')) { + $name = substr($method, 3); + $lcName = substr($lcName, 3); + } elseif ('i' === $lcName[0] && 0 === strpos($lcName, 'is')) { + $name = substr($method, 2); + $lcName = substr($lcName, 2); + } else { + 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; + } + } + } + self::$cache[$class] = $cache; + } + + $call = false; + if (isset(self::$cache[$class][$item])) { + $method = self::$cache[$class][$item]; + } elseif (isset(self::$cache[$class][$lcItem = strtolower($item)])) { + $method = self::$cache[$class][$lcItem]; + } elseif (isset(self::$cache[$class]['__call'])) { + $method = $item; + $call = true; + } else { + if ($isDefinedTest) { + return false; + } + + if ($ignoreStrictCheck || !$this->env->isStrictVariables()) { + return; + } + + 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_Sandbox')) { + $this->env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method); + } + + // Some objects throw exceptions when they have __call, and the method we try + // to call is not supported. If ignoreStrictCheck is true, we should return null. + try { + if (!$arguments) { + $ret = $object->$method(); + } else { + $ret = call_user_func_array(array($object, $method), $arguments); + } + } catch (BadMethodCallException $e) { + if ($call && ($ignoreStrictCheck || !$this->env->isStrictVariables())) { + return; + } + throw $e; + } + + // @deprecated in 1.28 + 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()); + if ('renderBlock' === $method || 'displayBlock' === $method) { + $message .= sprintf(' Use block("%s"%s) instead).', $arguments[0], $self ? '' : ', template'); + } elseif ('hasBlock' === $method) { + $message .= sprintf(' Use "block("%s"%s) is defined" instead).', $arguments[0], $self ? '' : ', template'); + } elseif ('render' === $method || 'display' === $method) { + $message .= sprintf(' Use include("%s") instead).', $object->getTemplateName()); + } + @trigger_error($message, E_USER_DEPRECATED); + + return '' === $ret ? '' : new Twig_Markup($ret, $this->env->getCharset()); + } + + return $ret; + } +} + +class_alias('Twig_Template', 'Twig\Template', false); diff --git a/vendor/twig/twig/lib/Twig/TemplateInterface.php b/vendor/twig/twig/lib/Twig/TemplateInterface.php new file mode 100644 index 0000000..457ef7d --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TemplateInterface.php @@ -0,0 +1,48 @@ + + * + * @deprecated since 1.12 (to be removed in 3.0) + */ +interface Twig_TemplateInterface +{ + const ANY_CALL = 'any'; + const ARRAY_CALL = 'array'; + const METHOD_CALL = 'method'; + + /** + * Renders the template with the given context and returns it as string. + * + * @param array $context An array of parameters to pass to the template + * + * @return string The rendered template + */ + public function render(array $context); + + /** + * Displays the template with the given context. + * + * @param array $context An array of parameters to pass to the template + * @param array $blocks An array of blocks to pass to the template + */ + public function display(array $context, array $blocks = array()); + + /** + * Returns the bound environment for this template. + * + * @return Twig_Environment + */ + public function getEnvironment(); +} diff --git a/vendor/twig/twig/lib/Twig/TemplateWrapper.php b/vendor/twig/twig/lib/Twig/TemplateWrapper.php new file mode 100644 index 0000000..497f6e9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TemplateWrapper.php @@ -0,0 +1,133 @@ + + */ +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). + * + * @internal + */ + public function __construct(Twig_Environment $env, Twig_Template $template) + { + $this->env = $env; + $this->template = $template; + } + + /** + * Renders the template. + * + * @param array $context An array of parameters to pass to the template + * + * @return string The rendered template + */ + public function render($context = array()) + { + return $this->template->render($context); + } + + /** + * Displays the template. + * + * @param array $context An array of parameters to pass to the template + */ + public function display($context = array()) + { + $this->template->display($context); + } + + /** + * Checks if a block is defined. + * + * @param string $name The block name + * @param array $context An array of parameters to pass to the template + * + * @return bool + */ + public function hasBlock($name, $context = array()) + { + return $this->template->hasBlock($name, $context); + } + + /** + * Returns defined block names in the template. + * + * @param array $context An array of parameters to pass to the template + * + * @return string[] An array of defined template block names + */ + public function getBlockNames($context = array()) + { + return $this->template->getBlockNames($context); + } + + /** + * Renders a template block. + * + * @param string $name The block name to render + * @param array $context An array of parameters to pass to the template + * + * @return string The rendered block + */ + public function renderBlock($name, $context = array()) + { + $context = $this->env->mergeGlobals($context); + $level = ob_get_level(); + ob_start(); + try { + $this->template->displayBlock($name, $context); + } catch (Exception $e) { + while (ob_get_level() > $level) { + ob_end_clean(); + } + + throw $e; + } catch (Throwable $e) { + while (ob_get_level() > $level) { + ob_end_clean(); + } + + throw $e; + } + + return ob_get_clean(); + } + + /** + * Displays a template block. + * + * @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 = array()) + { + $this->template->displayBlock($name, $this->env->mergeGlobals($context)); + } + + /** + * @return Twig_Source + */ + public function getSourceContext() + { + return $this->template->getSourceContext(); + } +} + +class_alias('Twig_TemplateWrapper', 'Twig\TemplateWrapper', false); diff --git a/vendor/twig/twig/lib/Twig/Test.php b/vendor/twig/twig/lib/Twig/Test.php new file mode 100644 index 0000000..b450ec6 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Test.php @@ -0,0 +1,37 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +abstract class Twig_Test implements Twig_TestInterface, Twig_TestCallableInterface +{ + protected $options; + protected $arguments = array(); + + public function __construct(array $options = array()) + { + $this->options = array_merge(array( + 'callable' => null, + ), $options); + } + + public function getCallable() + { + return $this->options['callable']; + } +} diff --git a/vendor/twig/twig/lib/Twig/Test/Function.php b/vendor/twig/twig/lib/Twig/Test/Function.php new file mode 100644 index 0000000..9e83c3f --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Test/Function.php @@ -0,0 +1,38 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Test_Function extends Twig_Test +{ + protected $function; + + public function __construct($function, array $options = array()) + { + $options['callable'] = $function; + + parent::__construct($options); + + $this->function = $function; + } + + public function compile() + { + return $this->function; + } +} diff --git a/vendor/twig/twig/lib/Twig/Test/IntegrationTestCase.php b/vendor/twig/twig/lib/Twig/Test/IntegrationTestCase.php new file mode 100644 index 0000000..382a3f2 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Test/IntegrationTestCase.php @@ -0,0 +1,249 @@ + + * @author Karma Dordrak + */ +abstract class Twig_Test_IntegrationTestCase extends TestCase +{ + /** + * @return string + */ + abstract protected function getFixturesDir(); + + /** + * @return Twig_RuntimeLoaderInterface[] + */ + protected function getRuntimeLoaders() + { + return array(); + } + + /** + * @return Twig_ExtensionInterface[] + */ + protected function getExtensions() + { + return array(); + } + + /** + * @return Twig_SimpleFilter[] + */ + protected function getTwigFilters() + { + return array(); + } + + /** + * @return Twig_SimpleFunction[] + */ + protected function getTwigFunctions() + { + return array(); + } + + /** + * @return Twig_SimpleTest[] + */ + protected function getTwigTests() + { + return array(); + } + + /** + * @dataProvider getTests + */ + public function testIntegration($file, $message, $condition, $templates, $exception, $outputs) + { + $this->doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs); + } + + /** + * @dataProvider getLegacyTests + * @group legacy + */ + public function testLegacyIntegration($file, $message, $condition, $templates, $exception, $outputs) + { + $this->doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs); + } + + public function getTests($name, $legacyTests = false) + { + $fixturesDir = realpath($this->getFixturesDir()); + $tests = array(); + + foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($fixturesDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) { + if (!preg_match('/\.test$/', $file)) { + continue; + } + + if ($legacyTests xor false !== strpos($file->getRealpath(), '.legacy.test')) { + continue; + } + + $test = file_get_contents($file->getRealpath()); + + if (preg_match('/--TEST--\s*(.*?)\s*(?:--CONDITION--\s*(.*))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)\s*(?:--DATA--\s*(.*))?\s*--EXCEPTION--\s*(.*)/sx', $test, $match)) { + $message = $match[1]; + $condition = $match[2]; + $templates = self::parseTemplates($match[3]); + $exception = $match[5]; + $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]; + $templates = self::parseTemplates($match[3]); + $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))); + } + + $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 array(array('not', '-', '', array(), '', array())); + } + + return $tests; + } + + public function getLegacyTests() + { + return $this->getTests('testLegacyIntegration', true); + } + + protected function doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs) + { + if (!$outputs) { + $this->markTestSkipped('no tests to run'); + } + + if ($condition) { + eval('$ret = '.$condition.';'); + if (!$ret) { + $this->markTestSkipped($condition); + } + } + + $loader = new Twig_Loader_Array($templates); + + foreach ($outputs as $i => $match) { + $config = array_merge(array( + 'cache' => false, + 'strict_variables' => true, + ), $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); + } + + foreach ($this->getTwigFilters() as $filter) { + $twig->addFilter($filter); + } + + foreach ($this->getTwigTests() as $test) { + $twig->addTest($test); + } + + foreach ($this->getTwigFunctions() as $function) { + $twig->addFunction($function); + } + + // 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->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, $message, 'Exception message must end with a dot or a question mark.'); + + return; + } + + 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) { + if (false !== $exception) { + $this->assertSame(trim($exception), trim(sprintf('%s: %s', get_class($e), $e->getMessage()))); + + return; + } + + $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())); + } + + 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)); + } + + $expected = trim($match[3], "\n "); + + if ($expected !== $output) { + printf("Compiled templates that failed on case %d:\n", $i + 1); + + foreach (array_keys($templates) as $name) { + echo "Template: $name\n"; + $loader = $twig->getLoader(); + if (!$loader instanceof Twig_SourceContextLoaderInterface) { + $source = new Twig_Source($loader->getSource($name), $name); + } else { + $source = $loader->getSourceContext($name); + } + echo $twig->compile($twig->parse($twig->tokenize($source))); + } + } + $this->assertEquals($expected, $output, $message.' (in '.$file.')'); + } + } + + protected static function parseTemplates($test) + { + $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]; + } + + return $templates; + } +} + +class_alias('Twig_Test_IntegrationTestCase', 'Twig\Test\IntegrationTestCase', false); diff --git a/vendor/twig/twig/lib/Twig/Test/Method.php b/vendor/twig/twig/lib/Twig/Test/Method.php new file mode 100644 index 0000000..feccd5d --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Test/Method.php @@ -0,0 +1,40 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Test_Method extends Twig_Test +{ + protected $extension; + protected $method; + + public function __construct(Twig_ExtensionInterface $extension, $method, array $options = array()) + { + $options['callable'] = array($extension, $method); + + parent::__construct($options); + + $this->extension = $extension; + $this->method = $method; + } + + public function compile() + { + return sprintf('$this->env->getExtension(\'%s\')->%s', get_class($this->extension), $this->method); + } +} diff --git a/vendor/twig/twig/lib/Twig/Test/Node.php b/vendor/twig/twig/lib/Twig/Test/Node.php new file mode 100644 index 0000000..6098a52 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Test/Node.php @@ -0,0 +1,40 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_Test_Node extends Twig_Test +{ + protected $class; + + public function __construct($class, array $options = array()) + { + parent::__construct($options); + + $this->class = $class; + } + + public function getClass() + { + return $this->class; + } + + public function compile() + { + } +} diff --git a/vendor/twig/twig/lib/Twig/Test/NodeTestCase.php b/vendor/twig/twig/lib/Twig/Test/NodeTestCase.php new file mode 100644 index 0000000..4794267 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Test/NodeTestCase.php @@ -0,0 +1,75 @@ +assertNodeCompilation($source, $node, $environment, $isPattern); + } + + public function assertNodeCompilation($source, Twig_Node $node, Twig_Environment $environment = null, $isPattern = false) + { + $compiler = $this->getCompiler($environment); + $compiler->compile($node); + + if ($isPattern) { + $this->assertStringMatchesFormat($source, trim($compiler->getSource())); + } else { + $this->assertEquals($source, trim($compiler->getSource())); + } + } + + protected function getCompiler(Twig_Environment $environment = null) + { + return new Twig_Compiler(null === $environment ? $this->getEnvironment() : $environment); + } + + protected function getEnvironment() + { + 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, $name); + } + + if (PHP_VERSION_ID >= 50400) { + return sprintf('%s(isset($context["%s"]) ? $context["%s"] : null)', $line, $name, $name); + } + + return sprintf('%s$this->getContext($context, "%s")', $line, $name); + } + + protected function getAttributeGetter() + { + if (function_exists('twig_template_get_attributes')) { + return 'twig_template_get_attributes($this, '; + } + + return '$this->getAttribute('; + } +} + +class_alias('Twig_Test_NodeTestCase', 'Twig\Test\NodeTestCase', false); +class_exists('Twig_Environment'); +class_exists('Twig_Node'); diff --git a/vendor/twig/twig/lib/Twig/TestCallableInterface.php b/vendor/twig/twig/lib/Twig/TestCallableInterface.php new file mode 100644 index 0000000..51ecb9a --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TestCallableInterface.php @@ -0,0 +1,22 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +interface Twig_TestCallableInterface +{ + public function getCallable(); +} diff --git a/vendor/twig/twig/lib/Twig/TestInterface.php b/vendor/twig/twig/lib/Twig/TestInterface.php new file mode 100644 index 0000000..9166407 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TestInterface.php @@ -0,0 +1,27 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +interface Twig_TestInterface +{ + /** + * Compiles a test. + * + * @return string The PHP code for the test + */ + public function compile(); +} diff --git a/vendor/twig/twig/lib/Twig/Token.php b/vendor/twig/twig/lib/Twig/Token.php new file mode 100644 index 0000000..8906686 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Token.php @@ -0,0 +1,207 @@ + + * + * @final + */ +class Twig_Token +{ + protected $value; + protected $type; + protected $lineno; + + const EOF_TYPE = -1; + const TEXT_TYPE = 0; + const BLOCK_START_TYPE = 1; + const VAR_START_TYPE = 2; + const BLOCK_END_TYPE = 3; + const VAR_END_TYPE = 4; + const NAME_TYPE = 5; + const NUMBER_TYPE = 6; + const STRING_TYPE = 7; + const OPERATOR_TYPE = 8; + const PUNCTUATION_TYPE = 9; + const INTERPOLATION_START_TYPE = 10; + const INTERPOLATION_END_TYPE = 11; + + /** + * @param int $type The type of the token + * @param string $value The token value + * @param int $lineno The line position in the source + */ + public function __construct($type, $value, $lineno) + { + $this->type = $type; + $this->value = $value; + $this->lineno = $lineno; + } + + public function __toString() + { + return sprintf('%s(%s)', self::typeToString($this->type, true), $this->value); + } + + /** + * Tests the current token for a type and/or a value. + * + * Parameters may be: + * * just type + * * 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|string|null $values The token value + * + * @return bool + */ + public function test($type, $values = null) + { + 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)) || + $this->value == $values + ); + } + + /** + * @return int + */ + public function getLine() + { + return $this->lineno; + } + + /** + * @return int + */ + public function getType() + { + return $this->type; + } + + /** + * @return string + */ + public function getValue() + { + return $this->value; + } + + /** + * Returns the constant representation (internal) of a given type. + * + * @param int $type The type as an integer + * @param bool $short Whether to return a short representation or not + * + * @return string The string representation + */ + public static function typeToString($type, $short = false) + { + switch ($type) { + case self::EOF_TYPE: + $name = 'EOF_TYPE'; + break; + case self::TEXT_TYPE: + $name = 'TEXT_TYPE'; + break; + case self::BLOCK_START_TYPE: + $name = 'BLOCK_START_TYPE'; + break; + case self::VAR_START_TYPE: + $name = 'VAR_START_TYPE'; + break; + case self::BLOCK_END_TYPE: + $name = 'BLOCK_END_TYPE'; + break; + case self::VAR_END_TYPE: + $name = 'VAR_END_TYPE'; + break; + case self::NAME_TYPE: + $name = 'NAME_TYPE'; + break; + case self::NUMBER_TYPE: + $name = 'NUMBER_TYPE'; + break; + case self::STRING_TYPE: + $name = 'STRING_TYPE'; + break; + case self::OPERATOR_TYPE: + $name = 'OPERATOR_TYPE'; + break; + case self::PUNCTUATION_TYPE: + $name = 'PUNCTUATION_TYPE'; + break; + case self::INTERPOLATION_START_TYPE: + $name = 'INTERPOLATION_START_TYPE'; + break; + case self::INTERPOLATION_END_TYPE: + $name = 'INTERPOLATION_END_TYPE'; + break; + default: + throw new LogicException(sprintf('Token of type "%s" does not exist.', $type)); + } + + return $short ? $name : 'Twig_Token::'.$name; + } + + /** + * Returns the English representation of a given type. + * + * @param int $type The type as an integer + * + * @return string The string representation + */ + public static function typeToEnglish($type) + { + switch ($type) { + case self::EOF_TYPE: + return 'end of template'; + case self::TEXT_TYPE: + return 'text'; + case self::BLOCK_START_TYPE: + return 'begin of statement block'; + case self::VAR_START_TYPE: + return 'begin of print statement'; + case self::BLOCK_END_TYPE: + return 'end of statement block'; + case self::VAR_END_TYPE: + return 'end of print statement'; + case self::NAME_TYPE: + return 'name'; + case self::NUMBER_TYPE: + return 'number'; + case self::STRING_TYPE: + return 'string'; + case self::OPERATOR_TYPE: + return 'operator'; + case self::PUNCTUATION_TYPE: + return 'punctuation'; + case self::INTERPOLATION_START_TYPE: + return 'begin of string interpolation'; + case self::INTERPOLATION_END_TYPE: + return 'end of string interpolation'; + default: + throw new LogicException(sprintf('Token of type "%s" does not exist.', $type)); + } + } +} + +class_alias('Twig_Token', 'Twig\Token', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser.php b/vendor/twig/twig/lib/Twig/TokenParser.php new file mode 100644 index 0000000..1b4de14 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser.php @@ -0,0 +1,33 @@ + + */ +abstract class Twig_TokenParser implements Twig_TokenParserInterface +{ + /** + * @var Twig_Parser + */ + protected $parser; + + /** + * Sets the parser associated with this token parser. + */ + public function setParser(Twig_Parser $parser) + { + $this->parser = $parser; + } +} + +class_alias('Twig_TokenParser', 'Twig\TokenParser\AbstractTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/AutoEscape.php b/vendor/twig/twig/lib/Twig/TokenParser/AutoEscape.php new file mode 100644 index 0000000..a20dedd --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/AutoEscape.php @@ -0,0 +1,83 @@ + + * {% autoescape true %} + * Everything will be automatically escaped in this block + * {% endautoescape %} + * + * {% autoescape false %} + * Everything will be outputed as is in this block + * {% endautoescape %} + * + * {% autoescape true js %} + * Everything will be automatically escaped in this block + * using the js escaping strategy + * {% endautoescape %} + * + * + * @final + */ +class Twig_TokenParser_AutoEscape extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + $stream = $this->parser->getStream(); + + if ($stream->test(Twig_Token::BLOCK_END_TYPE)) { + $value = 'html'; + } else { + $expr = $this->parser->getExpressionParser()->parseExpression(); + if (!$expr instanceof Twig_Node_Expression_Constant) { + throw new Twig_Error_Syntax('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(Twig_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 Twig_Error_Syntax('Unexpected escaping strategy as you set autoescaping to false.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); + } + + $value = $stream->next()->getValue(); + } + } + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_AutoEscape($value, $body, $lineno, $this->getTag()); + } + + public function decideBlockEnd(Twig_Token $token) + { + return $token->test('endautoescape'); + } + + public function getTag() + { + return 'autoescape'; + } +} + +class_alias('Twig_TokenParser_AutoEscape', 'Twig\TokenParser\AutoEscapeTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Block.php b/vendor/twig/twig/lib/Twig/TokenParser/Block.php new file mode 100644 index 0000000..f30f86b --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Block.php @@ -0,0 +1,73 @@ + + * {% block head %} + * + * {% block title %}{% endblock %} - My Webpage + * {% endblock %} + * + * + * @final + */ +class Twig_TokenParser_Block extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + $stream = $this->parser->getStream(); + $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + if ($this->parser->hasBlock($name)) { + throw new Twig_Error_Syntax(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 Twig_Node_Block($name, new Twig_Node(array()), $lineno)); + $this->parser->pushLocalScope(); + $this->parser->pushBlockStack($name); + + if ($stream->nextIf(Twig_Token::BLOCK_END_TYPE)) { + $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true); + if ($token = $stream->nextIf(Twig_Token::NAME_TYPE)) { + $value = $token->getValue(); + + if ($value != $name) { + throw new Twig_Error_Syntax(sprintf('Expected endblock for block "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext()); + } + } + } else { + $body = new Twig_Node(array( + new Twig_Node_Print($this->parser->getExpressionParser()->parseExpression(), $lineno), + )); + } + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + $block->setNode('body', $body); + $this->parser->popBlockStack(); + $this->parser->popLocalScope(); + + return new Twig_Node_BlockReference($name, $lineno, $this->getTag()); + } + + public function decideBlockEnd(Twig_Token $token) + { + return $token->test('endblock'); + } + + public function getTag() + { + return 'block'; + } +} + +class_alias('Twig_TokenParser_Block', 'Twig\TokenParser\BlockTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Deprecated.php b/vendor/twig/twig/lib/Twig/TokenParser/Deprecated.php new file mode 100644 index 0000000..be5d549 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Deprecated.php @@ -0,0 +1,42 @@ + + * {% deprecated 'The "base.twig" template is deprecated, use "layout.twig" instead.' %} + * + * {% extends 'layout.html.twig' %} + * + * + * @author Yonel Ceruto + * + * @final + */ +class Twig_TokenParser_Deprecated extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $expr = $this->parser->getExpressionParser()->parseExpression(); + + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_Deprecated($expr, $token->getLine(), $this->getTag()); + } + + public function getTag() + { + return 'deprecated'; + } +} + +class_alias('Twig_TokenParser_Deprecated', 'Twig\TokenParser\DeprecatedTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Do.php b/vendor/twig/twig/lib/Twig/TokenParser/Do.php new file mode 100644 index 0000000..8ce0880 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Do.php @@ -0,0 +1,34 @@ +parser->getExpressionParser()->parseExpression(); + + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_Do($expr, $token->getLine(), $this->getTag()); + } + + public function getTag() + { + return 'do'; + } +} + +class_alias('Twig_TokenParser_Do', 'Twig\TokenParser\DoTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Embed.php b/vendor/twig/twig/lib/Twig/TokenParser/Embed.php new file mode 100644 index 0000000..44644cc --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Embed.php @@ -0,0 +1,67 @@ +parser->getStream(); + + $parent = $this->parser->getExpressionParser()->parseExpression(); + + list($variables, $only, $ignoreMissing) = $this->parseArguments(); + + $parentToken = $fakeParentToken = new Twig_Token(Twig_Token::STRING_TYPE, '__parent__', $token->getLine()); + if ($parent instanceof Twig_Node_Expression_Constant) { + $parentToken = new Twig_Token(Twig_Token::STRING_TYPE, $parent->getAttribute('value'), $token->getLine()); + } elseif ($parent instanceof Twig_Node_Expression_Name) { + $parentToken = new Twig_Token(Twig_Token::NAME_TYPE, $parent->getAttribute('name'), $token->getLine()); + } + + // inject a fake parent to make the parent() function work + $stream->injectTokens(array( + new Twig_Token(Twig_Token::BLOCK_START_TYPE, '', $token->getLine()), + new Twig_Token(Twig_Token::NAME_TYPE, 'extends', $token->getLine()), + $parentToken, + new Twig_Token(Twig_Token::BLOCK_END_TYPE, '', $token->getLine()), + )); + + $module = $this->parser->parse($stream, array($this, 'decideBlockEnd'), true); + + // override the parent with the correct one + if ($fakeParentToken === $parentToken) { + $module->setNode('parent', $parent); + } + + $this->parser->embedTemplate($module); + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_Embed($module->getTemplateName(), $module->getAttribute('index'), $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag()); + } + + public function decideBlockEnd(Twig_Token $token) + { + return $token->test('endembed'); + } + + public function getTag() + { + return 'embed'; + } +} + +class_alias('Twig_TokenParser_Embed', 'Twig\TokenParser\EmbedTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Extends.php b/vendor/twig/twig/lib/Twig/TokenParser/Extends.php new file mode 100644 index 0000000..31168cc --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Extends.php @@ -0,0 +1,46 @@ + + * {% extends "base.html" %} + * + * + * @final + */ +class Twig_TokenParser_Extends extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $stream = $this->parser->getStream(); + + if (!$this->parser->isMainScope()) { + throw new Twig_Error_Syntax('Cannot extend from a block.', $token->getLine(), $stream->getSourceContext()); + } + + if (null !== $this->parser->getParent()) { + throw new Twig_Error_Syntax('Multiple extends tags are forbidden.', $token->getLine(), $stream->getSourceContext()); + } + $this->parser->setParent($this->parser->getExpressionParser()->parseExpression()); + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + } + + public function getTag() + { + return 'extends'; + } +} + +class_alias('Twig_TokenParser_Extends', 'Twig\TokenParser\ExtendsTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Filter.php b/vendor/twig/twig/lib/Twig/TokenParser/Filter.php new file mode 100644 index 0000000..7601782 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Filter.php @@ -0,0 +1,53 @@ + + * {% filter upper %} + * This text becomes uppercase + * {% endfilter %} + * + * + * @final + */ +class Twig_TokenParser_Filter extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $name = $this->parser->getVarName(); + $ref = new Twig_Node_Expression_BlockReference(new Twig_Node_Expression_Constant($name, $token->getLine()), null, $token->getLine(), $this->getTag()); + + $filter = $this->parser->getExpressionParser()->parseFilterExpressionRaw($ref, $this->getTag()); + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true); + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + $block = new Twig_Node_Block($name, $body, $token->getLine()); + $this->parser->setBlock($name, $block); + + return new Twig_Node_Print($filter, $token->getLine(), $this->getTag()); + } + + public function decideBlockEnd(Twig_Token $token) + { + return $token->test('endfilter'); + } + + public function getTag() + { + return 'filter'; + } +} + +class_alias('Twig_TokenParser_Filter', 'Twig\TokenParser\FilterTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Flush.php b/vendor/twig/twig/lib/Twig/TokenParser/Flush.php new file mode 100644 index 0000000..51832c7 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Flush.php @@ -0,0 +1,34 @@ +parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_Flush($token->getLine(), $this->getTag()); + } + + public function getTag() + { + return 'flush'; + } +} + +class_alias('Twig_TokenParser_Flush', 'Twig\TokenParser\FlushTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/For.php b/vendor/twig/twig/lib/Twig/TokenParser/For.php new file mode 100644 index 0000000..8e737c5 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/For.php @@ -0,0 +1,127 @@ + + *
      + * {% for user in users %} + *
    • {{ user.username|e }}
    • + * {% endfor %} + *
    + * + * + * @final + */ +class Twig_TokenParser_For extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + $stream = $this->parser->getStream(); + $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); + $stream->expect(Twig_Token::OPERATOR_TYPE, 'in'); + $seq = $this->parser->getExpressionParser()->parseExpression(); + + $ifexpr = null; + if ($stream->nextIf(Twig_Token::NAME_TYPE, 'if')) { + $ifexpr = $this->parser->getExpressionParser()->parseExpression(); + } + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideForFork')); + if ('else' == $stream->next()->getValue()) { + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $else = $this->parser->subparse(array($this, 'decideForEnd'), true); + } else { + $else = null; + } + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + if (count($targets) > 1) { + $keyTarget = $targets->getNode(0); + $keyTarget = new Twig_Node_Expression_AssignName($keyTarget->getAttribute('name'), $keyTarget->getTemplateLine()); + $valueTarget = $targets->getNode(1); + $valueTarget = new Twig_Node_Expression_AssignName($valueTarget->getAttribute('name'), $valueTarget->getTemplateLine()); + } else { + $keyTarget = new Twig_Node_Expression_AssignName('_key', $lineno); + $valueTarget = $targets->getNode(0); + $valueTarget = new Twig_Node_Expression_AssignName($valueTarget->getAttribute('name'), $valueTarget->getTemplateLine()); + } + + if ($ifexpr) { + $this->checkLoopUsageCondition($stream, $ifexpr); + $this->checkLoopUsageBody($stream, $body); + } + + return new Twig_Node_For($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, $lineno, $this->getTag()); + } + + public function decideForFork(Twig_Token $token) + { + return $token->test(array('else', 'endfor')); + } + + public function decideForEnd(Twig_Token $token) + { + return $token->test('endfor'); + } + + // the loop variable cannot be used in the condition + protected function checkLoopUsageCondition(Twig_TokenStream $stream, Twig_NodeInterface $node) + { + if ($node instanceof Twig_Node_Expression_GetAttr && $node->getNode('node') instanceof Twig_Node_Expression_Name && 'loop' == $node->getNode('node')->getAttribute('name')) { + throw new Twig_Error_Syntax('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(Twig_TokenStream $stream, Twig_NodeInterface $node) + { + if ($node instanceof Twig_Node_Expression_GetAttr && $node->getNode('node') instanceof Twig_Node_Expression_Name && 'loop' == $node->getNode('node')->getAttribute('name')) { + $attribute = $node->getNode('attribute'); + if ($attribute instanceof Twig_Node_Expression_Constant && in_array($attribute->getAttribute('value'), array('length', 'revindex0', 'revindex', 'last'))) { + throw new Twig_Error_Syntax(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 Twig_Node_For) { + return; + } + + foreach ($node as $n) { + if (!$n) { + continue; + } + + $this->checkLoopUsageBody($stream, $n); + } + } + + public function getTag() + { + return 'for'; + } +} + +class_alias('Twig_TokenParser_For', 'Twig\TokenParser\ForTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/From.php b/vendor/twig/twig/lib/Twig/TokenParser/From.php new file mode 100644 index 0000000..f3053da --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/From.php @@ -0,0 +1,66 @@ + + * {% from 'forms.html' import forms %} + * + * + * @final + */ +class Twig_TokenParser_From extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $macro = $this->parser->getExpressionParser()->parseExpression(); + $stream = $this->parser->getStream(); + $stream->expect('import'); + + $targets = array(); + do { + $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + + $alias = $name; + if ($stream->nextIf('as')) { + $alias = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + } + + $targets[$name] = $alias; + + if (!$stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) { + break; + } + } while (true); + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + $node = new Twig_Node_Import($macro, new Twig_Node_Expression_AssignName($this->parser->getVarName(), $token->getLine()), $token->getLine(), $this->getTag()); + + foreach ($targets as $name => $alias) { + if ($this->parser->isReservedMacroName($name)) { + throw new Twig_Error_Syntax(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, $node->getNode('var')); + } + + return $node; + } + + public function getTag() + { + return 'from'; + } +} + +class_alias('Twig_TokenParser_From', 'Twig\TokenParser\FromTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/If.php b/vendor/twig/twig/lib/Twig/TokenParser/If.php new file mode 100644 index 0000000..f081df3 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/If.php @@ -0,0 +1,86 @@ + + * {% if users %} + *
      + * {% for user in users %} + *
    • {{ user.username|e }}
    • + * {% endfor %} + *
    + * {% endif %} + * + * + * @final + */ +class Twig_TokenParser_If extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + $expr = $this->parser->getExpressionParser()->parseExpression(); + $stream = $this->parser->getStream(); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideIfFork')); + $tests = array($expr, $body); + $else = null; + + $end = false; + while (!$end) { + switch ($stream->next()->getValue()) { + case 'else': + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $else = $this->parser->subparse(array($this, 'decideIfEnd')); + break; + + case 'elseif': + $expr = $this->parser->getExpressionParser()->parseExpression(); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideIfFork')); + $tests[] = $expr; + $tests[] = $body; + break; + + case 'endif': + $end = true; + break; + + default: + throw new Twig_Error_Syntax(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(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_If(new Twig_Node($tests), $else, $lineno, $this->getTag()); + } + + public function decideIfFork(Twig_Token $token) + { + return $token->test(array('elseif', 'else', 'endif')); + } + + public function decideIfEnd(Twig_Token $token) + { + return $token->test(array('endif')); + } + + public function getTag() + { + return 'if'; + } +} + +class_alias('Twig_TokenParser_If', 'Twig\TokenParser\IfTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Import.php b/vendor/twig/twig/lib/Twig/TokenParser/Import.php new file mode 100644 index 0000000..47802f5 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Import.php @@ -0,0 +1,41 @@ + + * {% import 'forms.html' as forms %} + * + * + * @final + */ +class Twig_TokenParser_Import extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $macro = $this->parser->getExpressionParser()->parseExpression(); + $this->parser->getStream()->expect('as'); + $var = new Twig_Node_Expression_AssignName($this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue(), $token->getLine()); + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + $this->parser->addImportedSymbol('template', $var->getAttribute('name')); + + return new Twig_Node_Import($macro, $var, $token->getLine(), $this->getTag()); + } + + public function getTag() + { + return 'import'; + } +} + +class_alias('Twig_TokenParser_Import', 'Twig\TokenParser\ImportTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Include.php b/vendor/twig/twig/lib/Twig/TokenParser/Include.php new file mode 100644 index 0000000..309f11d --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Include.php @@ -0,0 +1,65 @@ + + * {% include 'header.html' %} + * Body + * {% include 'footer.html' %} + * + */ +class Twig_TokenParser_Include extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $expr = $this->parser->getExpressionParser()->parseExpression(); + + list($variables, $only, $ignoreMissing) = $this->parseArguments(); + + return new Twig_Node_Include($expr, $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag()); + } + + protected function parseArguments() + { + $stream = $this->parser->getStream(); + + $ignoreMissing = false; + if ($stream->nextIf(Twig_Token::NAME_TYPE, 'ignore')) { + $stream->expect(Twig_Token::NAME_TYPE, 'missing'); + + $ignoreMissing = true; + } + + $variables = null; + if ($stream->nextIf(Twig_Token::NAME_TYPE, 'with')) { + $variables = $this->parser->getExpressionParser()->parseExpression(); + } + + $only = false; + if ($stream->nextIf(Twig_Token::NAME_TYPE, 'only')) { + $only = true; + } + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + return array($variables, $only, $ignoreMissing); + } + + public function getTag() + { + return 'include'; + } +} + +class_alias('Twig_TokenParser_Include', 'Twig\TokenParser\IncludeTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Macro.php b/vendor/twig/twig/lib/Twig/TokenParser/Macro.php new file mode 100644 index 0000000..4287934 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Macro.php @@ -0,0 +1,60 @@ + + * {% macro input(name, value, type, size) %} + * + * {% endmacro %} + * + * + * @final + */ +class Twig_TokenParser_Macro extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + $stream = $this->parser->getStream(); + $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + + $arguments = $this->parser->getExpressionParser()->parseArguments(true, true); + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $this->parser->pushLocalScope(); + $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true); + if ($token = $stream->nextIf(Twig_Token::NAME_TYPE)) { + $value = $token->getValue(); + + if ($value != $name) { + throw new Twig_Error_Syntax(sprintf('Expected endmacro for macro "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext()); + } + } + $this->parser->popLocalScope(); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + $this->parser->setMacro($name, new Twig_Node_Macro($name, new Twig_Node_Body(array($body)), $arguments, $lineno, $this->getTag())); + } + + public function decideBlockEnd(Twig_Token $token) + { + return $token->test('endmacro'); + } + + public function getTag() + { + return 'macro'; + } +} + +class_alias('Twig_TokenParser_Macro', 'Twig\TokenParser\MacroTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Sandbox.php b/vendor/twig/twig/lib/Twig/TokenParser/Sandbox.php new file mode 100644 index 0000000..7fc70d9 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Sandbox.php @@ -0,0 +1,61 @@ + + * {% sandbox %} + * {% include 'user.html' %} + * {% endsandbox %} + * + * + * @see https://twig.symfony.com/doc/api.html#sandbox-extension for details + * + * @final + */ +class Twig_TokenParser_Sandbox extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $stream = $this->parser->getStream(); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + // in a sandbox tag, only include tags are allowed + if (!$body instanceof Twig_Node_Include) { + foreach ($body as $node) { + if ($node instanceof Twig_Node_Text && ctype_space($node->getAttribute('data'))) { + continue; + } + + if (!$node instanceof Twig_Node_Include) { + throw new Twig_Error_Syntax('Only "include" tags are allowed within a "sandbox" section.', $node->getTemplateLine(), $stream->getSourceContext()); + } + } + } + + return new Twig_Node_Sandbox($body, $token->getLine(), $this->getTag()); + } + + public function decideBlockEnd(Twig_Token $token) + { + return $token->test('endsandbox'); + } + + public function getTag() + { + return 'sandbox'; + } +} + +class_alias('Twig_TokenParser_Sandbox', 'Twig\TokenParser\SandboxTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Set.php b/vendor/twig/twig/lib/Twig/TokenParser/Set.php new file mode 100644 index 0000000..48c6b3a --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Set.php @@ -0,0 +1,75 @@ + + * {% set foo = 'foo' %} + * + * {% set foo = [1, 2] %} + * + * {% set foo = {'foo': 'bar'} %} + * + * {% set foo = 'foo' ~ 'bar' %} + * + * {% set foo, bar = 'foo', 'bar' %} + * + * {% set foo %}Some content{% endset %} + * + * + * @final + */ +class Twig_TokenParser_Set extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + $stream = $this->parser->getStream(); + $names = $this->parser->getExpressionParser()->parseAssignmentExpression(); + + $capture = false; + if ($stream->nextIf(Twig_Token::OPERATOR_TYPE, '=')) { + $values = $this->parser->getExpressionParser()->parseMultitargetExpression(); + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + if (count($names) !== count($values)) { + throw new Twig_Error_Syntax('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 Twig_Error_Syntax('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); + } + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + $values = $this->parser->subparse(array($this, 'decideBlockEnd'), true); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + } + + return new Twig_Node_Set($capture, $names, $values, $lineno, $this->getTag()); + } + + public function decideBlockEnd(Twig_Token $token) + { + return $token->test('endset'); + } + + public function getTag() + { + return 'set'; + } +} + +class_alias('Twig_TokenParser_Set', 'Twig\TokenParser\SetTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Spaceless.php b/vendor/twig/twig/lib/Twig/TokenParser/Spaceless.php new file mode 100644 index 0000000..cecf27c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Spaceless.php @@ -0,0 +1,51 @@ + + * {% spaceless %} + *
    + * foo + *
    + * {% endspaceless %} + * + * {# output will be
    foo
    #} + * + * + * @final + */ +class Twig_TokenParser_Spaceless extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $lineno = $token->getLine(); + + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + $body = $this->parser->subparse(array($this, 'decideSpacelessEnd'), true); + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_Spaceless($body, $lineno, $this->getTag()); + } + + public function decideSpacelessEnd(Twig_Token $token) + { + return $token->test('endspaceless'); + } + + public function getTag() + { + return 'spaceless'; + } +} + +class_alias('Twig_TokenParser_Spaceless', 'Twig\TokenParser\SpacelessTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/Use.php b/vendor/twig/twig/lib/Twig/TokenParser/Use.php new file mode 100644 index 0000000..1ab24e2 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/Use.php @@ -0,0 +1,70 @@ + + * {% extends "base.html" %} + * + * {% use "blocks.html" %} + * + * {% block title %}{% endblock %} + * {% block content %}{% endblock %} + * + * + * @see https://twig.symfony.com/doc/templates.html#horizontal-reuse for details. + * + * @final + */ +class Twig_TokenParser_Use extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $template = $this->parser->getExpressionParser()->parseExpression(); + $stream = $this->parser->getStream(); + + if (!$template instanceof Twig_Node_Expression_Constant) { + throw new Twig_Error_Syntax('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); + } + + $targets = array(); + if ($stream->nextIf('with')) { + do { + $name = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + + $alias = $name; + if ($stream->nextIf('as')) { + $alias = $stream->expect(Twig_Token::NAME_TYPE)->getValue(); + } + + $targets[$name] = new Twig_Node_Expression_Constant($alias, -1); + + if (!$stream->nextIf(Twig_Token::PUNCTUATION_TYPE, ',')) { + break; + } + } while (true); + } + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + $this->parser->addTrait(new Twig_Node(array('template' => $template, 'targets' => new Twig_Node($targets)))); + + return new Twig_Node(); + } + + public function getTag() + { + return 'use'; + } +} + +class_alias('Twig_TokenParser_Use', 'Twig\TokenParser\UseTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParser/With.php b/vendor/twig/twig/lib/Twig/TokenParser/With.php new file mode 100644 index 0000000..7a69259 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParser/With.php @@ -0,0 +1,52 @@ + + * + * @final + */ +class Twig_TokenParser_With extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $stream = $this->parser->getStream(); + + $variables = null; + $only = false; + if (!$stream->test(Twig_Token::BLOCK_END_TYPE)) { + $variables = $this->parser->getExpressionParser()->parseExpression(); + $only = $stream->nextIf(Twig_Token::NAME_TYPE, 'only'); + } + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + $body = $this->parser->subparse(array($this, 'decideWithEnd'), true); + + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_With($body, $variables, $only, $token->getLine(), $this->getTag()); + } + + public function decideWithEnd(Twig_Token $token) + { + return $token->test('endwith'); + } + + public function getTag() + { + return 'with'; + } +} + +class_alias('Twig_TokenParser_With', 'Twig\TokenParser\WithTokenParser', false); diff --git a/vendor/twig/twig/lib/Twig/TokenParserBroker.php b/vendor/twig/twig/lib/Twig/TokenParserBroker.php new file mode 100644 index 0000000..0d7d6e5 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParserBroker.php @@ -0,0 +1,120 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +class Twig_TokenParserBroker implements Twig_TokenParserBrokerInterface +{ + protected $parser; + protected $parsers = array(); + protected $brokers = array(); + + /** + * @param array|Traversable $parsers A Traversable of Twig_TokenParserInterface instances + * @param array|Traversable $brokers A Traversable of Twig_TokenParserBrokerInterface instances + * @param bool $triggerDeprecationError + */ + public function __construct($parsers = array(), $brokers = array(), $triggerDeprecationError = true) + { + if ($triggerDeprecationError) { + @trigger_error('The '.__CLASS__.' class is deprecated since version 1.12 and will be removed in 2.0.', E_USER_DEPRECATED); + } + + foreach ($parsers as $parser) { + if (!$parser instanceof Twig_TokenParserInterface) { + throw new LogicException('$parsers must a an array of Twig_TokenParserInterface.'); + } + $this->parsers[$parser->getTag()] = $parser; + } + foreach ($brokers as $broker) { + if (!$broker instanceof Twig_TokenParserBrokerInterface) { + throw new LogicException('$brokers must a an array of Twig_TokenParserBrokerInterface.'); + } + $this->brokers[] = $broker; + } + } + + public function addTokenParser(Twig_TokenParserInterface $parser) + { + $this->parsers[$parser->getTag()] = $parser; + } + + public function removeTokenParser(Twig_TokenParserInterface $parser) + { + $name = $parser->getTag(); + if (isset($this->parsers[$name]) && $parser === $this->parsers[$name]) { + unset($this->parsers[$name]); + } + } + + public function addTokenParserBroker(self $broker) + { + $this->brokers[] = $broker; + } + + public function removeTokenParserBroker(self $broker) + { + if (false !== $pos = array_search($broker, $this->brokers)) { + unset($this->brokers[$pos]); + } + } + + /** + * Gets a suitable TokenParser for a tag. + * + * First looks in parsers, then in brokers. + * + * @param string $tag A tag name + * + * @return null|Twig_TokenParserInterface A Twig_TokenParserInterface or null if no suitable TokenParser was found + */ + public function getTokenParser($tag) + { + if (isset($this->parsers[$tag])) { + return $this->parsers[$tag]; + } + $broker = end($this->brokers); + while (false !== $broker) { + $parser = $broker->getTokenParser($tag); + if (null !== $parser) { + return $parser; + } + $broker = prev($this->brokers); + } + } + + public function getParsers() + { + return $this->parsers; + } + + public function getParser() + { + return $this->parser; + } + + public function setParser(Twig_ParserInterface $parser) + { + $this->parser = $parser; + foreach ($this->parsers as $tokenParser) { + $tokenParser->setParser($parser); + } + foreach ($this->brokers as $broker) { + $broker->setParser($parser); + } + } +} diff --git a/vendor/twig/twig/lib/Twig/TokenParserBrokerInterface.php b/vendor/twig/twig/lib/Twig/TokenParserBrokerInterface.php new file mode 100644 index 0000000..6c93f5e --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParserBrokerInterface.php @@ -0,0 +1,44 @@ + + * + * @deprecated since 1.12 (to be removed in 2.0) + */ +interface Twig_TokenParserBrokerInterface +{ + /** + * Gets a TokenParser suitable for a tag. + * + * @param string $tag A tag name + * + * @return Twig_TokenParserInterface|null A Twig_TokenParserInterface or null if no suitable TokenParser was found + */ + public function getTokenParser($tag); + + /** + * Calls Twig_TokenParserInterface::setParser on all parsers the implementation knows of. + */ + public function setParser(Twig_ParserInterface $parser); + + /** + * Gets the Twig_ParserInterface. + * + * @return null|Twig_ParserInterface A Twig_ParserInterface instance or null + */ + public function getParser(); +} diff --git a/vendor/twig/twig/lib/Twig/TokenParserInterface.php b/vendor/twig/twig/lib/Twig/TokenParserInterface.php new file mode 100644 index 0000000..14acc80 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenParserInterface.php @@ -0,0 +1,43 @@ + + */ +interface Twig_TokenParserInterface +{ + /** + * Sets the parser associated with this token parser. + */ + public function setParser(Twig_Parser $parser); + + /** + * Parses a token and returns a node. + * + * @return Twig_NodeInterface + * + * @throws Twig_Error_Syntax + */ + public function parse(Twig_Token $token); + + /** + * Gets the tag name associated with this token parser. + * + * @return string The tag name + */ + public function getTag(); +} + +class_alias('Twig_TokenParserInterface', 'Twig\TokenParser\TokenParserInterface', false); +class_exists('Twig_Parser'); +class_exists('Twig_Token'); diff --git a/vendor/twig/twig/lib/Twig/TokenStream.php b/vendor/twig/twig/lib/Twig/TokenStream.php new file mode 100644 index 0000000..81c043c --- /dev/null +++ b/vendor/twig/twig/lib/Twig/TokenStream.php @@ -0,0 +1,196 @@ + + */ +class Twig_TokenStream +{ + protected $tokens; + protected $current = 0; + protected $filename; + + private $source; + + /** + * @param array $tokens An array of tokens + * @param string|null $name The name of the template which tokens are associated with + * @param string|null $source The source code associated with the tokens + */ + public function __construct(array $tokens, $name = null, $source = null) + { + 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); + } + $this->source = new Twig_Source($source, $name); + } else { + $this->source = $name; + } + + $this->tokens = $tokens; + + // deprecated, not used anymore, to be removed in 2.0 + $this->filename = $this->source->getName(); + } + + public function __toString() + { + return implode("\n", $this->tokens); + } + + public function injectTokens(array $tokens) + { + $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 Twig_Token + */ + public function next() + { + if (!isset($this->tokens[++$this->current])) { + throw new Twig_Error_Syntax('Unexpected end of template.', $this->tokens[$this->current - 1]->getLine(), $this->source); + } + + return $this->tokens[$this->current - 1]; + } + + /** + * Tests a token, sets the pointer to the next one and returns it or throws a syntax error. + * + * @return Twig_Token|null The next token if the condition is true, null otherwise + */ + public function nextIf($primary, $secondary = null) + { + if ($this->tokens[$this->current]->test($primary, $secondary)) { + return $this->next(); + } + } + + /** + * Tests a token and returns it or throws a syntax error. + * + * @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 Twig_Error_Syntax(sprintf('%sUnexpected token "%s" of value "%s" ("%s" expected%s).', + $message ? $message.'. ' : '', + Twig_Token::typeToEnglish($token->getType()), $token->getValue(), + Twig_Token::typeToEnglish($type), $value ? sprintf(' with value "%s"', $value) : ''), + $line, + $this->source + ); + } + $this->next(); + + return $token; + } + + /** + * Looks at the next token. + * + * @param int $number + * + * @return Twig_Token + */ + public function look($number = 1) + { + if (!isset($this->tokens[$this->current + $number])) { + throw new Twig_Error_Syntax('Unexpected end of template.', $this->tokens[$this->current + $number - 1]->getLine(), $this->source); + } + + return $this->tokens[$this->current + $number]; + } + + /** + * Tests the current token. + * + * @return bool + */ + public function test($primary, $secondary = null) + { + return $this->tokens[$this->current]->test($primary, $secondary); + } + + /** + * Checks if end of stream was reached. + * + * @return bool + */ + public function isEOF() + { + return Twig_Token::EOF_TYPE === $this->tokens[$this->current]->getType(); + } + + /** + * @return Twig_Token + */ + public function getCurrent() + { + return $this->tokens[$this->current]; + } + + /** + * Gets the name associated with this stream (null if not defined). + * + * @return string|null + * + * @deprecated since 1.27 (to be removed in 2.0) + */ + public function getFilename() + { + @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->source->getName(); + } + + /** + * Gets the source code associated with this stream. + * + * @return string + * + * @internal Don't use this as it might be empty depending on the environment configuration + * + * @deprecated since 1.27 (to be removed in 2.0) + */ + public function getSource() + { + @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->source->getCode(); + } + + /** + * Gets the source associated with this stream. + * + * @return Twig_Source + * + * @internal + */ + public function getSourceContext() + { + return $this->source; + } +} + +class_alias('Twig_TokenStream', 'Twig\TokenStream', false); diff --git a/vendor/twig/twig/lib/Twig/Util/DeprecationCollector.php b/vendor/twig/twig/lib/Twig/Util/DeprecationCollector.php new file mode 100644 index 0000000..c7bf53b --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Util/DeprecationCollector.php @@ -0,0 +1,86 @@ + + * + * @final + */ +class Twig_Util_DeprecationCollector +{ + private $twig; + private $deprecations; + + public function __construct(Twig_Environment $twig) + { + $this->twig = $twig; + } + + /** + * Returns deprecations for templates contained in a directory. + * + * @param string $dir A directory where templates are stored + * @param string $ext Limit the loaded templates by extension + * + * @return array An array of deprecations + */ + public function collectDir($dir, $ext = '.twig') + { + $iterator = new RegexIterator( + new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($dir), RecursiveIteratorIterator::LEAVES_ONLY + ), '{'.preg_quote($ext).'$}' + ); + + 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) + * + * @return array An array of deprecations + */ + public function collect(Traversable $iterator) + { + $this->deprecations = array(); + + set_error_handler(array($this, 'errorHandler')); + + foreach ($iterator as $name => $contents) { + try { + $this->twig->parse($this->twig->tokenize(new Twig_Source($contents, $name))); + } catch (Twig_Error_Syntax $e) { + // ignore templates containing syntax errors + } + } + + restore_error_handler(); + + $deprecations = $this->deprecations; + $this->deprecations = array(); + + return $deprecations; + } + + /** + * @internal + */ + public function errorHandler($type, $msg) + { + if (E_USER_DEPRECATED === $type) { + $this->deprecations[] = $msg; + } + } +} + +class_alias('Twig_Util_DeprecationCollector', 'Twig\Util\DeprecationCollector', false); diff --git a/vendor/twig/twig/lib/Twig/Util/TemplateDirIterator.php b/vendor/twig/twig/lib/Twig/Util/TemplateDirIterator.php new file mode 100644 index 0000000..c868233 --- /dev/null +++ b/vendor/twig/twig/lib/Twig/Util/TemplateDirIterator.php @@ -0,0 +1,28 @@ + + */ +class Twig_Util_TemplateDirIterator extends IteratorIterator +{ + public function current() + { + return file_get_contents(parent::current()); + } + + public function key() + { + return (string) parent::key(); + } +} + +class_alias('Twig_Util_TemplateDirIterator', 'Twig\Util\TemplateDirIterator', false); diff --git a/vendor/twig/twig/phpunit.xml.dist b/vendor/twig/twig/phpunit.xml.dist new file mode 100644 index 0000000..ce77327 --- /dev/null +++ b/vendor/twig/twig/phpunit.xml.dist @@ -0,0 +1,33 @@ + + + + + + ./test/Twig/ + + + + + + + + + + + + + + ./lib/Twig/ + + + diff --git a/vendor/twig/twig/src/Cache/CacheInterface.php b/vendor/twig/twig/src/Cache/CacheInterface.php new file mode 100644 index 0000000..2e35e3b --- /dev/null +++ b/vendor/twig/twig/src/Cache/CacheInterface.php @@ -0,0 +1,11 @@ + + */ +interface RuntimeExtensionInterface +{ +} diff --git a/vendor/twig/twig/src/Extension/SandboxExtension.php b/vendor/twig/twig/src/Extension/SandboxExtension.php new file mode 100644 index 0000000..0c244ff --- /dev/null +++ b/vendor/twig/twig/src/Extension/SandboxExtension.php @@ -0,0 +1,11 @@ +assertFalse(class_exists('FooBarFoo'), '->autoload() does not try to load classes that does not begin with Twig'); + + $autoloader = new Twig_Autoloader(); + $this->assertNull($autoloader->autoload('Foo'), '->autoload() returns false if it is not able to load a class'); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Cache/FilesystemTest.php b/vendor/twig/twig/test/Twig/Tests/Cache/FilesystemTest.php new file mode 100644 index 0000000..e9e600c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Cache/FilesystemTest.php @@ -0,0 +1,193 @@ +classname = '__Twig_Tests_Cache_FilesystemTest_Template_'.$nonce; + $this->directory = sys_get_temp_dir().'/twig-test'; + $this->cache = new Twig_Cache_Filesystem($this->directory); + } + + protected function tearDown() + { + if (file_exists($this->directory)) { + Twig_Tests_FilesystemHelper::removeDir($this->directory); + } + } + + public function testLoad() + { + $key = $this->directory.'/cache/cachefile.php'; + + $dir = dirname($key); + @mkdir($dir, 0777, true); + $this->assertTrue(is_dir($dir)); + $this->assertFalse(class_exists($this->classname, false)); + + $content = $this->generateSource(); + file_put_contents($key, $content); + + $this->cache->load($key); + + $this->assertTrue(class_exists($this->classname, false)); + } + + public function testLoadMissing() + { + $key = $this->directory.'/cache/cachefile.php'; + + $this->assertFalse(class_exists($this->classname, false)); + + $this->cache->load($key); + + $this->assertFalse(class_exists($this->classname, false)); + } + + public function testWrite() + { + $key = $this->directory.'/cache/cachefile.php'; + $content = $this->generateSource(); + + $this->assertFileNotExists($key); + $this->assertFileNotExists($this->directory); + + $this->cache->write($key, $content); + + $this->assertFileExists($this->directory); + $this->assertFileExists($key); + $this->assertSame(file_get_contents($key), $content); + } + + /** + * @expectedException RuntimeException + * @expectedExceptionMessage Unable to create the cache directory + */ + public function testWriteFailMkdir() + { + if (defined('PHP_WINDOWS_VERSION_BUILD')) { + $this->markTestSkipped('Read-only directories not possible on Windows.'); + } + + $key = $this->directory.'/cache/cachefile.php'; + $content = $this->generateSource(); + + $this->assertFileNotExists($key); + + // Create read-only root directory. + @mkdir($this->directory, 0555, true); + $this->assertTrue(is_dir($this->directory)); + + $this->cache->write($key, $content); + } + + /** + * @expectedException RuntimeException + * @expectedExceptionMessage Unable to write in the cache directory + */ + public function testWriteFailDirWritable() + { + if (defined('PHP_WINDOWS_VERSION_BUILD')) { + $this->markTestSkipped('Read-only directories not possible on Windows.'); + } + + $key = $this->directory.'/cache/cachefile.php'; + $content = $this->generateSource(); + + $this->assertFileNotExists($key); + + // Create root directory. + @mkdir($this->directory, 0777, true); + // Create read-only subdirectory. + @mkdir($this->directory.'/cache', 0555); + $this->assertTrue(is_dir($this->directory.'/cache')); + + $this->cache->write($key, $content); + } + + /** + * @expectedException RuntimeException + * @expectedExceptionMessage Failed to write cache file + */ + public function testWriteFailWriteFile() + { + $key = $this->directory.'/cache/cachefile.php'; + $content = $this->generateSource(); + + $this->assertFileNotExists($key); + + // Create a directory in the place of the cache file. + @mkdir($key, 0777, true); + $this->assertTrue(is_dir($key)); + + $this->cache->write($key, $content); + } + + public function testGetTimestamp() + { + $key = $this->directory.'/cache/cachefile.php'; + + $dir = dirname($key); + @mkdir($dir, 0777, true); + $this->assertTrue(is_dir($dir)); + + // Create the file with a specific modification time. + touch($key, 1234567890); + + $this->assertSame(1234567890, $this->cache->getTimestamp($key)); + } + + public function testGetTimestampMissingFile() + { + $key = $this->directory.'/cache/cachefile.php'; + $this->assertSame(0, $this->cache->getTimestamp($key)); + } + + /** + * Test file cache is tolerant towards trailing (back)slashes on the configured cache directory. + * + * @dataProvider provideDirectories + */ + public function testGenerateKey($expected, $input) + { + $cache = new Twig_Cache_Filesystem($input); + $this->assertRegExp($expected, $cache->generateKey('_test_', get_class($this))); + } + + public function provideDirectories() + { + $pattern = '#a/b/[a-zA-Z0-9]+/[a-zA-Z0-9]+.php$#'; + + return array( + array($pattern, 'a/b'), + array($pattern, 'a/b/'), + array($pattern, 'a/b\\'), + array($pattern, 'a/b\\/'), + array($pattern, 'a/b\\//'), + array('#/'.substr($pattern, 1), '/a/b'), + ); + } + + private function generateSource() + { + return strtr(' $this->classname, + )); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/CompilerTest.php b/vendor/twig/twig/test/Twig/Tests/CompilerTest.php new file mode 100644 index 0000000..4d4b8df --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/CompilerTest.php @@ -0,0 +1,33 @@ +getMockBuilder('Twig_LoaderInterface')->getMock())); + + $locale = setlocale(LC_NUMERIC, 0); + if (false === $locale) { + $this->markTestSkipped('Your platform does not support locales.'); + } + + $required_locales = array('fr_FR.UTF-8', 'fr_FR.UTF8', 'fr_FR.utf-8', 'fr_FR.utf8', 'French_France.1252'); + if (false === setlocale(LC_NUMERIC, $required_locales)) { + $this->markTestSkipped('Could not set any of required locales: '.implode(', ', $required_locales)); + } + + $this->assertEquals('1.2', $compiler->repr(1.2)->getSource()); + $this->assertContains('fr', strtolower(setlocale(LC_NUMERIC, 0))); + + setlocale(LC_NUMERIC, $locale); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/ContainerRuntimeLoaderTest.php b/vendor/twig/twig/test/Twig/Tests/ContainerRuntimeLoaderTest.php new file mode 100644 index 0000000..c111f92 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/ContainerRuntimeLoaderTest.php @@ -0,0 +1,40 @@ +getMockBuilder('Psr\Container\ContainerInterface')->getMock(); + $container->expects($this->once())->method('has')->with('stdClass')->willReturn(true); + $container->expects($this->once())->method('get')->with('stdClass')->willReturn(new stdClass()); + + $loader = new Twig_ContainerRuntimeLoader($container); + + $this->assertInstanceOf('stdClass', $loader->load('stdClass')); + } + + /** + * @requires PHP 5.3 + */ + public function testLoadUnknownRuntimeReturnsNull() + { + $container = $this->getMockBuilder('Psr\Container\ContainerInterface')->getMock(); + $container->expects($this->once())->method('has')->with('Foo'); + $container->expects($this->never())->method('get'); + + $loader = new Twig_ContainerRuntimeLoader($container); + $this->assertNull($loader->load('Foo')); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/CustomExtensionTest.php b/vendor/twig/twig/test/Twig/Tests/CustomExtensionTest.php new file mode 100644 index 0000000..f9d44fd --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/CustomExtensionTest.php @@ -0,0 +1,93 @@ +expectException('InvalidArgumentException'); + $this->expectExceptionMessage($expectedExceptionMessage); + } else { + $this->setExpectedException('InvalidArgumentException', $expectedExceptionMessage); + } + + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $env->addExtension($extension); + $env->getUnaryOperators(); + } + + public function provideInvalidExtensions() + { + return array( + array(new InvalidOperatorExtension(new stdClass()), '"InvalidOperatorExtension::getOperators()" must return an array with operators, got "stdClass".'), + array(new InvalidOperatorExtension(array(1, 2, 3)), '"InvalidOperatorExtension::getOperators()" must return an array of 2 elements, got 3.'), + ); + } +} + +class InvalidOperatorExtension implements Twig_ExtensionInterface +{ + private $operators; + + public function __construct($operators) + { + $this->operators = $operators; + } + + public function initRuntime(Twig_Environment $environment) + { + } + + public function getTokenParsers() + { + return array(); + } + + public function getNodeVisitors() + { + return array(); + } + + public function getFilters() + { + return array(); + } + + public function getTests() + { + return array(); + } + + public function getFunctions() + { + return array(); + } + + public function getGlobals() + { + return array(); + } + + public function getOperators() + { + return $this->operators; + } + + public function getName() + { + return __CLASS__; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/EnvironmentTest.php b/vendor/twig/twig/test/Twig/Tests/EnvironmentTest.php new file mode 100644 index 0000000..dd8dac9 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/EnvironmentTest.php @@ -0,0 +1,686 @@ +tokenize('{{ foo }}', 'foo'); + $this->assertEquals('{{ foo }}', $stream->getSource()); + $this->assertEquals('foo', $stream->getFilename()); + } + + /** + * @group legacy + */ + public function testLegacyCompileSourceSignature() + { + $loader = new Twig_Loader_Array(array('foo' => '{{ foo }}')); + $env = new Twig_Environment($loader); + $this->assertContains('getTemplateName', $env->compileSource('{{ foo }}', 'foo')); + } + + /** + * @expectedException LogicException + * @expectedExceptionMessage You must set a loader first. + * @group legacy + */ + public function testRenderNoLoader() + { + $env = new Twig_Environment(); + $env->render('test'); + } + + public function testAutoescapeOption() + { + $loader = new Twig_Loader_Array(array( + 'html' => '{{ foo }} {{ foo }}', + 'js' => '{{ bar }} {{ bar }}', + )); + + $twig = new Twig_Environment($loader, array( + 'debug' => true, + 'cache' => false, + 'autoescape' => array($this, 'escapingStrategyCallback'), + )); + + $this->assertEquals('foo<br/ > foo<br/ >', $twig->render('html', array('foo' => 'foo
    '))); + $this->assertEquals('foo\u003Cbr\/\u0020\u003E foo\u003Cbr\/\u0020\u003E', $twig->render('js', array('bar' => 'foo
    '))); + } + + public function escapingStrategyCallback($name) + { + return $name; + } + + public function testGlobals() + { + // to be removed in 2.0 + $loader = $this->getMockBuilder('Twig_EnvironmentTestLoaderInterface')->getMock(); + //$loader = $this->getMockBuilder(array('Twig_LoaderInterface', 'Twig_SourceContextLoaderInterface'))->getMock(); + $loader->expects($this->any())->method('getSourceContext')->will($this->returnValue(new Twig_Source('', ''))); + + // globals can be added after calling getGlobals + + $twig = new Twig_Environment($loader); + $twig->addGlobal('foo', 'foo'); + $twig->getGlobals(); + $twig->addGlobal('foo', 'bar'); + $globals = $twig->getGlobals(); + $this->assertEquals('bar', $globals['foo']); + + // globals can be modified after a template has been loaded + $twig = new Twig_Environment($loader); + $twig->addGlobal('foo', 'foo'); + $twig->getGlobals(); + $twig->loadTemplate('index'); + $twig->addGlobal('foo', 'bar'); + $globals = $twig->getGlobals(); + $this->assertEquals('bar', $globals['foo']); + + // globals can be modified after extensions init + $twig = new Twig_Environment($loader); + $twig->addGlobal('foo', 'foo'); + $twig->getGlobals(); + $twig->getFunctions(); + $twig->addGlobal('foo', 'bar'); + $globals = $twig->getGlobals(); + $this->assertEquals('bar', $globals['foo']); + + // globals can be modified after extensions and a template has been loaded + $arrayLoader = new Twig_Loader_Array(array('index' => '{{foo}}')); + $twig = new Twig_Environment($arrayLoader); + $twig->addGlobal('foo', 'foo'); + $twig->getGlobals(); + $twig->getFunctions(); + $twig->loadTemplate('index'); + $twig->addGlobal('foo', 'bar'); + $globals = $twig->getGlobals(); + $this->assertEquals('bar', $globals['foo']); + + $twig = new Twig_Environment($arrayLoader); + $twig->getGlobals(); + $twig->addGlobal('foo', 'bar'); + $template = $twig->loadTemplate('index'); + $this->assertEquals('bar', $template->render(array())); + + /* to be uncomment in Twig 2.0 + // globals cannot be added after a template has been loaded + $twig = new Twig_Environment($loader); + $twig->addGlobal('foo', 'foo'); + $twig->getGlobals(); + $twig->loadTemplate('index'); + try { + $twig->addGlobal('bar', 'bar'); + $this->fail(); + } catch (LogicException $e) { + $this->assertFalse(array_key_exists('bar', $twig->getGlobals())); + } + + // globals cannot be added after extensions init + $twig = new Twig_Environment($loader); + $twig->addGlobal('foo', 'foo'); + $twig->getGlobals(); + $twig->getFunctions(); + try { + $twig->addGlobal('bar', 'bar'); + $this->fail(); + } catch (LogicException $e) { + $this->assertFalse(array_key_exists('bar', $twig->getGlobals())); + } + + // globals cannot be added after extensions and a template has been loaded + $twig = new Twig_Environment($loader); + $twig->addGlobal('foo', 'foo'); + $twig->getGlobals(); + $twig->getFunctions(); + $twig->loadTemplate('index'); + try { + $twig->addGlobal('bar', 'bar'); + $this->fail(); + } catch (LogicException $e) { + $this->assertFalse(array_key_exists('bar', $twig->getGlobals())); + } + + // test adding globals after a template has been loaded without call to getGlobals + $twig = new Twig_Environment($loader); + $twig->loadTemplate('index'); + try { + $twig->addGlobal('bar', 'bar'); + $this->fail(); + } catch (LogicException $e) { + $this->assertFalse(array_key_exists('bar', $twig->getGlobals())); + } + */ + } + + public function testExtensionsAreNotInitializedWhenRenderingACompiledTemplate() + { + $cache = new Twig_Cache_Filesystem($dir = sys_get_temp_dir().'/twig'); + $options = array('cache' => $cache, 'auto_reload' => false, 'debug' => false); + + // force compilation + $twig = new Twig_Environment($loader = new Twig_Loader_Array(array('index' => '{{ foo }}')), $options); + + $key = $cache->generateKey('index', $twig->getTemplateClass('index')); + $cache->write($key, $twig->compileSource(new Twig_Source('{{ foo }}', 'index'))); + + // check that extensions won't be initialized when rendering a template that is already in the cache + $twig = $this + ->getMockBuilder('Twig_Environment') + ->setConstructorArgs(array($loader, $options)) + ->setMethods(array('initExtensions')) + ->getMock() + ; + + $twig->expects($this->never())->method('initExtensions'); + + // render template + $output = $twig->render('index', array('foo' => 'bar')); + $this->assertEquals('bar', $output); + + Twig_Tests_FilesystemHelper::removeDir($dir); + } + + public function testAutoReloadCacheMiss() + { + $templateName = __FUNCTION__; + $templateContent = __FUNCTION__; + + $cache = $this->getMockBuilder('Twig_CacheInterface')->getMock(); + $loader = $this->getMockLoader($templateName, $templateContent); + $twig = new Twig_Environment($loader, array('cache' => $cache, 'auto_reload' => true, 'debug' => false)); + + // Cache miss: getTimestamp returns 0 and as a result the load() is + // skipped. + $cache->expects($this->once()) + ->method('generateKey') + ->will($this->returnValue('key')); + $cache->expects($this->once()) + ->method('getTimestamp') + ->will($this->returnValue(0)); + $loader->expects($this->never()) + ->method('isFresh'); + $cache->expects($this->once()) + ->method('write'); + $cache->expects($this->once()) + ->method('load'); + + $twig->loadTemplate($templateName); + } + + public function testAutoReloadCacheHit() + { + $templateName = __FUNCTION__; + $templateContent = __FUNCTION__; + + $cache = $this->getMockBuilder('Twig_CacheInterface')->getMock(); + $loader = $this->getMockLoader($templateName, $templateContent); + $twig = new Twig_Environment($loader, array('cache' => $cache, 'auto_reload' => true, 'debug' => false)); + + $now = time(); + + // Cache hit: getTimestamp returns something > extension timestamps and + // the loader returns true for isFresh(). + $cache->expects($this->once()) + ->method('generateKey') + ->will($this->returnValue('key')); + $cache->expects($this->once()) + ->method('getTimestamp') + ->will($this->returnValue($now)); + $loader->expects($this->once()) + ->method('isFresh') + ->will($this->returnValue(true)); + $cache->expects($this->atLeastOnce()) + ->method('load'); + + $twig->loadTemplate($templateName); + } + + public function testAutoReloadOutdatedCacheHit() + { + $templateName = __FUNCTION__; + $templateContent = __FUNCTION__; + + $cache = $this->getMockBuilder('Twig_CacheInterface')->getMock(); + $loader = $this->getMockLoader($templateName, $templateContent); + $twig = new Twig_Environment($loader, array('cache' => $cache, 'auto_reload' => true, 'debug' => false)); + + $now = time(); + + $cache->expects($this->once()) + ->method('generateKey') + ->will($this->returnValue('key')); + $cache->expects($this->once()) + ->method('getTimestamp') + ->will($this->returnValue($now)); + $loader->expects($this->once()) + ->method('isFresh') + ->will($this->returnValue(false)); + $cache->expects($this->once()) + ->method('write'); + $cache->expects($this->once()) + ->method('load'); + + $twig->loadTemplate($templateName); + } + + /** + * @group legacy + */ + public function testHasGetExtensionWithDynamicName() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + + $ext1 = new Twig_Tests_EnvironmentTest_Extension_DynamicWithDeprecatedName('ext1'); + $ext2 = new Twig_Tests_EnvironmentTest_Extension_DynamicWithDeprecatedName('ext2'); + $twig->addExtension($ext1); + $twig->addExtension($ext2); + + $this->assertTrue($twig->hasExtension('ext1')); + $this->assertTrue($twig->hasExtension('ext2')); + + $this->assertTrue($twig->hasExtension('Twig_Tests_EnvironmentTest_Extension_DynamicWithDeprecatedName')); + + $this->assertSame($ext1, $twig->getExtension('ext1')); + $this->assertSame($ext2, $twig->getExtension('ext2')); + } + + public function testHasGetExtensionByClassName() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addExtension($ext = new Twig_Tests_EnvironmentTest_Extension()); + $this->assertTrue($twig->hasExtension('Twig_Tests_EnvironmentTest_Extension')); + $this->assertTrue($twig->hasExtension('\Twig_Tests_EnvironmentTest_Extension')); + + $this->assertSame($ext, $twig->getExtension('Twig_Tests_EnvironmentTest_Extension')); + $this->assertSame($ext, $twig->getExtension('\Twig_Tests_EnvironmentTest_Extension')); + + $this->assertTrue($twig->hasExtension('Twig\Tests\EnvironmentTest\Extension')); + $this->assertSame($ext, $twig->getExtension('Twig\Tests\EnvironmentTest\Extension')); + } + + public function testAddExtension() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension()); + + $this->assertArrayHasKey('test', $twig->getTags()); + $this->assertArrayHasKey('foo_filter', $twig->getFilters()); + $this->assertArrayHasKey('foo_function', $twig->getFunctions()); + $this->assertArrayHasKey('foo_test', $twig->getTests()); + $this->assertArrayHasKey('foo_unary', $twig->getUnaryOperators()); + $this->assertArrayHasKey('foo_binary', $twig->getBinaryOperators()); + $this->assertArrayHasKey('foo_global', $twig->getGlobals()); + $visitors = $twig->getNodeVisitors(); + $found = false; + foreach ($visitors as $visitor) { + if ($visitor instanceof Twig_Tests_EnvironmentTest_NodeVisitor) { + $found = true; + } + } + $this->assertTrue($found); + } + + /** + * @requires PHP 5.3 + */ + public function testAddExtensionWithDeprecatedGetGlobals() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension_WithGlobals()); + + $this->deprecations = array(); + set_error_handler(array($this, 'handleError')); + + $this->assertArrayHasKey('foo_global', $twig->getGlobals()); + + $this->assertCount(1, $this->deprecations); + $this->assertContains('Defining the getGlobals() method in the "Twig_Tests_EnvironmentTest_Extension_WithGlobals" extension ', $this->deprecations[0]); + + restore_error_handler(); + } + + /** + * @group legacy + */ + public function testRemoveExtension() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName()); + $twig->removeExtension('environment_test'); + + $this->assertArrayNotHasKey('test', $twig->getTags()); + $this->assertArrayNotHasKey('foo_filter', $twig->getFilters()); + $this->assertArrayNotHasKey('foo_function', $twig->getFunctions()); + $this->assertArrayNotHasKey('foo_test', $twig->getTests()); + $this->assertArrayNotHasKey('foo_unary', $twig->getUnaryOperators()); + $this->assertArrayNotHasKey('foo_binary', $twig->getBinaryOperators()); + $this->assertArrayNotHasKey('foo_global', $twig->getGlobals()); + $this->assertCount(2, $twig->getNodeVisitors()); + } + + public function testAddMockExtension() + { + // should be replaced by the following in 2.0 (this current code is just to avoid a dep notice) + // $extension = $this->getMockBuilder('Twig_Extension')->getMock(); + $extension = eval(<< 'hey')); + + $twig = new Twig_Environment($loader); + $twig->addExtension($extension); + + $this->assertInstanceOf('Twig_ExtensionInterface', $twig->getExtension(get_class($extension))); + $this->assertTrue($twig->isTemplateFresh('page', time())); + } + + public function testInitRuntimeWithAnExtensionUsingInitRuntimeNoDeprecation() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addExtension(new Twig_Tests_EnvironmentTest_ExtensionWithoutDeprecationInitRuntime()); + $twig->initRuntime(); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any deprecations + $this->addToAssertionCount(1); + } + + /** + * @requires PHP 5.3 + */ + public function testInitRuntimeWithAnExtensionUsingInitRuntimeDeprecation() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addExtension(new Twig_Tests_EnvironmentTest_ExtensionWithDeprecationInitRuntime()); + + $this->deprecations = array(); + set_error_handler(array($this, 'handleError')); + + $twig->initRuntime(); + + $this->assertCount(1, $this->deprecations); + $this->assertContains('Defining the initRuntime() method in the "Twig_Tests_EnvironmentTest_ExtensionWithDeprecationInitRuntime" extension is deprecated since version 1.23.', $this->deprecations[0]); + + restore_error_handler(); + } + + public function handleError($type, $msg) + { + if (E_USER_DEPRECATED === $type) { + $this->deprecations[] = $msg; + } + } + + /** + * @requires PHP 5.3 + */ + public function testOverrideExtension() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addExtension(new Twig_Tests_EnvironmentTest_ExtensionWithDeprecationInitRuntime()); + + $this->deprecations = array(); + set_error_handler(array($this, 'handleError')); + + $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName()); + $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName()); + + $this->assertCount(1, $this->deprecations); + $this->assertContains('The possibility to register the same extension twice', $this->deprecations[0]); + + restore_error_handler(); + } + + public function testAddRuntimeLoader() + { + $runtimeLoader = $this->getMockBuilder('Twig_RuntimeLoaderInterface')->getMock(); + $runtimeLoader->expects($this->any())->method('load')->will($this->returnValue(new Twig_Tests_EnvironmentTest_Runtime())); + + $loader = new Twig_Loader_Array(array( + 'func_array' => '{{ from_runtime_array("foo") }}', + 'func_array_default' => '{{ from_runtime_array() }}', + 'func_array_named_args' => '{{ from_runtime_array(name="foo") }}', + 'func_string' => '{{ from_runtime_string("foo") }}', + 'func_string_default' => '{{ from_runtime_string() }}', + 'func_string_named_args' => '{{ from_runtime_string(name="foo") }}', + )); + + $twig = new Twig_Environment($loader); + $twig->addExtension(new Twig_Tests_EnvironmentTest_ExtensionWithoutRuntime()); + $twig->addRuntimeLoader($runtimeLoader); + + $this->assertEquals('foo', $twig->render('func_array')); + $this->assertEquals('bar', $twig->render('func_array_default')); + $this->assertEquals('foo', $twig->render('func_array_named_args')); + $this->assertEquals('foo', $twig->render('func_string')); + $this->assertEquals('bar', $twig->render('func_string_default')); + $this->assertEquals('foo', $twig->render('func_string_named_args')); + } + + /** + * @expectedException Twig_Error_Runtime + * @expectedExceptionMessage Circular reference detected for Twig template "base.html.twig", path: base.html.twig -> base.html.twig in "base.html.twig" at line 1 + */ + public function testFailLoadTemplateOnCircularReference() + { + $twig = new Twig_Environment(new Twig_Loader_Array(array( + 'base.html.twig' => '{% extends "base.html.twig" %}', + ))); + + $twig->loadTemplate('base.html.twig'); + } + + /** + * @expectedException Twig_Error_Runtime + * @expectedExceptionMessage Circular reference detected for Twig template "base1.html.twig", path: base1.html.twig -> base2.html.twig -> base1.html.twig in "base1.html.twig" at line 1 + */ + public function testFailLoadTemplateOnComplexCircularReference() + { + $twig = new Twig_Environment(new Twig_Loader_Array(array( + 'base1.html.twig' => '{% extends "base2.html.twig" %}', + 'base2.html.twig' => '{% extends "base1.html.twig" %}', + ))); + + $twig->loadTemplate('base1.html.twig'); + } + + protected function getMockLoader($templateName, $templateContent) + { + // to be removed in 2.0 + $loader = $this->getMockBuilder('Twig_EnvironmentTestLoaderInterface')->getMock(); + //$loader = $this->getMockBuilder(array('Twig_LoaderInterface', 'Twig_SourceContextLoaderInterface'))->getMock(); + $loader->expects($this->any()) + ->method('getSourceContext') + ->with($templateName) + ->will($this->returnValue(new Twig_Source($templateContent, $templateName))); + $loader->expects($this->any()) + ->method('getCacheKey') + ->with($templateName) + ->will($this->returnValue($templateName)); + + return $loader; + } +} + +class Twig_Tests_EnvironmentTest_Extension_WithGlobals extends Twig_Extension +{ + public function getGlobals() + { + return array( + 'foo_global' => 'foo_global', + ); + } +} + +class Twig_Tests_EnvironmentTest_Extension extends Twig_Extension implements Twig_Extension_GlobalsInterface +{ + public function getTokenParsers() + { + return array( + new Twig_Tests_EnvironmentTest_TokenParser(), + ); + } + + public function getNodeVisitors() + { + return array( + new Twig_Tests_EnvironmentTest_NodeVisitor(), + ); + } + + public function getFilters() + { + return array( + new Twig_SimpleFilter('foo_filter', 'foo_filter'), + ); + } + + public function getTests() + { + return array( + new Twig_SimpleTest('foo_test', 'foo_test'), + ); + } + + public function getFunctions() + { + return array( + new Twig_SimpleFunction('foo_function', 'foo_function'), + ); + } + + public function getOperators() + { + return array( + array('foo_unary' => array()), + array('foo_binary' => array()), + ); + } + + public function getGlobals() + { + return array( + 'foo_global' => 'foo_global', + ); + } +} +class_alias('Twig_Tests_EnvironmentTest_Extension', 'Twig\Tests\EnvironmentTest\Extension', false); + +class Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName extends Twig_Extension +{ + public function getName() + { + return 'environment_test'; + } +} + +class Twig_Tests_EnvironmentTest_Extension_DynamicWithDeprecatedName extends Twig_Extension +{ + private $name; + + public function __construct($name) + { + $this->name = $name; + } + + public function getName() + { + return $this->name; + } +} + +class Twig_Tests_EnvironmentTest_TokenParser extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + } + + public function getTag() + { + return 'test'; + } +} + +class Twig_Tests_EnvironmentTest_NodeVisitor implements Twig_NodeVisitorInterface +{ + public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) + { + return $node; + } + + public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env) + { + return $node; + } + + public function getPriority() + { + return 0; + } +} + +class Twig_Tests_EnvironmentTest_ExtensionWithDeprecationInitRuntime extends Twig_Extension +{ + public function initRuntime(Twig_Environment $env) + { + } +} + +class Twig_Tests_EnvironmentTest_ExtensionWithoutDeprecationInitRuntime extends Twig_Extension implements Twig_Extension_InitRuntimeInterface +{ + public function initRuntime(Twig_Environment $env) + { + } +} + +class Twig_Tests_EnvironmentTest_ExtensionWithoutRuntime extends Twig_Extension +{ + public function getFunctions() + { + return array( + new Twig_SimpleFunction('from_runtime_array', array('Twig_Tests_EnvironmentTest_Runtime', 'fromRuntime')), + new Twig_SimpleFunction('from_runtime_string', 'Twig_Tests_EnvironmentTest_Runtime::fromRuntime'), + ); + } + + public function getName() + { + return 'from_runtime'; + } +} + +class Twig_Tests_EnvironmentTest_Runtime +{ + public function fromRuntime($name = 'bar') + { + return $name; + } +} + +// to be removed in 2.0 +interface Twig_EnvironmentTestLoaderInterface extends Twig_LoaderInterface, Twig_SourceContextLoaderInterface +{ +} diff --git a/vendor/twig/twig/test/Twig/Tests/ErrorTest.php b/vendor/twig/twig/test/Twig/Tests/ErrorTest.php new file mode 100644 index 0000000..3ec572a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/ErrorTest.php @@ -0,0 +1,211 @@ +setSourceContext(new Twig_Source('', new SplFileInfo(__FILE__))); + + $this->assertContains('test'.DIRECTORY_SEPARATOR.'Twig'.DIRECTORY_SEPARATOR.'Tests'.DIRECTORY_SEPARATOR.'ErrorTest.php', $error->getMessage()); + } + + public function testErrorWithArrayFilename() + { + $error = new Twig_Error('foo'); + $error->setSourceContext(new Twig_Source('', array('foo' => 'bar'))); + + $this->assertEquals('foo in {"foo":"bar"}', $error->getMessage()); + } + + public function testTwigExceptionGuessWithMissingVarAndArrayLoader() + { + $loader = new Twig_Loader_Array(array( + 'base.html' => '{% block content %}{% endblock %}', + 'index.html' => << true, 'debug' => true, 'cache' => false)); + + $template = $twig->loadTemplate('index.html'); + try { + $template->render(array()); + + $this->fail(); + } catch (Twig_Error_Runtime $e) { + $this->assertEquals('Variable "foo" does not exist in "index.html" at line 3.', $e->getMessage()); + $this->assertEquals(3, $e->getTemplateLine()); + $this->assertEquals('index.html', $e->getSourceContext()->getName()); + } + } + + public function testTwigExceptionGuessWithExceptionAndArrayLoader() + { + $loader = new Twig_Loader_Array(array( + 'base.html' => '{% block content %}{% endblock %}', + 'index.html' => << true, 'debug' => true, 'cache' => false)); + + $template = $twig->loadTemplate('index.html'); + try { + $template->render(array('foo' => new Twig_Tests_ErrorTest_Foo())); + + $this->fail(); + } catch (Twig_Error_Runtime $e) { + $this->assertEquals('An exception has been thrown during the rendering of a template ("Runtime error...") in "index.html" at line 3.', $e->getMessage()); + $this->assertEquals(3, $e->getTemplateLine()); + $this->assertEquals('index.html', $e->getSourceContext()->getName()); + } + } + + public function testTwigExceptionGuessWithMissingVarAndFilesystemLoader() + { + $loader = new Twig_Loader_Filesystem(dirname(__FILE__).'/Fixtures/errors'); + $twig = new Twig_Environment($loader, array('strict_variables' => true, 'debug' => true, 'cache' => false)); + + $template = $twig->loadTemplate('index.html'); + try { + $template->render(array()); + + $this->fail(); + } catch (Twig_Error_Runtime $e) { + $this->assertEquals('Variable "foo" does not exist.', $e->getMessage()); + $this->assertEquals(3, $e->getTemplateLine()); + $this->assertEquals('index.html', $e->getSourceContext()->getName()); + $this->assertEquals(3, $e->getLine()); + $this->assertEquals(strtr(dirname(__FILE__).'/Fixtures/errors/index.html', '/', DIRECTORY_SEPARATOR), $e->getFile()); + } + } + + public function testTwigExceptionGuessWithExceptionAndFilesystemLoader() + { + $loader = new Twig_Loader_Filesystem(dirname(__FILE__).'/Fixtures/errors'); + $twig = new Twig_Environment($loader, array('strict_variables' => true, 'debug' => true, 'cache' => false)); + + $template = $twig->loadTemplate('index.html'); + try { + $template->render(array('foo' => new Twig_Tests_ErrorTest_Foo())); + + $this->fail(); + } catch (Twig_Error_Runtime $e) { + $this->assertEquals('An exception has been thrown during the rendering of a template ("Runtime error...").', $e->getMessage()); + $this->assertEquals(3, $e->getTemplateLine()); + $this->assertEquals('index.html', $e->getSourceContext()->getName()); + $this->assertEquals(3, $e->getLine()); + $this->assertEquals(strtr(dirname(__FILE__).'/Fixtures/errors/index.html', '/', DIRECTORY_SEPARATOR), $e->getFile()); + } + } + + /** + * @dataProvider getErroredTemplates + */ + public function testTwigExceptionAddsFileAndLine($templates, $name, $line) + { + $loader = new Twig_Loader_Array($templates); + $twig = new Twig_Environment($loader, array('strict_variables' => true, 'debug' => true, 'cache' => false)); + + $template = $twig->loadTemplate('index'); + + try { + $template->render(array()); + + $this->fail(); + } catch (Twig_Error_Runtime $e) { + $this->assertEquals(sprintf('Variable "foo" does not exist in "%s" at line %d.', $name, $line), $e->getMessage()); + $this->assertEquals($line, $e->getTemplateLine()); + $this->assertEquals($name, $e->getSourceContext()->getName()); + } + + try { + $template->render(array('foo' => new Twig_Tests_ErrorTest_Foo())); + + $this->fail(); + } catch (Twig_Error_Runtime $e) { + $this->assertEquals(sprintf('An exception has been thrown during the rendering of a template ("Runtime error...") in "%s" at line %d.', $name, $line), $e->getMessage()); + $this->assertEquals($line, $e->getTemplateLine()); + $this->assertEquals($name, $e->getSourceContext()->getName()); + } + } + + public function getErroredTemplates() + { + return array( + // error occurs in a template + array( + array( + 'index' => "\n\n{{ foo.bar }}\n\n\n{{ 'foo' }}", + ), + 'index', 3, + ), + + // error occurs in an included template + array( + array( + 'index' => "{% include 'partial' %}", + 'partial' => '{{ foo.bar }}', + ), + 'partial', 1, + ), + + // error occurs in a parent block when called via parent() + array( + array( + 'index' => "{% extends 'base' %} + {% block content %} + {{ parent() }} + {% endblock %}", + 'base' => '{% block content %}{{ foo.bar }}{% endblock %}', + ), + 'base', 1, + ), + + // error occurs in a block from the child + array( + array( + 'index' => "{% extends 'base' %} + {% block content %} + {{ foo.bar }} + {% endblock %} + {% block foo %} + {{ foo.bar }} + {% endblock %}", + 'base' => '{% block content %}{% endblock %}', + ), + 'index', 3, + ), + ); + } +} + +class Twig_Tests_ErrorTest_Foo +{ + public function bar() + { + throw new Exception('Runtime error...'); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/ExpressionParserTest.php b/vendor/twig/twig/test/Twig/Tests/ExpressionParserTest.php new file mode 100644 index 0000000..3a173f0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/ExpressionParserTest.php @@ -0,0 +1,377 @@ +getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source($template, 'index'))); + } + + public function getFailingTestsForAssignment() + { + return array( + array('{% set false = "foo" %}'), + array('{% set FALSE = "foo" %}'), + array('{% set true = "foo" %}'), + array('{% set TRUE = "foo" %}'), + array('{% set none = "foo" %}'), + array('{% set NONE = "foo" %}'), + array('{% set null = "foo" %}'), + array('{% set NULL = "foo" %}'), + array('{% set 3 = "foo" %}'), + array('{% set 1 + 2 = "foo" %}'), + array('{% set "bar" = "foo" %}'), + array('{% set %}{% endset %}'), + ); + } + + /** + * @dataProvider getTestsForArray + */ + public function testArrayExpression($template, $expected) + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $stream = $env->tokenize(new Twig_Source($template, '')); + $parser = new Twig_Parser($env); + + $this->assertEquals($expected, $parser->parse($stream)->getNode('body')->getNode(0)->getNode('expr')); + } + + /** + * @expectedException Twig_Error_Syntax + * @dataProvider getFailingTestsForArray + */ + public function testArraySyntaxError($template) + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source($template, 'index'))); + } + + public function getFailingTestsForArray() + { + return array( + array('{{ [1, "a": "b"] }}'), + array('{{ {"a": "b", 2} }}'), + ); + } + + public function getTestsForArray() + { + return array( + // simple array + array('{{ [1, 2] }}', new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant(0, 1), + new Twig_Node_Expression_Constant(1, 1), + + new Twig_Node_Expression_Constant(1, 1), + new Twig_Node_Expression_Constant(2, 1), + ), 1), + ), + + // array with trailing , + array('{{ [1, 2, ] }}', new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant(0, 1), + new Twig_Node_Expression_Constant(1, 1), + + new Twig_Node_Expression_Constant(1, 1), + new Twig_Node_Expression_Constant(2, 1), + ), 1), + ), + + // simple hash + array('{{ {"a": "b", "b": "c"} }}', new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant('a', 1), + new Twig_Node_Expression_Constant('b', 1), + + new Twig_Node_Expression_Constant('b', 1), + new Twig_Node_Expression_Constant('c', 1), + ), 1), + ), + + // hash with trailing , + array('{{ {"a": "b", "b": "c", } }}', new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant('a', 1), + new Twig_Node_Expression_Constant('b', 1), + + new Twig_Node_Expression_Constant('b', 1), + new Twig_Node_Expression_Constant('c', 1), + ), 1), + ), + + // hash in an array + array('{{ [1, {"a": "b", "b": "c"}] }}', new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant(0, 1), + new Twig_Node_Expression_Constant(1, 1), + + new Twig_Node_Expression_Constant(1, 1), + new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant('a', 1), + new Twig_Node_Expression_Constant('b', 1), + + new Twig_Node_Expression_Constant('b', 1), + new Twig_Node_Expression_Constant('c', 1), + ), 1), + ), 1), + ), + + // array in a hash + array('{{ {"a": [1, 2], "b": "c"} }}', new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant('a', 1), + new Twig_Node_Expression_Array(array( + new Twig_Node_Expression_Constant(0, 1), + new Twig_Node_Expression_Constant(1, 1), + + new Twig_Node_Expression_Constant(1, 1), + new Twig_Node_Expression_Constant(2, 1), + ), 1), + new Twig_Node_Expression_Constant('b', 1), + new Twig_Node_Expression_Constant('c', 1), + ), 1), + ), + ); + } + + /** + * @expectedException Twig_Error_Syntax + */ + public function testStringExpressionDoesNotConcatenateTwoConsecutiveStrings() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); + $stream = $env->tokenize(new Twig_Source('{{ "a" "b" }}', 'index')); + $parser = new Twig_Parser($env); + + $parser->parse($stream); + } + + /** + * @dataProvider getTestsForString + */ + public function testStringExpression($template, $expected) + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false, 'optimizations' => 0)); + $stream = $env->tokenize(new Twig_Source($template, '')); + $parser = new Twig_Parser($env); + + $this->assertEquals($expected, $parser->parse($stream)->getNode('body')->getNode(0)->getNode('expr')); + } + + public function getTestsForString() + { + return array( + array( + '{{ "foo" }}', new Twig_Node_Expression_Constant('foo', 1), + ), + array( + '{{ "foo #{bar}" }}', new Twig_Node_Expression_Binary_Concat( + new Twig_Node_Expression_Constant('foo ', 1), + new Twig_Node_Expression_Name('bar', 1), + 1 + ), + ), + array( + '{{ "foo #{bar} baz" }}', new Twig_Node_Expression_Binary_Concat( + new Twig_Node_Expression_Binary_Concat( + new Twig_Node_Expression_Constant('foo ', 1), + new Twig_Node_Expression_Name('bar', 1), + 1 + ), + new Twig_Node_Expression_Constant(' baz', 1), + 1 + ), + ), + + array( + '{{ "foo #{"foo #{bar} baz"} baz" }}', new Twig_Node_Expression_Binary_Concat( + new Twig_Node_Expression_Binary_Concat( + new Twig_Node_Expression_Constant('foo ', 1), + new Twig_Node_Expression_Binary_Concat( + new Twig_Node_Expression_Binary_Concat( + new Twig_Node_Expression_Constant('foo ', 1), + new Twig_Node_Expression_Name('bar', 1), + 1 + ), + new Twig_Node_Expression_Constant(' baz', 1), + 1 + ), + 1 + ), + new Twig_Node_Expression_Constant(' baz', 1), + 1 + ), + ), + ); + } + + /** + * @expectedException Twig_Error_Syntax + */ + public function testAttributeCallDoesNotSupportNamedArguments() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{{ foo.bar(name="Foo") }}', 'index'))); + } + + /** + * @expectedException Twig_Error_Syntax + */ + public function testMacroCallDoesNotSupportNamedArguments() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{% from _self import foo %}{% macro foo() %}{% endmacro %}{{ foo(name="Foo") }}', 'index'))); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage An argument must be a name. Unexpected token "string" of value "a" ("name" expected) in "index" at line 1. + */ + public function testMacroDefinitionDoesNotSupportNonNameVariableName() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{% macro foo("a") %}{% endmacro %}', 'index'))); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage A default value for an argument must be a constant (a boolean, a string, a number, or an array) in "index" at line 1 + * @dataProvider getMacroDefinitionDoesNotSupportNonConstantDefaultValues + */ + public function testMacroDefinitionDoesNotSupportNonConstantDefaultValues($template) + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source($template, 'index'))); + } + + public function getMacroDefinitionDoesNotSupportNonConstantDefaultValues() + { + return array( + array('{% macro foo(name = "a #{foo} a") %}{% endmacro %}'), + array('{% macro foo(name = [["b", "a #{foo} a"]]) %}{% endmacro %}'), + ); + } + + /** + * @dataProvider getMacroDefinitionSupportsConstantDefaultValues + */ + public function testMacroDefinitionSupportsConstantDefaultValues($template) + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source($template, 'index'))); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function getMacroDefinitionSupportsConstantDefaultValues() + { + return array( + array('{% macro foo(name = "aa") %}{% endmacro %}'), + array('{% macro foo(name = 12) %}{% endmacro %}'), + array('{% macro foo(name = true) %}{% endmacro %}'), + array('{% macro foo(name = ["a"]) %}{% endmacro %}'), + array('{% macro foo(name = [["a"]]) %}{% endmacro %}'), + array('{% macro foo(name = {a: "a"}) %}{% endmacro %}'), + array('{% macro foo(name = {a: {b: "a"}}) %}{% endmacro %}'), + ); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "cycl" function. Did you mean "cycle" in "index" at line 1? + */ + public function testUnknownFunction() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{{ cycl() }}', 'index'))); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "foobar" function in "index" at line 1. + */ + public function testUnknownFunctionWithoutSuggestions() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{{ foobar() }}', 'index'))); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "lowe" filter. Did you mean "lower" in "index" at line 1? + */ + public function testUnknownFilter() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{{ 1|lowe }}', 'index'))); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "foobar" filter in "index" at line 1. + */ + public function testUnknownFilterWithoutSuggestions() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{{ 1|foobar }}', 'index'))); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "nul" test. Did you mean "null" in "index" at line 1 + */ + public function testUnknownTest() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + $stream = $env->tokenize(new Twig_Source('{{ 1 is nul }}', 'index')); + $parser->parse($stream); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "foobar" test in "index" at line 1. + */ + public function testUnknownTestWithoutSuggestions() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $parser = new Twig_Parser($env); + + $parser->parse($env->tokenize(new Twig_Source('{{ 1 is foobar }}', 'index'))); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php b/vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php new file mode 100644 index 0000000..ca69b4a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Extension/CoreTest.php @@ -0,0 +1,355 @@ +getMockBuilder('Twig_LoaderInterface')->getMock()); + + for ($i = 0; $i < 100; ++$i) { + $this->assertTrue(in_array(twig_random($env, $value), $expectedInArray, true)); // assertContains() would not consider the type + } + } + + public function getRandomFunctionTestData() + { + return array( + array(// array + array('apple', 'orange', 'citrus'), + array('apple', 'orange', 'citrus'), + ), + array(// Traversable + new ArrayObject(array('apple', 'orange', 'citrus')), + array('apple', 'orange', 'citrus'), + ), + array(// unicode string + 'Ä€é', + array('Ä', '€', 'é'), + ), + array(// numeric but string + '123', + array('1', '2', '3'), + ), + array(// integer + 5, + range(0, 5, 1), + ), + array(// float + 5.9, + range(0, 5, 1), + ), + array(// negative + -2, + array(0, -1, -2), + ), + ); + } + + public function testRandomFunctionWithoutParameter() + { + $max = mt_getrandmax(); + + for ($i = 0; $i < 100; ++$i) { + $val = twig_random(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $this->assertTrue(is_int($val) && $val >= 0 && $val <= $max); + } + } + + public function testRandomFunctionReturnsAsIs() + { + $this->assertSame('', twig_random(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()), '')); + $this->assertSame('', twig_random(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('charset' => null)), '')); + + $instance = new stdClass(); + $this->assertSame($instance, twig_random(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()), $instance)); + } + + /** + * @expectedException Twig_Error_Runtime + */ + public function testRandomFunctionOfEmptyArrayThrowsException() + { + twig_random(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()), array()); + } + + public function testRandomFunctionOnNonUTF8String() + { + if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) { + $this->markTestSkipped('needs iconv or mbstring'); + } + + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->setCharset('ISO-8859-1'); + + $text = twig_convert_encoding('Äé', 'ISO-8859-1', 'UTF-8'); + for ($i = 0; $i < 30; ++$i) { + $rand = twig_random($twig, $text); + $this->assertTrue(in_array(twig_convert_encoding($rand, 'UTF-8', 'ISO-8859-1'), array('Ä', 'é'), true)); + } + } + + public function testReverseFilterOnNonUTF8String() + { + if (!function_exists('iconv') && !function_exists('mb_convert_encoding')) { + $this->markTestSkipped('needs iconv or mbstring'); + } + + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->setCharset('ISO-8859-1'); + + $input = twig_convert_encoding('Äé', 'ISO-8859-1', 'UTF-8'); + $output = twig_convert_encoding(twig_reverse_filter($twig, $input), 'UTF-8', 'ISO-8859-1'); + + $this->assertEquals($output, 'éÄ'); + } + + /** + * @dataProvider provideCustomEscaperCases + */ + public function testCustomEscaper($expected, $string, $strategy) + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->getExtension('Twig_Extension_Core')->setEscaper('foo', 'foo_escaper_for_test'); + + $this->assertSame($expected, twig_escape_filter($twig, $string, $strategy)); + } + + public function provideCustomEscaperCases() + { + return array( + array('fooUTF-8', 'foo', 'foo'), + array('UTF-8', null, 'foo'), + array('42UTF-8', 42, 'foo'), + ); + } + + /** + * @expectedException Twig_Error_Runtime + */ + public function testUnknownCustomEscaper() + { + twig_escape_filter(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()), 'foo', 'bar'); + } + + /** + * @dataProvider provideTwigFirstCases + */ + public function testTwigFirst($expected, $input) + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $this->assertSame($expected, twig_first($twig, $input)); + } + + public function provideTwigFirstCases() + { + $i = array(1 => 'a', 2 => 'b', 3 => 'c'); + + return array( + array('a', 'abc'), + array(1, array(1, 2, 3)), + array('', null), + array('', ''), + array('a', new CoreTestIterator($i, array_keys($i), true, 3)), + ); + } + + /** + * @dataProvider provideTwigLastCases + */ + public function testTwigLast($expected, $input) + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $this->assertSame($expected, twig_last($twig, $input)); + } + + public function provideTwigLastCases() + { + $i = array(1 => 'a', 2 => 'b', 3 => 'c'); + + return array( + array('c', 'abc'), + array(3, array(1, 2, 3)), + array('', null), + array('', ''), + array('c', new CoreTestIterator($i, array_keys($i), true)), + ); + } + + /** + * @dataProvider provideArrayKeyCases + */ + public function testArrayKeysFilter(array $expected, $input) + { + $this->assertSame($expected, twig_get_array_keys_filter($input)); + } + + public function provideArrayKeyCases() + { + $array = array('a' => 'a1', 'b' => 'b1', 'c' => 'c1'); + $keys = array_keys($array); + + return array( + array($keys, $array), + array($keys, new CoreTestIterator($array, $keys)), + array($keys, new CoreTestIteratorAggregate($array, $keys)), + array($keys, new CoreTestIteratorAggregateAggregate($array, $keys)), + array(array(), null), + array(array('a'), new SimpleXMLElement('')), + ); + } + + /** + * @dataProvider provideInFilterCases + */ + public function testInFilter($expected, $value, $compare) + { + $this->assertSame($expected, twig_in_filter($value, $compare)); + } + + public function provideInFilterCases() + { + $array = array(1, 2, 'a' => 3, 5, 6, 7); + $keys = array_keys($array); + + return array( + array(true, 1, $array), + array(true, '3', $array), + array(true, '3', 'abc3def'), + array(true, 1, new CoreTestIterator($array, $keys, true, 1)), + array(true, '3', new CoreTestIterator($array, $keys, true, 3)), + array(true, '3', new CoreTestIteratorAggregateAggregate($array, $keys, true, 3)), + array(false, 4, $array), + array(false, 4, new CoreTestIterator($array, $keys, true)), + array(false, 4, new CoreTestIteratorAggregateAggregate($array, $keys, true)), + array(false, 1, 1), + array(true, 'b', new SimpleXMLElement('b')), + ); + } + + /** + * @dataProvider provideSliceFilterCases + */ + public function testSliceFilter($expected, $input, $start, $length = null, $preserveKeys = false) + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $this->assertSame($expected, twig_slice($twig, $input, $start, $length, $preserveKeys)); + } + + public function provideSliceFilterCases() + { + $i = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4); + $keys = array_keys($i); + + return array( + array(array('a' => 1), $i, 0, 1, true), + array(array('a' => 1), $i, 0, 1, false), + array(array('b' => 2, 'c' => 3), $i, 1, 2), + array(array(1), array(1, 2, 3, 4), 0, 1), + array(array(2, 3), array(1, 2, 3, 4), 1, 2), + array(array(2, 3), new CoreTestIterator($i, $keys, true), 1, 2), + array(array('c' => 3, 'd' => 4), new CoreTestIteratorAggregate($i, $keys, true), 2, null, true), + array($i, new CoreTestIterator($i, $keys, true), 0, count($keys) + 10, true), + array(array(), new CoreTestIterator($i, $keys, true), count($keys) + 10), + array('de', 'abcdef', 3, 2), + array(array(), new SimpleXMLElement('12'), 3), + array(array(), new ArrayIterator(array(1, 2)), 3), + ); + } +} + +function foo_escaper_for_test(Twig_Environment $env, $string, $charset) +{ + return $string.$charset; +} + +final class CoreTestIteratorAggregate implements IteratorAggregate +{ + private $iterator; + + public function __construct(array $array, array $keys, $allowAccess = false, $maxPosition = false) + { + $this->iterator = new CoreTestIterator($array, $keys, $allowAccess, $maxPosition); + } + + public function getIterator() + { + return $this->iterator; + } +} + +final class CoreTestIteratorAggregateAggregate implements IteratorAggregate +{ + private $iterator; + + public function __construct(array $array, array $keys, $allowValueAccess = false, $maxPosition = false) + { + $this->iterator = new CoreTestIteratorAggregate($array, $keys, $allowValueAccess, $maxPosition); + } + + public function getIterator() + { + return $this->iterator; + } +} + +final class CoreTestIterator implements Iterator +{ + private $position; + private $array; + private $arrayKeys; + private $allowValueAccess; + private $maxPosition; + + public function __construct(array $values, array $keys, $allowValueAccess = false, $maxPosition = false) + { + $this->array = $values; + $this->arrayKeys = $keys; + $this->position = 0; + $this->allowValueAccess = $allowValueAccess; + $this->maxPosition = false === $maxPosition ? count($values) + 1 : $maxPosition; + } + + public function rewind() + { + $this->position = 0; + } + + public function current() + { + if ($this->allowValueAccess) { + return $this->array[$this->key()]; + } + + throw new LogicException('Code should only use the keys, not the values provided by iterator.'); + } + + public function key() + { + return $this->arrayKeys[$this->position]; + } + + public function next() + { + ++$this->position; + if ($this->position === $this->maxPosition) { + throw new LogicException(sprintf('Code should not iterate beyond %d.', $this->maxPosition)); + } + } + + public function valid() + { + return isset($this->arrayKeys[$this->position]); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Extension/SandboxTest.php b/vendor/twig/twig/test/Twig/Tests/Extension/SandboxTest.php new file mode 100644 index 0000000..e268115 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Extension/SandboxTest.php @@ -0,0 +1,323 @@ + 'Fabien', + 'obj' => new FooObject(), + 'arr' => array('obj' => new FooObject()), + ); + + self::$templates = array( + '1_basic1' => '{{ obj.foo }}', + '1_basic2' => '{{ name|upper }}', + '1_basic3' => '{% if name %}foo{% endif %}', + '1_basic4' => '{{ obj.bar }}', + '1_basic5' => '{{ obj }}', + '1_basic6' => '{{ arr.obj }}', + '1_basic7' => '{{ cycle(["foo","bar"], 1) }}', + '1_basic8' => '{{ obj.getfoobar }}{{ obj.getFooBar }}', + '1_basic9' => '{{ obj.foobar }}{{ obj.fooBar }}', + '1_basic' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}', + '1_layout' => '{% block content %}{% endblock %}', + '1_child' => "{% extends \"1_layout\" %}\n{% block content %}\n{{ \"a\"|json_encode }}\n{% endblock %}", + '1_include' => '{{ include("1_basic1", sandboxed=true) }}', + '1_range_operator' => '{{ (1..2)[0] }}', + ); + } + + /** + * @expectedException Twig_Sandbox_SecurityError + * @expectedExceptionMessage Filter "json_encode" is not allowed in "1_child" at line 3. + */ + public function testSandboxWithInheritance() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array('block')); + $twig->loadTemplate('1_child')->render(array()); + } + + public function testSandboxGloballySet() + { + $twig = $this->getEnvironment(false, array(), self::$templates); + $this->assertEquals('FOO', $twig->loadTemplate('1_basic')->render(self::$params), 'Sandbox does nothing if it is disabled globally'); + } + + public function testSandboxUnallowedMethodAccessor() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_basic1')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if an unallowed method is called'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedMethodError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedMethodError'); + $this->assertEquals('FooObject', $e->getClassName(), 'Exception should be raised on the "FooObject" class'); + $this->assertEquals('foo', $e->getMethodName(), 'Exception should be raised on the "foo" method'); + } + } + + public function testSandboxUnallowedFilter() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_basic2')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if an unallowed filter is called'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedFilterError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedFilterError'); + $this->assertEquals('upper', $e->getFilterName(), 'Exception should be raised on the "upper" filter'); + } + } + + public function testSandboxUnallowedTag() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_basic3')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if an unallowed tag is used in the template'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedTagError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedTagError'); + $this->assertEquals('if', $e->getTagName(), 'Exception should be raised on the "if" tag'); + } + } + + public function testSandboxUnallowedProperty() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_basic4')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if an unallowed property is called in the template'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedPropertyError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedPropertyError'); + $this->assertEquals('FooObject', $e->getClassName(), 'Exception should be raised on the "FooObject" class'); + $this->assertEquals('bar', $e->getPropertyName(), 'Exception should be raised on the "bar" property'); + } + } + + public function testSandboxUnallowedToString() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_basic5')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if an unallowed method (__toString()) is called in the template'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedMethodError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedMethodError'); + $this->assertEquals('FooObject', $e->getClassName(), 'Exception should be raised on the "FooObject" class'); + $this->assertEquals('__tostring', $e->getMethodName(), 'Exception should be raised on the "__toString" method'); + } + } + + public function testSandboxUnallowedToStringArray() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_basic6')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if an unallowed method (__toString()) is called in the template'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedMethodError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedMethodError'); + $this->assertEquals('FooObject', $e->getClassName(), 'Exception should be raised on the "FooObject" class'); + $this->assertEquals('__tostring', $e->getMethodName(), 'Exception should be raised on the "__toString" method'); + } + } + + public function testSandboxUnallowedFunction() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_basic7')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if an unallowed function is called in the template'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedFunctionError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedFunctionError'); + $this->assertEquals('cycle', $e->getFunctionName(), 'Exception should be raised on the "cycle" function'); + } + } + + public function testSandboxUnallowedRangeOperator() + { + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('1_range_operator')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception if the unallowed range operator is called'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedFunctionError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedFunctionError'); + $this->assertEquals('range', $e->getFunctionName(), 'Exception should be raised on the "range" function'); + } + } + + public function testSandboxAllowMethodFoo() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array(), array(), array('FooObject' => 'foo')); + FooObject::reset(); + $this->assertEquals('foo', $twig->loadTemplate('1_basic1')->render(self::$params), 'Sandbox allow some methods'); + $this->assertEquals(1, FooObject::$called['foo'], 'Sandbox only calls method once'); + } + + public function testSandboxAllowMethodToString() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array(), array(), array('FooObject' => '__toString')); + FooObject::reset(); + $this->assertEquals('foo', $twig->loadTemplate('1_basic5')->render(self::$params), 'Sandbox allow some methods'); + $this->assertEquals(1, FooObject::$called['__toString'], 'Sandbox only calls method once'); + } + + public function testSandboxAllowMethodToStringDisabled() + { + $twig = $this->getEnvironment(false, array(), self::$templates); + FooObject::reset(); + $this->assertEquals('foo', $twig->loadTemplate('1_basic5')->render(self::$params), 'Sandbox allows __toString when sandbox disabled'); + $this->assertEquals(1, FooObject::$called['__toString'], 'Sandbox only calls method once'); + } + + public function testSandboxAllowFilter() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array(), array('upper')); + $this->assertEquals('FABIEN', $twig->loadTemplate('1_basic2')->render(self::$params), 'Sandbox allow some filters'); + } + + public function testSandboxAllowTag() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array('if')); + $this->assertEquals('foo', $twig->loadTemplate('1_basic3')->render(self::$params), 'Sandbox allow some tags'); + } + + public function testSandboxAllowProperty() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array(), array(), array(), array('FooObject' => 'bar')); + $this->assertEquals('bar', $twig->loadTemplate('1_basic4')->render(self::$params), 'Sandbox allow some properties'); + } + + public function testSandboxAllowFunction() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array(), array(), array(), array(), array('cycle')); + $this->assertEquals('bar', $twig->loadTemplate('1_basic7')->render(self::$params), 'Sandbox allow some functions'); + } + + public function testSandboxAllowRangeOperator() + { + $twig = $this->getEnvironment(true, array(), self::$templates, array(), array(), array(), array(), array('range')); + $this->assertEquals('1', $twig->loadTemplate('1_range_operator')->render(self::$params), 'Sandbox allow the range operator'); + } + + public function testSandboxAllowFunctionsCaseInsensitive() + { + foreach (array('getfoobar', 'getFoobar', 'getFooBar') as $name) { + $twig = $this->getEnvironment(true, array(), self::$templates, array(), array(), array('FooObject' => $name)); + FooObject::reset(); + $this->assertEquals('foobarfoobar', $twig->loadTemplate('1_basic8')->render(self::$params), 'Sandbox allow methods in a case-insensitive way'); + $this->assertEquals(2, FooObject::$called['getFooBar'], 'Sandbox only calls method once'); + + $this->assertEquals('foobarfoobar', $twig->loadTemplate('1_basic9')->render(self::$params), 'Sandbox allow methods via shortcut names (ie. without get/set)'); + } + } + + public function testSandboxLocallySetForAnInclude() + { + self::$templates = array( + '2_basic' => '{{ obj.foo }}{% include "2_included" %}{{ obj.foo }}', + '2_included' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}', + ); + + $twig = $this->getEnvironment(false, array(), self::$templates); + $this->assertEquals('fooFOOfoo', $twig->loadTemplate('2_basic')->render(self::$params), 'Sandbox does nothing if disabled globally and sandboxed not used for the include'); + + self::$templates = array( + '3_basic' => '{{ obj.foo }}{% sandbox %}{% include "3_included" %}{% endsandbox %}{{ obj.foo }}', + '3_included' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}', + ); + + $twig = $this->getEnvironment(true, array(), self::$templates); + try { + $twig->loadTemplate('3_basic')->render(self::$params); + $this->fail('Sandbox throws a SecurityError exception when the included file is sandboxed'); + } catch (Twig_Sandbox_SecurityError $e) { + $this->assertInstanceOf('Twig_Sandbox_SecurityNotAllowedTagError', $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedTagError'); + $this->assertEquals('sandbox', $e->getTagName()); + } + } + + public function testMacrosInASandbox() + { + $twig = $this->getEnvironment(true, array('autoescape' => 'html'), array('index' => <<{{ text }}

    {% endmacro %} + +{{- macros.test('username') }} +EOF + ), array('macro', 'import'), array('escape')); + + $this->assertEquals('

    username

    ', $twig->loadTemplate('index')->render(array())); + } + + public function testSandboxDisabledAfterIncludeFunctionError() + { + $twig = $this->getEnvironment(false, array(), self::$templates); + + $e = null; + try { + $twig->loadTemplate('1_include')->render(self::$params); + } catch (Throwable $e) { + } catch (Exception $e) { + } + if (null === $e) { + $this->fail('An exception should be thrown for this test to be valid.'); + } + + $this->assertFalse($twig->getExtension('Twig_Extension_Sandbox')->isSandboxed(), 'Sandboxed include() function call should not leave Sandbox enabled when an error occurs.'); + } + + protected function getEnvironment($sandboxed, $options, $templates, $tags = array(), $filters = array(), $methods = array(), $properties = array(), $functions = array()) + { + $loader = new Twig_Loader_Array($templates); + $twig = new Twig_Environment($loader, array_merge(array('debug' => true, 'cache' => false, 'autoescape' => false), $options)); + $policy = new Twig_Sandbox_SecurityPolicy($tags, $filters, $methods, $properties, $functions); + $twig->addExtension(new Twig_Extension_Sandbox($policy, $sandboxed)); + + return $twig; + } +} + +class FooObject +{ + public static $called = array('__toString' => 0, 'foo' => 0, 'getFooBar' => 0); + + public $bar = 'bar'; + + public static function reset() + { + self::$called = array('__toString' => 0, 'foo' => 0, 'getFooBar' => 0); + } + + public function __toString() + { + ++self::$called['__toString']; + + return 'foo'; + } + + public function foo() + { + ++self::$called['foo']; + + return 'foo'; + } + + public function getFooBar() + { + ++self::$called['getFooBar']; + + return 'foobar'; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/FactoryRuntimeLoaderTest.php b/vendor/twig/twig/test/Twig/Tests/FactoryRuntimeLoaderTest.php new file mode 100644 index 0000000..f97d306 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/FactoryRuntimeLoaderTest.php @@ -0,0 +1,32 @@ + 'getRuntime')); + + $this->assertInstanceOf('stdClass', $loader->load('stdClass')); + } + + public function testLoadReturnsNullForUnmappedRuntime() + { + $loader = new Twig_FactoryRuntimeLoader(); + + $this->assertNull($loader->load('stdClass')); + } +} + +function getRuntime() +{ + return new stdClass(); +} diff --git a/vendor/twig/twig/test/Twig/Tests/FileCachingTest.php b/vendor/twig/twig/test/Twig/Tests/FileCachingTest.php new file mode 100644 index 0000000..e8a23ea --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/FileCachingTest.php @@ -0,0 +1,63 @@ +tmpDir = sys_get_temp_dir().'/TwigTests'; + if (!file_exists($this->tmpDir)) { + @mkdir($this->tmpDir, 0777, true); + } + + if (!is_writable($this->tmpDir)) { + $this->markTestSkipped(sprintf('Unable to run the tests as "%s" is not writable.', $this->tmpDir)); + } + + $this->env = new Twig_Environment(new Twig_Loader_Array(array('index' => 'index', 'index2' => 'index2')), array('cache' => $this->tmpDir)); + } + + protected function tearDown() + { + Twig_Tests_FilesystemHelper::removeDir($this->tmpDir); + } + + /** + * @group legacy + */ + public function testWritingCacheFiles() + { + $name = 'index'; + $this->env->loadTemplate($name); + $cacheFileName = $this->env->getCacheFilename($name); + + $this->assertFileExists($cacheFileName, 'Cache file does not exist.'); + } + + /** + * @group legacy + */ + public function testClearingCacheFiles() + { + $name = 'index2'; + $this->env->loadTemplate($name); + $cacheFileName = $this->env->getCacheFilename($name); + + $this->assertFileExists($cacheFileName, 'Cache file does not exist.'); + $this->env->clearCacheFiles(); + $this->assertFileNotExists($cacheFileName, 'Cache file was not cleared.'); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/FileExtensionEscapingStrategyTest.php b/vendor/twig/twig/test/Twig/Tests/FileExtensionEscapingStrategyTest.php new file mode 100644 index 0000000..a983a47 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/FileExtensionEscapingStrategyTest.php @@ -0,0 +1,51 @@ +assertSame($strategy, Twig_FileExtensionEscapingStrategy::guess($filename)); + } + + public function getGuessData() + { + return array( + // default + array('html', 'foo.html'), + array('html', 'foo.html.twig'), + array('html', 'foo'), + array('html', 'foo.bar.twig'), + array('html', 'foo.txt/foo'), + array('html', 'foo.txt/foo.js/'), + + // css + array('css', 'foo.css'), + array('css', 'foo.css.twig'), + array('css', 'foo.twig.css'), + array('css', 'foo.js.css'), + array('css', 'foo.js.css.twig'), + + // js + array('js', 'foo.js'), + array('js', 'foo.js.twig'), + array('js', 'foo.txt/foo.js'), + array('js', 'foo.txt.twig/foo.js'), + + // txt + array(false, 'foo.txt'), + array(false, 'foo.txt.twig'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/FilesystemHelper.php b/vendor/twig/twig/test/Twig/Tests/FilesystemHelper.php new file mode 100644 index 0000000..0e315e8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/FilesystemHelper.php @@ -0,0 +1,30 @@ + $fileInfo) { + if ($iterator->isDot()) { + continue; + } + + if ($fileInfo->isDir()) { + rmdir($filename); + } else { + unlink($filename); + } + } + rmdir($dir); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/autoescape/block.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/autoescape/block.test new file mode 100644 index 0000000..1290973 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/autoescape/block.test @@ -0,0 +1,21 @@ +--TEST-- +blocks and autoescape +--TEMPLATE-- +{{ include('unrelated.txt.twig') -}} +{{ include('template.html.twig') -}} +--TEMPLATE(unrelated.txt.twig)-- +{% block content %}{% endblock %} +--TEMPLATE(template.html.twig)-- +{% extends 'parent.html.twig' %} +{% block content %} +{{ br -}} +{% endblock %} +--TEMPLATE(parent.html.twig)-- +{% set _content = block('content')|raw %} +{{ _content|raw }} +--DATA-- +return array('br' => '
    ') +--CONFIG-- +return array('autoescape' => 'name') +--EXPECT-- +<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/autoescape/name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/autoescape/name.test new file mode 100644 index 0000000..98e8939 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/autoescape/name.test @@ -0,0 +1,22 @@ +--TEST-- +"name" autoescape strategy +--TEMPLATE-- +{{ br -}} +{{ include('index.js.twig') -}} +{{ include('index.html.twig') -}} +{{ include('index.txt.twig') -}} +--TEMPLATE(index.js.twig)-- +{{ br -}} +--TEMPLATE(index.html.twig)-- +{{ br -}} +--TEMPLATE(index.txt.twig)-- +{{ br -}} +--DATA-- +return array('br' => '
    ') +--CONFIG-- +return array('autoescape' => 'name') +--EXPECT-- +<br /> +\u003Cbr\u0020\/\u003E +<br /> +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/errors/base.html b/vendor/twig/twig/test/Twig/Tests/Fixtures/errors/base.html new file mode 100644 index 0000000..cb0dbe4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/errors/base.html @@ -0,0 +1 @@ +{% block content %}{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/errors/index.html b/vendor/twig/twig/test/Twig/Tests/Fixtures/errors/index.html new file mode 100644 index 0000000..df57c82 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/errors/index.html @@ -0,0 +1,7 @@ +{% extends 'base.html' %} +{% block content %} + {{ foo.bar }} +{% endblock %} +{% block foo %} + {{ foo.bar }} +{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/child_contents_outside_blocks.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/child_contents_outside_blocks.test new file mode 100644 index 0000000..2a9c5e7 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/child_contents_outside_blocks.test @@ -0,0 +1,15 @@ +--TEST-- +Exception for child templates defining content outside blocks defined by parent +--TEMPLATE-- +{% extends 'base.twig' %} + +Content outside a block. + +{% block sidebar %} + Content inside a block. +{% endblock %} +--TEMPLATE(base.twig)-- +{% block sidebar %} +{% endblock %} +--EXCEPTION-- +Twig_Error_Syntax: A template that extends another one cannot include content outside Twig blocks. Did you forget to put the content inside a {% block %} tag in "index.twig" at line 3? diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable.test new file mode 100644 index 0000000..7ff2eed --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable.test @@ -0,0 +1,18 @@ +--TEST-- +Exception for multiline array with undefined variable +--TEMPLATE-- +{% set foo = { + foo: 'foo', + bar: 'bar', + + + foobar: foobar, + + + + foo2: foo2, +} %} +--DATA-- +return array('foobar' => 'foobar') +--EXCEPTION-- +Twig_Error_Runtime: Variable "foo2" does not exist in "index.twig" at line 11. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable_again.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable_again.test new file mode 100644 index 0000000..c425069 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable_again.test @@ -0,0 +1,18 @@ +--TEST-- +Exception for multiline array with undefined variable +--TEMPLATE-- +{% set foo = { + foo: 'foo', + bar: 'bar', + + + foobar: foobar, + + + + foo2: foo2, +} %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Runtime: Variable "foobar" does not exist in "index.twig" at line 7. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_undefined_variable.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_undefined_variable.test new file mode 100644 index 0000000..2f94a5e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_undefined_variable.test @@ -0,0 +1,12 @@ +--TEST-- +Exception for multile function with undefined variable +--TEMPLATE-- +{{ include('foo', + with_context=with_context +) }} +--TEMPLATE(foo)-- +Foo +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Runtime: Variable "with_context" does not exist in "index.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_unknown_argument.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_unknown_argument.test new file mode 100644 index 0000000..64761fc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_unknown_argument.test @@ -0,0 +1,9 @@ +--TEST-- +Exception for multiline function with unknown argument +--TEMPLATE-- +{{ include('foo', + with_context=True, + invalid=False +) }} +--EXCEPTION-- +Twig_Error_Syntax: Unknown argument "invalid" for function "include(template, variables, with_context, ignore_missing, sandboxed)" in "index.twig" at line 4. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_tag_with_undefined_variable.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_tag_with_undefined_variable.test new file mode 100644 index 0000000..7b3b1da --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/multiline_tag_with_undefined_variable.test @@ -0,0 +1,12 @@ +--TEST-- +Exception for multiline tag with undefined variable +--TEMPLATE-- +{% include 'foo' + with vars +%} +--TEMPLATE(foo)-- +Foo +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Runtime: Variable "vars" does not exist in "index.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/strict_comparison_operator.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/strict_comparison_operator.test new file mode 100644 index 0000000..dffbc01 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/strict_comparison_operator.test @@ -0,0 +1,6 @@ +--TEST-- +The PHP === strict comparison operator is not supported +--TEMPLATE-- +{{ 1 === 2 }} +--EXCEPTION-- +Twig_Error_Syntax: Unexpected operator of value "=". Did you try to use "===" or "!==" for strict comparison? Use "is same as(value)" instead in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/syntax_error_in_reused_template.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/syntax_error_in_reused_template.test new file mode 100644 index 0000000..9ca418b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/syntax_error_in_reused_template.test @@ -0,0 +1,10 @@ +--TEST-- +Exception for syntax error in reused template +--TEMPLATE-- +{% use 'foo.twig' %} +--TEMPLATE(foo.twig)-- +{% block bar %} + {% do node.data = 5 %} +{% endblock %} +--EXCEPTION-- +Twig_Error_Syntax: Unexpected token "operator" of value "=" ("end of statement block" expected) in "foo.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/unclosed_tag.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/unclosed_tag.test new file mode 100644 index 0000000..2c35ad5 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/unclosed_tag.test @@ -0,0 +1,20 @@ +--TEST-- +Exception for an unclosed tag +--TEMPLATE-- +{% block foo %} + {% if foo %} + + + + + {% for i in fo %} + + + + {% endfor %} + + + +{% endblock %} +--EXCEPTION-- +Twig_Error_Syntax: Unexpected "endblock" tag (expecting closing tag for the "if" tag defined near line 4) in "index.twig" at line 16. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_parent.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_parent.test new file mode 100644 index 0000000..c8e7a09 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_parent.test @@ -0,0 +1,8 @@ +--TEST-- +Exception for an undefined parent +--TEMPLATE-- +{% extends 'foo.html' %} + +{% set foo = "foo" %} +--EXCEPTION-- +Twig_Error_Loader: Template "foo.html" is not defined in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_template_in_child_template.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_template_in_child_template.test new file mode 100644 index 0000000..1992510 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_template_in_child_template.test @@ -0,0 +1,15 @@ +--TEST-- +Exception for an undefined template in a child template +--TEMPLATE-- +{% extends 'base.twig' %} + +{% block sidebar %} + {{ include('include.twig') }} +{% endblock %} +--TEMPLATE(base.twig)-- +{% block sidebar %} +{% endblock %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Loader: Template "include.twig" is not defined in "index.twig" at line 5. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_trait.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_trait.test new file mode 100644 index 0000000..6679fbe --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/exceptions/undefined_trait.test @@ -0,0 +1,9 @@ +--TEST-- +Exception for an undefined trait +--TEMPLATE-- +{% use 'foo' with foobar as bar %} +--TEMPLATE(foo)-- +{% block bar %} +{% endblock %} +--EXCEPTION-- +Twig_Error_Runtime: Block "foobar" is not defined in trait "foo" in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/_self.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/_self.test new file mode 100644 index 0000000..32fed8f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/_self.test @@ -0,0 +1,8 @@ +--TEST-- +_self returns the template name +--TEMPLATE-- +{{ _self }} +--DATA-- +return array() +--EXPECT-- +index.twig diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/array.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/array.test new file mode 100644 index 0000000..c69b119 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/array.test @@ -0,0 +1,61 @@ +--TEST-- +Twig supports array notation +--TEMPLATE-- +{# empty array #} +{{ []|join(',') }} + +{{ [1, 2]|join(',') }} +{{ ['foo', "bar"]|join(',') }} +{{ {0: 1, 'foo': 'bar'}|join(',') }} +{{ {0: 1, 'foo': 'bar'}|keys|join(',') }} + +{{ {0: 1, foo: 'bar'}|join(',') }} +{{ {0: 1, foo: 'bar'}|keys|join(',') }} + +{# nested arrays #} +{% set a = [1, 2, [1, 2], {'foo': {'foo': 'bar'}}] %} +{{ a[2]|join(',') }} +{{ a[3]["foo"]|join(',') }} + +{# works even if [] is used inside the array #} +{{ [foo[bar]]|join(',') }} + +{# elements can be any expression #} +{{ ['foo'|upper, bar|upper, bar == foo]|join(',') }} + +{# arrays can have a trailing , like in PHP #} +{{ + [ + 1, + 2, + ]|join(',') +}} + +{# keys can be any expression #} +{% set a = 1 %} +{% set b = "foo" %} +{% set ary = { (a): 'a', (b): 'b', 'c': 'c', (a ~ b): 'd' } %} +{{ ary|keys|join(',') }} +{{ ary|join(',') }} +--DATA-- +return array('bar' => 'bar', 'foo' => array('bar' => 'bar')) +--EXPECT-- +1,2 +foo,bar +1,bar +0,foo + +1,bar +0,foo + +1,2 +bar + +bar + +FOO,BAR, + +1,2 + +1,foo,c,1foo +a,b,c,d diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/array_call.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/array_call.test new file mode 100644 index 0000000..f3df328 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/array_call.test @@ -0,0 +1,14 @@ +--TEST-- +Twig supports method calls +--TEMPLATE-- +{{ items.foo }} +{{ items['foo'] }} +{{ items[foo] }} +{{ items[items[foo]] }} +--DATA-- +return array('foo' => 'bar', 'items' => array('foo' => 'bar', 'bar' => 'foo')) +--EXPECT-- +bar +bar +foo +bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/binary.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/binary.test new file mode 100644 index 0000000..f5e6845 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/binary.test @@ -0,0 +1,46 @@ +--TEST-- +Twig supports binary operations (+, -, *, /, ~, %, and, or) +--TEMPLATE-- +{{ 1 + 1 }} +{{ 2 - 1 }} +{{ 2 * 2 }} +{{ 2 / 2 }} +{{ 3 % 2 }} +{{ 1 and 1 }} +{{ 1 and 0 }} +{{ 0 and 1 }} +{{ 0 and 0 }} +{{ 1 or 1 }} +{{ 1 or 0 }} +{{ 0 or 1 }} +{{ 0 or 0 }} +{{ 0 or 1 and 0 }} +{{ 1 or 0 and 1 }} +{{ "foo" ~ "bar" }} +{{ foo ~ "bar" }} +{{ "foo" ~ bar }} +{{ foo ~ bar }} +{{ 20 // 7 }} +--DATA-- +return array('foo' => 'bar', 'bar' => 'foo') +--EXPECT-- +2 +1 +4 +1 +1 +1 + + + +1 +1 +1 + + +1 +foobar +barbar +foofoo +barfoo +2 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/bitwise.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/bitwise.test new file mode 100644 index 0000000..74fe6ca --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/bitwise.test @@ -0,0 +1,14 @@ +--TEST-- +Twig supports bitwise operations +--TEMPLATE-- +{{ 1 b-and 5 }} +{{ 1 b-or 5 }} +{{ 1 b-xor 5 }} +{{ (1 and 0 b-or 0) is same as(1 and (0 b-or 0)) ? 'ok' : 'ko' }} +--DATA-- +return array() +--EXPECT-- +1 +5 +4 +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/comparison.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/comparison.test new file mode 100644 index 0000000..726b850 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/comparison.test @@ -0,0 +1,14 @@ +--TEST-- +Twig supports comparison operators (==, !=, <, >, >=, <=) +--TEMPLATE-- +{{ 1 > 2 }}/{{ 1 > 1 }}/{{ 1 >= 2 }}/{{ 1 >= 1 }} +{{ 1 < 2 }}/{{ 1 < 1 }}/{{ 1 <= 2 }}/{{ 1 <= 1 }} +{{ 1 == 1 }}/{{ 1 == 2 }} +{{ 1 != 1 }}/{{ 1 != 2 }} +--DATA-- +return array() +--EXPECT-- +///1 +1//1/1 +1/ +/1 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/divisibleby.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/divisibleby.test new file mode 100644 index 0000000..238dd27 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/divisibleby.test @@ -0,0 +1,17 @@ +--TEST-- +Twig supports the "divisible by" operator +--TEMPLATE-- +{{ 8 is divisible by(2) ? 'OK' }} +{{ 8 is not divisible by(3) ? 'OK' }} +{{ 8 is divisible by (2) ? 'OK' }} +{{ 8 is not + divisible + by + (3) ? 'OK' }} +--DATA-- +return array() +--EXPECT-- +OK +OK +OK +OK diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/dotdot.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/dotdot.test new file mode 100644 index 0000000..9cd0676 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/dotdot.test @@ -0,0 +1,20 @@ +--TEST-- +Twig supports the .. operator +--TEMPLATE-- +{% for i in 0..10 %}{{ i }} {% endfor %} + +{% for letter in 'a'..'z' %}{{ letter }} {% endfor %} + +{% for letter in 'a'|upper..'z'|upper %}{{ letter }} {% endfor %} + +{% for i in foo[0]..foo[1] %}{{ i }} {% endfor %} + +{% for i in 0 + 1 .. 10 - 1 %}{{ i }} {% endfor %} +--DATA-- +return array('foo' => array(1, 10)) +--EXPECT-- +0 1 2 3 4 5 6 7 8 9 10 +a b c d e f g h i j k l m n o p q r s t u v w x y z +A B C D E F G H I J K L M N O P Q R S T U V W X Y Z +1 2 3 4 5 6 7 8 9 10 +1 2 3 4 5 6 7 8 9 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ends_with.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ends_with.test new file mode 100644 index 0000000..9ad5e5e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ends_with.test @@ -0,0 +1,26 @@ +--TEST-- +Twig supports the "ends with" operator +--TEMPLATE-- +{{ 'foo' ends with 'o' ? 'OK' : 'KO' }} +{{ not ('foo' ends with 'f') ? 'OK' : 'KO' }} +{{ not ('foo' ends with 'foowaytoolong') ? 'OK' : 'KO' }} +{{ 'foo' ends with '' ? 'OK' : 'KO' }} +{{ '1' ends with true ? 'OK' : 'KO' }} +{{ 1 ends with true ? 'OK' : 'KO' }} +{{ 0 ends with false ? 'OK' : 'KO' }} +{{ '' ends with false ? 'OK' : 'KO' }} +{{ false ends with false ? 'OK' : 'KO' }} +{{ false ends with '' ? 'OK' : 'KO' }} +--DATA-- +return array() +--EXPECT-- +OK +OK +OK +OK +KO +KO +KO +KO +KO +KO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/grouping.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/grouping.test new file mode 100644 index 0000000..79f8e0b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/grouping.test @@ -0,0 +1,8 @@ +--TEST-- +Twig supports grouping of expressions +--TEMPLATE-- +{{ (2 + 2) / 2 }} +--DATA-- +return array() +--EXPECT-- +2 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/literals.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/literals.test new file mode 100644 index 0000000..7ae3bae --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/literals.test @@ -0,0 +1,22 @@ +--TEST-- +Twig supports literals +--TEMPLATE-- +1 {{ true }} +2 {{ TRUE }} +3 {{ false }} +4 {{ FALSE }} +5 {{ none }} +6 {{ NONE }} +7 {{ null }} +8 {{ NULL }} +--DATA-- +return array() +--EXPECT-- +1 1 +2 1 +3 +4 +5 +6 +7 +8 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/magic_call.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/magic_call.test new file mode 100644 index 0000000..1a27a2d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/magic_call.test @@ -0,0 +1,27 @@ +--TEST-- +Twig supports __call() for attributes +--TEMPLATE-- +{{ foo.foo }} +{{ foo.bar }} +--DATA-- +class TestClassForMagicCallAttributes +{ + public function getBar() + { + return 'bar_from_getbar'; + } + + public function __call($method, $arguments) + { + if ('foo' === $method) { + return 'foo_from_call'; + } + + return false; + } +} + +return array('foo' => new TestClassForMagicCallAttributes()) +--EXPECT-- +foo_from_call +bar_from_getbar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/matches.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/matches.test new file mode 100644 index 0000000..b6c7716 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/matches.test @@ -0,0 +1,12 @@ +--TEST-- +Twig supports the "matches" operator +--TEMPLATE-- +{{ 'foo' matches '/o/' ? 'OK' : 'KO' }} +{{ 'foo' matches '/^fo/' ? 'OK' : 'KO' }} +{{ 'foo' matches '/O/i' ? 'OK' : 'KO' }} +--DATA-- +return array() +--EXPECT-- +OK +OK +OK diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/method_call.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/method_call.test new file mode 100644 index 0000000..5f801e6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/method_call.test @@ -0,0 +1,28 @@ +--TEST-- +Twig supports method calls +--TEMPLATE-- +{{ items.foo.foo }} +{{ items.foo.getFoo() }} +{{ items.foo.bar }} +{{ items.foo['bar'] }} +{{ items.foo.bar('a', 43) }} +{{ items.foo.bar(foo) }} +{{ items.foo.self.foo() }} +{{ items.foo.is }} +{{ items.foo.in }} +{{ items.foo.not }} +--DATA-- +return array('foo' => 'bar', 'items' => array('foo' => new TwigTestFoo(), 'bar' => 'foo')) +--CONFIG-- +return array('strict_variables' => false) +--EXPECT-- +foo +foo +bar + +bar_a-43 +bar_bar +foo +is +in +not diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/negative_numbers.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/negative_numbers.test new file mode 100644 index 0000000..1853b1b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/negative_numbers.test @@ -0,0 +1,18 @@ +--TEST-- +Twig manages negative numbers correctly +--TEMPLATE-- +{{ -1 }} +{{ - 1 }} +{{ 5 - 1 }} +{{ 5-1 }} +{{ 5 + -1 }} +{{ 5 + - 1 }} +--DATA-- +return array() +--EXPECT-- +-1 +-1 +4 +4 +4 +4 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/operators_as_variables.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/operators_as_variables.test new file mode 100644 index 0000000..fe29d08 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/operators_as_variables.test @@ -0,0 +1,16 @@ +--TEST-- +Twig allows to use named operators as variable names +--TEMPLATE-- +{% for match in matches %} + {{- match }} +{% endfor %} +{{ in }} +{{ is }} +--DATA-- +return array('matches' => array(1, 2, 3), 'in' => 'in', 'is' => 'is') +--EXPECT-- +1 +2 +3 +in +is diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/postfix.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/postfix.test new file mode 100644 index 0000000..542c350 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/postfix.test @@ -0,0 +1,22 @@ +--TEST-- +Twig parses postfix expressions +--TEMPLATE-- +{% import _self as macros %} + +{% macro foo() %}foo{% endmacro %} + +{{ 'a' }} +{{ 'a'|upper }} +{{ ('a')|upper }} +{{ -1|upper }} +{{ macros.foo() }} +{{ (macros).foo() }} +--DATA-- +return array(); +--EXPECT-- +a +A +A +-1 +foo +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/power.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/power.test new file mode 100644 index 0000000..eacc98f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/power.test @@ -0,0 +1,20 @@ +--TEST-- +Twig parses power expressions +--TEMPLATE-- +{{ 2**3 }} +{{ (-2)**3 }} +{{ (-2)**(-3) }} +{{ a ** a }} +{{ a ** b }} +{{ b ** a }} +{{ b ** b }} +--DATA-- +return array('a' => 4, 'b' => -2); +--EXPECT-- +8 +-8 +-0.125 +256 +0.0625 +16 +0.25 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/sameas.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/sameas.test new file mode 100644 index 0000000..601201d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/sameas.test @@ -0,0 +1,21 @@ +--TEST-- +Twig supports the "same as" operator +--TEMPLATE-- +{{ 1 is same as(1) ? 'OK' }} +{{ 1 is not same as(true) ? 'OK' }} +{{ 1 is same as(1) ? 'OK' }} +{{ 1 is not same as(true) ? 'OK' }} +{{ 1 is same as (1) ? 'OK' }} +{{ 1 is not + same + as + (true) ? 'OK' }} +--DATA-- +return array() +--EXPECT-- +OK +OK +OK +OK +OK +OK diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/starts_with.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/starts_with.test new file mode 100644 index 0000000..75d331e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/starts_with.test @@ -0,0 +1,27 @@ +--TEST-- +Twig supports the "starts with" operator +--TEMPLATE-- +{{ 'foo' starts with 'f' ? 'OK' : 'KO' }} +{{ not ('foo' starts with 'oo') ? 'OK' : 'KO' }} +{{ not ('foo' starts with 'foowaytoolong') ? 'OK' : 'KO' }} +{{ 'foo' starts with 'f' ? 'OK' : 'KO' }} +{{ 'foo' starts +with 'f' ? 'OK' : 'KO' }} +{{ 'foo' starts with '' ? 'OK' : 'KO' }} +{{ '1' starts with true ? 'OK' : 'KO' }} +{{ '' starts with false ? 'OK' : 'KO' }} +{{ 'a' starts with false ? 'OK' : 'KO' }} +{{ false starts with '' ? 'OK' : 'KO' }} +--DATA-- +return array() +--EXPECT-- +OK +OK +OK +OK +OK +OK +KO +KO +KO +KO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/strings.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/strings.test new file mode 100644 index 0000000..a911661 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/strings.test @@ -0,0 +1,10 @@ +--TEST-- +Twig supports string interpolation +--TEMPLATE-- +{{ "foo #{"foo #{bar} baz"} baz" }} +{{ "foo #{bar}#{bar} baz" }} +--DATA-- +return array('bar' => 'BAR'); +--EXPECT-- +foo foo BAR baz baz +foo BARBAR baz diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator.test new file mode 100644 index 0000000..0e6fa96 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator.test @@ -0,0 +1,18 @@ +--TEST-- +Twig supports the ternary operator +--TEMPLATE-- +{{ 1 ? 'YES' : 'NO' }} +{{ 0 ? 'YES' : 'NO' }} +{{ 0 ? 'YES' : (1 ? 'YES1' : 'NO1') }} +{{ 0 ? 'YES' : (0 ? 'YES1' : 'NO1') }} +{{ 1 == 1 ? 'foo
    ':'' }} +{{ foo ~ (bar ? ('-' ~ bar) : '') }} +--DATA-- +return array('foo' => 'foo', 'bar' => 'bar') +--EXPECT-- +YES +NO +YES1 +NO1 +foo
    +foo-bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator_noelse.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator_noelse.test new file mode 100644 index 0000000..fdc660f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator_noelse.test @@ -0,0 +1,10 @@ +--TEST-- +Twig supports the ternary operator +--TEMPLATE-- +{{ 1 ? 'YES' }} +{{ 0 ? 'YES' }} +--DATA-- +return array() +--EXPECT-- +YES + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator_nothen.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator_nothen.test new file mode 100644 index 0000000..9057e83 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/ternary_operator_nothen.test @@ -0,0 +1,10 @@ +--TEST-- +Twig supports the ternary operator +--TEMPLATE-- +{{ 'YES' ?: 'NO' }} +{{ 0 ?: 'NO' }} +--DATA-- +return array() +--EXPECT-- +YES +NO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/two_word_operators_as_variables.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/two_word_operators_as_variables.test new file mode 100644 index 0000000..0eaabb4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/two_word_operators_as_variables.test @@ -0,0 +1,8 @@ +--TEST-- +Twig does not allow to use two-word named operators as variable names +--TEMPLATE-- +{{ starts with }} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: Unexpected token "operator" of value "starts with" in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary.test new file mode 100644 index 0000000..b79219a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary.test @@ -0,0 +1,12 @@ +--TEST-- +Twig supports unary operators (not, -, +) +--TEMPLATE-- +{{ not 1 }}/{{ not 0 }} +{{ +1 + 1 }}/{{ -1 - 1 }} +{{ not (false or true) }} +--DATA-- +return array() +--EXPECT-- +/1 +2/-2 + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary_macro_arguments.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary_macro_arguments.test new file mode 100644 index 0000000..ad84a9c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary_macro_arguments.test @@ -0,0 +1,22 @@ +--TEST-- +Twig manages negative numbers as default parameters +--TEMPLATE-- +{% import _self as macros %} +{{ macros.negative_number1() }} +{{ macros.negative_number2() }} +{{ macros.negative_number3() }} +{{ macros.positive_number1() }} +{{ macros.positive_number2() }} +{% macro negative_number1(nb=-1) %}{{ nb }}{% endmacro %} +{% macro negative_number2(nb = --1) %}{{ nb }}{% endmacro %} +{% macro negative_number3(nb = - 1) %}{{ nb }}{% endmacro %} +{% macro positive_number1(nb = +1) %}{{ nb }}{% endmacro %} +{% macro positive_number2(nb = ++1) %}{{ nb }}{% endmacro %} +--DATA-- +return array() +--EXPECT-- +-1 +1 +-1 +1 +1 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary_precedence.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary_precedence.test new file mode 100644 index 0000000..cc6eef8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/expressions/unary_precedence.test @@ -0,0 +1,14 @@ +--TEST-- +Twig unary operators precedence +--TEMPLATE-- +{{ -1 - 1 }} +{{ -1 - -1 }} +{{ -1 * -1 }} +{{ 4 / -1 * 5 }} +--DATA-- +return array() +--EXPECT-- +-2 +0 +1 +-20 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/abs.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/abs.test new file mode 100644 index 0000000..27e93fd --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/abs.test @@ -0,0 +1,30 @@ +--TEST-- +"abs" filter +--TEMPLATE-- +{{ (-5.5)|abs }} +{{ (-5)|abs }} +{{ (-0)|abs }} +{{ 0|abs }} +{{ 5|abs }} +{{ 5.5|abs }} +{{ number1|abs }} +{{ number2|abs }} +{{ number3|abs }} +{{ number4|abs }} +{{ number5|abs }} +{{ number6|abs }} +--DATA-- +return array('number1' => -5.5, 'number2' => -5, 'number3' => -0, 'number4' => 0, 'number5' => 5, 'number6' => 5.5) +--EXPECT-- +5.5 +5 +0 +0 +5 +5.5 +5.5 +5 +0 +0 +5 +5.5 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch.test new file mode 100644 index 0000000..cb6de7f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch.test @@ -0,0 +1,31 @@ +--TEST-- +"batch" filter +--TEMPLATE-- +{% for row in items|batch(3) %} +
    + {% for column in row %} +
    {{ column }}
    + {% endfor %} +
    +{% endfor %} +--DATA-- +return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) +--EXPECT-- +
    +
    a
    +
    b
    +
    c
    +
    +
    +
    d
    +
    e
    +
    f
    +
    +
    +
    g
    +
    h
    +
    i
    +
    +
    +
    j
    +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_float.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_float.test new file mode 100644 index 0000000..e2ec4be --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_float.test @@ -0,0 +1,29 @@ +--TEST-- +"batch" filter +--TEMPLATE-- +{% for row in items|batch(3.1) %} +
    + {% for column in row %} +
    {{ column }}
    + {% endfor %} +
    +{% endfor %} +--DATA-- +return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) +--EXPECT-- +
    +
    a
    +
    b
    +
    c
    +
    d
    +
    +
    +
    e
    +
    f
    +
    g
    +
    h
    +
    +
    +
    i
    +
    j
    +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_empty_fill.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_empty_fill.test new file mode 100644 index 0000000..af996f2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_empty_fill.test @@ -0,0 +1,37 @@ +--TEST-- +"batch" filter +--TEMPLATE-- + +{% for row in items|batch(3, '') %} + + {% for column in row %} + + {% endfor %} + +{% endfor %} +
    {{ column }}
    +--DATA-- +return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) +--EXPECT-- + + + + + + + + + + + + + + + + + + + + + +
    abc
    def
    ghi
    j
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_exact_elements.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_exact_elements.test new file mode 100644 index 0000000..72483f4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_exact_elements.test @@ -0,0 +1,33 @@ +--TEST-- +"batch" filter +--TEMPLATE-- +{% for row in items|batch(3, 'fill') %} +
    + {% for column in row %} +
    {{ column }}
    + {% endfor %} +
    +{% endfor %} +--DATA-- +return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l')) +--EXPECT-- +
    +
    a
    +
    b
    +
    c
    +
    +
    +
    d
    +
    e
    +
    f
    +
    +
    +
    g
    +
    h
    +
    i
    +
    +
    +
    j
    +
    k
    +
    l
    +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_fill.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_fill.test new file mode 100644 index 0000000..746295f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_fill.test @@ -0,0 +1,37 @@ +--TEST-- +"batch" filter +--TEMPLATE-- + +{% for row in items|batch(3, 'fill') %} + + {% for column in row %} + + {% endfor %} + +{% endfor %} +
    {{ column }}
    +--DATA-- +return array('items' => array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')) +--EXPECT-- + + + + + + + + + + + + + + + + + + + + + +
    abc
    def
    ghi
    jfillfill
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_keys.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_keys.test new file mode 100644 index 0000000..6015380 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_keys.test @@ -0,0 +1,10 @@ +--TEST-- +"batch" filter preserves array keys +--TEMPLATE-- +{{ {'foo': 'bar', 'key': 'value'}|batch(4)|first|keys|join(',') }} +{{ {'foo': 'bar', 'key': 'value'}|batch(4, 'fill')|first|keys|join(',') }} +--DATA-- +return array() +--EXPECT-- +foo,key +foo,key,0,1 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_zero_elements.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_zero_elements.test new file mode 100644 index 0000000..b9c058d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/batch_with_zero_elements.test @@ -0,0 +1,10 @@ +--TEST-- +"batch" filter with zero elements +--TEMPLATE-- +{{ []|batch(3)|length }} +{{ []|batch(3, 'fill')|length }} +--DATA-- +return array() +--EXPECT-- +0 +0 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/convert_encoding.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/convert_encoding.test new file mode 100644 index 0000000..380b04b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/convert_encoding.test @@ -0,0 +1,10 @@ +--TEST-- +"convert_encoding" filter +--CONDITION-- +function_exists('iconv') || function_exists('mb_convert_encoding') +--TEMPLATE-- +{{ "愛していますか?"|convert_encoding('ISO-2022-JP', 'UTF-8')|convert_encoding('UTF-8', 'ISO-2022-JP') }} +--DATA-- +return array() +--EXPECT-- +愛していますか? diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date.test new file mode 100644 index 0000000..d17e5e2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date.test @@ -0,0 +1,90 @@ +--TEST-- +"date" filter +--TEMPLATE-- +{{ date1|date }} +{{ date1|date('d/m/Y') }} +{{ date1|date('d/m/Y H:i:s', 'Asia/Hong_Kong') }} +{{ date1|date('d/m/Y H:i:s P', 'Asia/Hong_Kong') }} +{{ date1|date('d/m/Y H:i:s P', 'America/Chicago') }} +{{ date1|date('e') }} +{{ date1|date('d/m/Y H:i:s') }} + +{{ date2|date }} +{{ date2|date('d/m/Y') }} +{{ date2|date('d/m/Y H:i:s', 'Asia/Hong_Kong') }} +{{ date2|date('d/m/Y H:i:s', timezone1) }} +{{ date2|date('d/m/Y H:i:s') }} + +{{ date3|date }} +{{ date3|date('d/m/Y') }} + +{{ date4|date }} +{{ date4|date('d/m/Y') }} + +{{ date5|date }} +{{ date5|date('d/m/Y') }} + +{{ date6|date('d/m/Y H:i:s P', 'Europe/Paris') }} +{{ date6|date('d/m/Y H:i:s P', 'Asia/Hong_Kong') }} +{{ date6|date('d/m/Y H:i:s P', false) }} +{{ date6|date('e', 'Europe/Paris') }} +{{ date6|date('e', false) }} + +{{ date7|date }} +{{ date7|date(timezone='Europe/Paris') }} +{{ date7|date(timezone='Asia/Hong_Kong') }} +{{ date7|date(timezone=false) }} +{{ date7|date(timezone='Indian/Mauritius') }} + +{{ '2010-01-28 15:00:00'|date(timezone="Europe/Paris") }} +{{ '2010-01-28 15:00:00'|date(timezone="Asia/Hong_Kong") }} +--DATA-- +date_default_timezone_set('Europe/Paris'); +return array( + 'date1' => mktime(13, 45, 0, 10, 4, 2010), + 'date2' => new DateTime('2010-10-04 13:45'), + 'date3' => '2010-10-04 13:45', + 'date4' => 1286199900, // DateTime::createFromFormat('Y-m-d H:i', '2010-10-04 13:45', new DateTimeZone('UTC'))->getTimestamp() -- A unixtimestamp is always GMT + 'date5' => -189291360, // DateTime::createFromFormat('Y-m-d H:i', '1964-01-02 03:04', new DateTimeZone('UTC'))->getTimestamp(), + 'date6' => new DateTime('2010-10-04 13:45', new DateTimeZone('America/New_York')), + 'date7' => '2010-01-28T15:00:00+04:00', + 'timezone1' => new DateTimeZone('America/New_York'), +) +--EXPECT-- +October 4, 2010 13:45 +04/10/2010 +04/10/2010 19:45:00 +04/10/2010 19:45:00 +08:00 +04/10/2010 06:45:00 -05:00 +Europe/Paris +04/10/2010 13:45:00 + +October 4, 2010 13:45 +04/10/2010 +04/10/2010 19:45:00 +04/10/2010 07:45:00 +04/10/2010 13:45:00 + +October 4, 2010 13:45 +04/10/2010 + +October 4, 2010 15:45 +04/10/2010 + +January 2, 1964 04:04 +02/01/1964 + +04/10/2010 19:45:00 +02:00 +05/10/2010 01:45:00 +08:00 +04/10/2010 13:45:00 -04:00 +Europe/Paris +America/New_York + +January 28, 2010 12:00 +January 28, 2010 12:00 +January 28, 2010 19:00 +January 28, 2010 15:00 +January 28, 2010 15:00 + +January 28, 2010 15:00 +January 28, 2010 22:00 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_default_format.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_default_format.test new file mode 100644 index 0000000..6ad504c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_default_format.test @@ -0,0 +1,14 @@ +--TEST-- +"date" filter +--TEMPLATE-- +{{ date1|date }} +{{ date1|date('d/m/Y') }} +--DATA-- +date_default_timezone_set('UTC'); +$twig->getExtension('Twig_Extension_Core')->setDateFormat('Y-m-d', '%d days %h hours'); +return array( + 'date1' => mktime(13, 45, 0, 10, 4, 2010), +) +--EXPECT-- +2010-10-04 +04/10/2010 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_default_format_interval.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_default_format_interval.test new file mode 100644 index 0000000..be4a642 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_default_format_interval.test @@ -0,0 +1,16 @@ +--TEST-- +"date" filter (interval support as of PHP 5.3) +--CONDITION-- +version_compare(phpversion(), '5.3.0', '>=') +--TEMPLATE-- +{{ date2|date }} +{{ date2|date('%d days') }} +--DATA-- +date_default_timezone_set('UTC'); +$twig->getExtension('Twig_Extension_Core')->setDateFormat('Y-m-d', '%d days %h hours'); +return array( + 'date2' => new DateInterval('P2D'), +) +--EXPECT-- +2 days 0 hours +2 days diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_immutable.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_immutable.test new file mode 100644 index 0000000..4e18325 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_immutable.test @@ -0,0 +1,37 @@ +--TEST-- +"date" filter +--CONDITION-- +version_compare(phpversion(), '5.5.0', '>=') +--TEMPLATE-- +{{ date1|date }} +{{ date1|date('d/m/Y') }} +{{ date1|date('d/m/Y H:i:s', 'Asia/Hong_Kong') }} +{{ date1|date('d/m/Y H:i:s', timezone1) }} +{{ date1|date('d/m/Y H:i:s') }} +{{ date1|date_modify('+1 hour')|date('d/m/Y H:i:s') }} + +{{ date2|date('d/m/Y H:i:s P', 'Europe/Paris') }} +{{ date2|date('d/m/Y H:i:s P', 'Asia/Hong_Kong') }} +{{ date2|date('d/m/Y H:i:s P', false) }} +{{ date2|date('e', 'Europe/Paris') }} +{{ date2|date('e', false) }} +--DATA-- +date_default_timezone_set('Europe/Paris'); +return array( + 'date1' => new DateTimeImmutable('2010-10-04 13:45'), + 'date2' => new DateTimeImmutable('2010-10-04 13:45', new DateTimeZone('America/New_York')), + 'timezone1' => new DateTimeZone('America/New_York'), +) +--EXPECT-- +October 4, 2010 13:45 +04/10/2010 +04/10/2010 19:45:00 +04/10/2010 07:45:00 +04/10/2010 13:45:00 +04/10/2010 14:45:00 + +04/10/2010 19:45:00 +02:00 +05/10/2010 01:45:00 +08:00 +04/10/2010 13:45:00 -04:00 +Europe/Paris +America/New_York diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_interval.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_interval.test new file mode 100644 index 0000000..0c8c6f1 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_interval.test @@ -0,0 +1,19 @@ +--TEST-- +"date" filter (interval support as of PHP 5.3) +--CONDITION-- +version_compare(phpversion(), '5.3.0', '>=') +--TEMPLATE-- +{{ date1|date }} +{{ date1|date('%d days %h hours') }} +{{ date1|date('%d days %h hours', timezone1) }} +--DATA-- +date_default_timezone_set('UTC'); +return array( + 'date1' => new DateInterval('P2D'), + // This should have no effect on DateInterval formatting + 'timezone1' => new DateTimeZone('America/New_York'), +) +--EXPECT-- +2 days +2 days 0 hours +2 days 0 hours diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_modify.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_modify.test new file mode 100644 index 0000000..53d3a69 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_modify.test @@ -0,0 +1,14 @@ +--TEST-- +"date_modify" filter +--TEMPLATE-- +{{ date1|date_modify('-1day')|date('Y-m-d H:i:s') }} +{{ date2|date_modify('-1day')|date('Y-m-d H:i:s') }} +--DATA-- +date_default_timezone_set('UTC'); +return array( + 'date1' => '2010-10-04 13:45', + 'date2' => new DateTime('2010-10-04 13:45'), +) +--EXPECT-- +2010-10-03 13:45:00 +2010-10-03 13:45:00 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_namedargs.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_namedargs.test new file mode 100644 index 0000000..4ecde8a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/date_namedargs.test @@ -0,0 +1,13 @@ +--TEST-- +"date" filter +--TEMPLATE-- +{{ date|date(format='d/m/Y H:i:s P', timezone='America/Chicago') }} +{{ date|date(timezone='America/Chicago', format='d/m/Y H:i:s P') }} +{{ date|date('d/m/Y H:i:s P', timezone='America/Chicago') }} +--DATA-- +date_default_timezone_set('UTC'); +return array('date' => mktime(13, 45, 0, 10, 4, 2010)) +--EXPECT-- +04/10/2010 08:45:00 -05:00 +04/10/2010 08:45:00 -05:00 +04/10/2010 08:45:00 -05:00 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/default.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/default.test new file mode 100644 index 0000000..b8d1d66 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/default.test @@ -0,0 +1,150 @@ +--TEST-- +"default" filter +--TEMPLATE-- +Variable: +{{ definedVar |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ zeroVar |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ emptyVar |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ nullVar |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ undefinedVar |default('default') is same as('default') ? 'ok' : 'ko' }} +Array access: +{{ nested.definedVar |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ nested['definedVar'] |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ nested.zeroVar |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ nested.emptyVar |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ nested.nullVar |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ nested.undefinedVar |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ nested['undefinedVar'] |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ undefinedVar.foo |default('default') is same as('default') ? 'ok' : 'ko' }} +Plain values: +{{ 'defined' |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ 0 |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ '' |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ null |default('default') is same as('default') ? 'ok' : 'ko' }} +Precedence: +{{ 'o' ~ nullVar |default('k') }} +{{ 'o' ~ nested.nullVar |default('k') }} +Object methods: +{{ object.foo |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ object.undefinedMethod |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ object.getFoo() |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ object.getFoo('a') |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ object.undefinedMethod() |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ object.undefinedMethod('a') |default('default') is same as('default') ? 'ok' : 'ko' }} +Deep nested: +{{ nested.undefinedVar.foo.bar |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ nested.definedArray.0 |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ nested['definedArray'][0] |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ object.self.foo |default('default') is same as('default') ? 'ko' : 'ok' }} +{{ object.self.undefinedMethod |default('default') is same as('default') ? 'ok' : 'ko' }} +{{ object.undefinedMethod.self |default('default') is same as('default') ? 'ok' : 'ko' }} +--DATA-- +return array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'emptyVar' => '', + 'nullVar' => null, + 'nested' => array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'emptyVar' => '', + 'nullVar' => null, + 'definedArray' => array(0), + ), + 'object' => new TwigTestFoo(), +) +--CONFIG-- +return array('strict_variables' => false) +--EXPECT-- +Variable: +ok +ok +ok +ok +ok +Array access: +ok +ok +ok +ok +ok +ok +ok +ok +Plain values: +ok +ok +ok +ok +Precedence: +ok +ok +Object methods: +ok +ok +ok +ok +ok +ok +Deep nested: +ok +ok +ok +ok +ok +ok +--DATA-- +return array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'emptyVar' => '', + 'nullVar' => null, + 'nested' => array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'emptyVar' => '', + 'nullVar' => null, + 'definedArray' => array(0), + ), + 'object' => new TwigTestFoo(), +) +--CONFIG-- +return array('strict_variables' => true) +--EXPECT-- +Variable: +ok +ok +ok +ok +ok +Array access: +ok +ok +ok +ok +ok +ok +ok +ok +Plain values: +ok +ok +ok +ok +Precedence: +ok +ok +Object methods: +ok +ok +ok +ok +ok +ok +Deep nested: +ok +ok +ok +ok +ok +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/dynamic_filter.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/dynamic_filter.test new file mode 100644 index 0000000..93c5913 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/dynamic_filter.test @@ -0,0 +1,10 @@ +--TEST-- +dynamic filter +--TEMPLATE-- +{{ 'bar'|foo_path }} +{{ 'bar'|a_foo_b_bar }} +--DATA-- +return array() +--EXPECT-- +foo/bar +a/b/bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape.test new file mode 100644 index 0000000..a606c10 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape.test @@ -0,0 +1,8 @@ +--TEST-- +"escape" filter +--TEMPLATE-- +{{ "foo
    "|e }} +--DATA-- +return array() +--EXPECT-- +foo <br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_html_attr.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_html_attr.test new file mode 100644 index 0000000..009a245 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_html_attr.test @@ -0,0 +1,8 @@ +--TEST-- +"escape" filter does not escape with the html strategy when using the html_attr strategy +--TEMPLATE-- +{{ '
    '|escape('html_attr') }} +--DATA-- +return array() +--EXPECT-- +<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_javascript.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_javascript.test new file mode 100644 index 0000000..8e72781 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_javascript.test @@ -0,0 +1,8 @@ +--TEST-- +"escape" filter +--TEMPLATE-- +{{ "é ♜ 𝌆"|e('js') }} +--DATA-- +return array() +--EXPECT-- +\u00E9\u0020\u265C\u0020\uD834\uDF06 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_non_supported_charset.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_non_supported_charset.test new file mode 100644 index 0000000..bba26a0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/escape_non_supported_charset.test @@ -0,0 +1,8 @@ +--TEST-- +"escape" filter +--TEMPLATE-- +{{ "愛していますか?
    "|e }} +--DATA-- +return array() +--EXPECT-- +愛していますか? <br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/first.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/first.test new file mode 100644 index 0000000..aa54645 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/first.test @@ -0,0 +1,17 @@ +--TEST-- +"first" filter +--TEMPLATE-- +{{ [1, 2, 3, 4]|first }} +{{ {a: 1, b: 2, c: 3, d: 4}|first }} +{{ '1234'|first }} +{{ arr|first }} +{{ 'Ä€é'|first }} +{{ ''|first }} +--DATA-- +return array('arr' => new ArrayObject(array(1, 2, 3, 4))) +--EXPECT-- +1 +1 +1 +1 +Ä diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/force_escape.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/force_escape.test new file mode 100644 index 0000000..eb9cba7 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/force_escape.test @@ -0,0 +1,18 @@ +--TEST-- +"escape" filter +--TEMPLATE-- +{% set foo %} + foo
    +{% endset %} + +{{ foo|e('html') -}} +{{ foo|e('js') }} +{% autoescape true %} + {{ foo }} +{% endautoescape %} +--DATA-- +return array() +--EXPECT-- + foo<br /> +\u0020\u0020\u0020\u0020foo\u003Cbr\u0020\/\u003E\n + foo
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/format.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/format.test new file mode 100644 index 0000000..97221ff --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/format.test @@ -0,0 +1,8 @@ +--TEST-- +"format" filter +--TEMPLATE-- +{{ string|format(foo, 3) }} +--DATA-- +return array('string' => '%s/%d', 'foo' => 'bar') +--EXPECT-- +bar/3 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/join.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/join.test new file mode 100644 index 0000000..b342c17 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/join.test @@ -0,0 +1,12 @@ +--TEST-- +"join" filter +--TEMPLATE-- +{{ ["foo", "bar"]|join(', ') }} +{{ foo|join(', ') }} +{{ bar|join(', ') }} +--DATA-- +return array('foo' => new TwigTestFoo(), 'bar' => new ArrayObject(array(3, 4))) +--EXPECT-- +foo, bar +1, 2 +3, 4 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/json_encode.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/json_encode.test new file mode 100644 index 0000000..1738d40 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/json_encode.test @@ -0,0 +1,12 @@ +--TEST-- +"json_encode" filter +--TEMPLATE-- +{{ "foo"|json_encode|raw }} +{{ foo|json_encode|raw }} +{{ [foo, "foo"]|json_encode|raw }} +--DATA-- +return array('foo' => new Twig_Markup('foo', 'UTF-8')) +--EXPECT-- +"foo" +"foo" +["foo","foo"] diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/last.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/last.test new file mode 100644 index 0000000..1b8031e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/last.test @@ -0,0 +1,17 @@ +--TEST-- +"last" filter +--TEMPLATE-- +{{ [1, 2, 3, 4]|last }} +{{ {a: 1, b: 2, c: 3, d: 4}|last }} +{{ '1234'|last }} +{{ arr|last }} +{{ 'Ä€é'|last }} +{{ ''|last }} +--DATA-- +return array('arr' => new ArrayObject(array(1, 2, 3, 4))) +--EXPECT-- +4 +4 +4 +4 +é diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/length.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/length.test new file mode 100644 index 0000000..bad5cf5 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/length.test @@ -0,0 +1,37 @@ +--TEST-- +"length" filter +--TEMPLATE-- +{{ array|length }} +{{ string|length }} +{{ number|length }} +{{ to_string_able|length }} +{{ countable|length }} +{{ iterator_aggregate|length }} +{{ null|length }} +{{ magic|length }} +{{ non_countable|length }} +{{ simple_xml_element|length }} +--DATA-- +return array( + 'array' => array(1, 4), + 'string' => 'foo', + 'number' => 1000, + 'to_string_able' => new ToStringStub('foobar'), + 'countable' => new CountableStub(42), /* also asserts we do *not* call __toString() */ + 'iterator_aggregate' => new IteratorAggregateStub(array('a', 'b', 'c')), /* also asserts we do *not* call __toString() */ + 'null' => null, + 'magic' => new MagicCallStub(), /* used to assert we do *not* call __call */ + 'non_countable' => new \StdClass(), + 'simple_xml_element' => new \SimpleXMLElement(''), +); +--EXPECT-- +2 +3 +4 +6 +42 +3 +0 +1 +1 +2 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/length_utf8.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/length_utf8.test new file mode 100644 index 0000000..5d5e243 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/length_utf8.test @@ -0,0 +1,12 @@ +--TEST-- +"length" filter +--CONDITION-- +function_exists('mb_get_info') +--TEMPLATE-- +{{ string|length }} +{{ markup|length }} +--DATA-- +return array('string' => 'été', 'markup' => new Twig_Markup('foo', 'UTF-8')) +--EXPECT-- +3 +3 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/merge.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/merge.test new file mode 100644 index 0000000..81371a4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/merge.test @@ -0,0 +1,18 @@ +--TEST-- +"merge" filter +--TEMPLATE-- +{{ items|merge({'bar': 'foo'})|join }} +{{ items|merge({'bar': 'foo'})|keys|join }} +{{ {'bar': 'foo'}|merge(items)|join }} +{{ {'bar': 'foo'}|merge(items)|keys|join }} +{{ numerics|merge([4, 5, 6])|join }} +{{ traversable.a|merge(traversable.b)|join }} +--DATA-- +return array('items' => array('foo' => 'bar'), 'numerics' => array(1, 2, 3), 'traversable' => array('a' => new ArrayObject(array(0 => 1, 1 => 2, 2 => 3)), 'b' => new ArrayObject(array('a' => 'b')))) +--EXPECT-- +barfoo +foobar +foobar +barfoo +123456 +123b diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/nl2br.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/nl2br.test new file mode 100644 index 0000000..6545a9b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/nl2br.test @@ -0,0 +1,14 @@ +--TEST-- +"nl2br" filter +--TEMPLATE-- +{{ "I like Twig.\nYou will like it too.\n\nEverybody like it!"|nl2br }} +{{ text|nl2br }} +--DATA-- +return array('text' => "If you have some HTML\nit will be escaped.") +--EXPECT-- +I like Twig.
    +You will like it too.
    +
    +Everybody like it! +If you have some <strong>HTML</strong>
    +it will be escaped. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/number_format.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/number_format.test new file mode 100644 index 0000000..639a865 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/number_format.test @@ -0,0 +1,18 @@ +--TEST-- +"number_format" filter +--TEMPLATE-- +{{ 20|number_format }} +{{ 20.25|number_format }} +{{ 20.25|number_format(2) }} +{{ 20.25|number_format(2, ',') }} +{{ 1020.25|number_format(2, ',') }} +{{ 1020.25|number_format(2, ',', '.') }} +--DATA-- +return array(); +--EXPECT-- +20 +20 +20.25 +20,25 +1,020,25 +1.020,25 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/number_format_default.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/number_format_default.test new file mode 100644 index 0000000..65c1cdb --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/number_format_default.test @@ -0,0 +1,21 @@ +--TEST-- +"number_format" filter with defaults. +--TEMPLATE-- +{{ 20|number_format }} +{{ 20.25|number_format }} +{{ 20.25|number_format(1) }} +{{ 20.25|number_format(2, ',') }} +{{ 1020.25|number_format }} +{{ 1020.25|number_format(2, ',') }} +{{ 1020.25|number_format(2, ',', '.') }} +--DATA-- +$twig->getExtension('Twig_Extension_Core')->setNumberFormat(2, '!', '='); +return array(); +--EXPECT-- +20!00 +20!25 +20!3 +20,25 +1=020!25 +1=020,25 +1.020,25 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/replace.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/replace.test new file mode 100644 index 0000000..06be7e2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/replace.test @@ -0,0 +1,12 @@ +--TEST-- +"replace" filter +--TEMPLATE-- +{{ "I liké %this% and %that%."|replace({'%this%': "foo", '%that%': "bar"}) }} +{{ 'I like single replace operation only %that%'|replace({'%that%' : '%that%1'}) }} +{{ 'I like %this% and %that%.'|replace(traversable) }} +--DATA-- +return array('traversable' => new ArrayObject(array('%this%' => 'foo', '%that%' => 'bar'))) +--EXPECT-- +I liké foo and bar. +I like single replace operation only %that%1 +I like foo and bar. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/replace_invalid_arg.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/replace_invalid_arg.test new file mode 100644 index 0000000..2143a86 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/replace_invalid_arg.test @@ -0,0 +1,8 @@ +--TEST-- +Exception for invalid argument type in replace call +--TEMPLATE-- +{{ 'test %foo%'|replace(stdClass) }} +--DATA-- +return array('stdClass' => new stdClass()) +--EXCEPTION-- +Twig_Error_Runtime: The "replace" filter expects an array or "Traversable" as replace values, got "stdClass" in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/reverse.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/reverse.test new file mode 100644 index 0000000..7948ac4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/reverse.test @@ -0,0 +1,18 @@ +--TEST-- +"reverse" filter +--TEMPLATE-- +{{ [1, 2, 3, 4]|reverse|join('') }} +{{ '1234évènement'|reverse }} +{{ arr|reverse|join('') }} +{{ {'a': 'c', 'b': 'a'}|reverse()|join(',') }} +{{ {'a': 'c', 'b': 'a'}|reverse(preserveKeys=true)|join(glue=',') }} +{{ {'a': 'c', 'b': 'a'}|reverse(preserve_keys=true)|join(glue=',') }} +--DATA-- +return array('arr' => new ArrayObject(array(1, 2, 3, 4))) +--EXPECT-- +4321 +tnemenèvé4321 +4321 +a,c +a,c +a,c diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/round.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/round.test new file mode 100644 index 0000000..57806b6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/round.test @@ -0,0 +1,22 @@ +--TEST-- +"round" filter +--TEMPLATE-- +{{ 2.7|round }} +{{ 2.1|round }} +{{ 2.1234|round(3, 'floor') }} +{{ 2.1|round(0, 'ceil') }} + +{{ 21.3|round(-1)}} +{{ 21.3|round(-1, 'ceil')}} +{{ 21.3|round(-1, 'floor')}} +--DATA-- +return array() +--EXPECT-- +3 +2 +2.123 +3 + +20 +30 +20 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/slice.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/slice.test new file mode 100644 index 0000000..b49b89f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/slice.test @@ -0,0 +1,54 @@ +--TEST-- +"slice" filter +--TEMPLATE-- +{{ [1, 2, 3, 4][1:2]|join('') }} +{{ {a: 1, b: 2, c: 3, d: 4}[1:2]|join('') }} +{{ [1, 2, 3, 4][start:length]|join('') }} +{{ [1, 2, 3, 4]|slice(1, 2)|join('') }} +{{ [1, 2, 3, 4]|slice(1, 2)|keys|join('') }} +{{ [1, 2, 3, 4]|slice(1, 2, true)|keys|join('') }} +{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|join('') }} +{{ {a: 1, b: 2, c: 3, d: 4}|slice(1, 2)|keys|join('') }} +{{ '1234'|slice(1, 2) }} +{{ '1234'[1:2] }} +{{ arr|slice(1, 2)|join('') }} +{{ arr[1:2]|join('') }} +{{ arr[4:1]|join('') }} +{{ arr[3:2]|join('') }} + +{{ [1, 2, 3, 4]|slice(1)|join('') }} +{{ [1, 2, 3, 4][1:]|join('') }} +{{ '1234'|slice(1) }} +{{ '1234'[1:] }} +{{ '1234'[:1] }} + +{{ arr|slice(3)|join('') }} +{{ arr[2:]|join('') }} +{{ xml|slice(1)|join('')}} +--DATA-- +return array('start' => 1, 'length' => 2, 'arr' => new ArrayObject(array(1, 2, 3, 4)), 'xml' => new SimpleXMLElement('12')) +--EXPECT-- +23 +23 +23 +23 +01 +12 +23 +bc +23 +23 +23 +23 + +4 + +234 +234 +234 +234 +1 + +4 +34 +2 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/sort.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/sort.test new file mode 100644 index 0000000..c67c18e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/sort.test @@ -0,0 +1,12 @@ +--TEST-- +"sort" filter +--TEMPLATE-- +{{ array1|sort|join }} +{{ array2|sort|join }} +{{ traversable|sort|join }} +--DATA-- +return array('array1' => array(4, 1), 'array2' => array('foo', 'bar'), 'traversable' => new ArrayObject(array(0 => 3, 1 => 2, 2 => 1))) +--EXPECT-- +14 +barfoo +123 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/special_chars.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/special_chars.test new file mode 100644 index 0000000..dbaf7dc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/special_chars.test @@ -0,0 +1,8 @@ +--TEST-- +"§" custom filter +--TEMPLATE-- +{{ 'foo'|§ }} +--DATA-- +return array() +--EXPECT-- +§foo§ diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/split.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/split.test new file mode 100644 index 0000000..a093ed7 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/split.test @@ -0,0 +1,20 @@ +--TEST-- +"split" filter +--TEMPLATE-- +{{ "one,two,three,four,five"|split(',')|join('-') }} +{{ foo|split(',')|join('-') }} +{{ foo|split(',', 3)|join('-') }} +{{ baz|split('')|join('-') }} +{{ baz|split('', 1)|join('-') }} +{{ baz|split('', 2)|join('-') }} +{{ foo|split(',', -2)|join('-') }} +--DATA-- +return array('foo' => "one,two,three,four,five", 'baz' => '12345',) +--EXPECT-- +one-two-three-four-five +one-two-three-four-five +one-two-three,four,five +1-2-3-4-5 +1-2-3-4-5 +12-34-5 +one-two-three \ No newline at end of file diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/split_utf8.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/split_utf8.test new file mode 100644 index 0000000..305e162 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/split_utf8.test @@ -0,0 +1,24 @@ +--TEST-- +"split" filter +--CONDITION-- +function_exists('mb_get_info') +--TEMPLATE-- +{{ "é"|split('', 10)|join('-') }} +{{ foo|split(',')|join('-') }} +{{ foo|split(',', 1)|join('-') }} +{{ foo|split(',', 2)|join('-') }} +{{ foo|split(',', 3)|join('-') }} +{{ baz|split('')|join('-') }} +{{ baz|split('', 1)|join('-') }} +{{ baz|split('', 2)|join('-') }} +--DATA-- +return array('foo' => 'Ä,é,Äほ', 'baz' => 'éÄßごa',) +--EXPECT-- +é +Ä-é-Äほ +Ä,é,Äほ +Ä-é,Äほ +Ä-é-Äほ +é-Ä-ß-ご-a +é-Ä-ß-ご-a +éÄ-ßご-a \ No newline at end of file diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/static_calls.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/static_calls.test new file mode 100644 index 0000000..4e17b77 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/static_calls.test @@ -0,0 +1,10 @@ +--TEST-- +Filters as static method calls +--TEMPLATE-- +{{ 'foo'|static_call_string }} +{{ 'foo'|static_call_array }} +--DATA-- +return array('foo' => 'foo') +--EXPECT-- +*foo* +*foo* diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/trim.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/trim.test new file mode 100644 index 0000000..b1ef7b4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/trim.test @@ -0,0 +1,24 @@ +--TEST-- +"trim" filter +--TEMPLATE-- +{{ " I like Twig. "|trim }} +{{ text|trim }} +{{ " foo/"|trim("/") }} +{{ "xxxI like Twig.xxx"|trim(character_mask="x", side="left") }} +{{ "xxxI like Twig.xxx"|trim(side="right", character_mask="x") }} +{{ "xxxI like Twig.xxx"|trim("x", "right") }} +{{ "/ foo/"|trim("/", "left") }} +{{ "/ foo/"|trim(character_mask="/", side="left") }} +{{ " do nothing. "|trim("", "right") }} +--DATA-- +return array('text' => " If you have some HTML it will be escaped. ") +--EXPECT-- +I like Twig. +If you have some <strong>HTML</strong> it will be escaped. + foo +I like Twig.xxx +xxxI like Twig. +xxxI like Twig. + foo/ + foo/ + do nothing. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/urlencode.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/urlencode.test new file mode 100644 index 0000000..8726159 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/urlencode.test @@ -0,0 +1,16 @@ +--TEST-- +"url_encode" filter +--CONDITION-- +defined('PHP_QUERY_RFC3986') +--TEMPLATE-- +{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode }} +{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode|raw }} +{{ {}|url_encode|default("default") }} +{{ 'spéßi%le%c0d@dspa ce'|url_encode }} +--DATA-- +return array() +--EXPECT-- +foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= +foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= +default +sp%C3%A9%C3%9Fi%25le%25c0d%40dspa%20ce diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/urlencode_deprecated.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/urlencode_deprecated.test new file mode 100644 index 0000000..35e5039 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/filters/urlencode_deprecated.test @@ -0,0 +1,16 @@ +--TEST-- +"url_encode" filter for PHP < 5.4 +--CONDITION-- +defined('PHP_QUERY_RFC3986') +--TEMPLATE-- +{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode }} +{{ {foo: "bar", number: 3, "spéßi%l": "e%c0d@d", "spa ce": ""}|url_encode|raw }} +{{ {}|url_encode|default("default") }} +{{ 'spéßi%le%c0d@dspa ce'|url_encode }} +--DATA-- +return array() +--EXPECT-- +foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= +foo=bar&number=3&sp%C3%A9%C3%9Fi%25l=e%25c0d%40d&spa%20ce= +default +sp%C3%A9%C3%9Fi%25le%25c0d%40dspa%20ce diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/attribute.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/attribute.test new file mode 100644 index 0000000..71b2038 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/attribute.test @@ -0,0 +1,18 @@ +--TEST-- +"attribute" function +--TEMPLATE-- +{{ attribute(obj, method) }} +{{ attribute(array, item) }} +{{ attribute(obj, "bar", ["a", "b"]) }} +{{ attribute(obj, "bar", arguments) }} +{{ attribute(obj, method) is defined ? 'ok' : 'ko' }} +{{ attribute(obj, nonmethod) is defined ? 'ok' : 'ko' }} +--DATA-- +return array('obj' => new TwigTestFoo(), 'method' => 'foo', 'array' => array('foo' => 'bar'), 'item' => 'foo', 'nonmethod' => 'xxx', 'arguments' => array('a', 'b')) +--EXPECT-- +foo +bar +bar_a-b +bar_a-b +ok +ko diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block.test new file mode 100644 index 0000000..8e54059 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block.test @@ -0,0 +1,12 @@ +--TEST-- +"block" function +--TEMPLATE-- +{% extends 'base.twig' %} +{% block bar %}BAR{% endblock %} +--TEMPLATE(base.twig)-- +{% block foo %}{{ block('bar') }}{% endblock %} +{% block bar %}BAR_BASE{% endblock %} +--DATA-- +return array() +--EXPECT-- +BARBAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block_with_template.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block_with_template.test new file mode 100644 index 0000000..8305eb6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block_with_template.test @@ -0,0 +1,22 @@ +--TEST-- +"block" function with a template argument +--TEMPLATE-- +{{ block('foo', 'included.twig') }} +{{ block('foo', included_loaded) }} +{{ block('foo', included_loaded_internal) }} +{% set output = block('foo', 'included.twig') %} +{{ output }} +{% block foo %}NOT FOO{% endblock %} +--TEMPLATE(included.twig)-- +{% block foo %}FOO{% endblock %} +--DATA-- +return array( + 'included_loaded' => $twig->load('included.twig'), + 'included_loaded_internal' => $twig->loadTemplate('included.twig'), +) +--EXPECT-- +FOO +FOO +FOO +FOO +NOT FOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block_without_name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block_without_name.test new file mode 100644 index 0000000..665cc87 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/block_without_name.test @@ -0,0 +1,12 @@ +--TEST-- +"block" function without arguments +--TEMPLATE-- +{% extends 'base.twig' %} +{% block bar %}BAR{% endblock %} +--TEMPLATE(base.twig)-- +{% block foo %}{{ block() }}{% endblock %} +{% block bar %}BAR_BASE{% endblock %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: The "block" function takes one argument (the block name) in "base.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/constant.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/constant.test new file mode 100644 index 0000000..6312879 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/constant.test @@ -0,0 +1,10 @@ +--TEST-- +"constant" function +--TEMPLATE-- +{{ constant('DATE_W3C') == expect ? 'true' : 'false' }} +{{ constant('ARRAY_AS_PROPS', object) }} +--DATA-- +return array('expect' => DATE_W3C, 'object' => new ArrayObject(array('hi'))); +--EXPECT-- +true +2 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/cycle.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/cycle.test new file mode 100644 index 0000000..522a63b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/cycle.test @@ -0,0 +1,16 @@ +--TEST-- +"cycle" function +--TEMPLATE-- +{% for i in 0..6 %} +{{ cycle(array1, i) }}-{{ cycle(array2, i) }} +{% endfor %} +--DATA-- +return array('array1' => array('odd', 'even'), 'array2' => array('apple', 'orange', 'citrus')) +--EXPECT-- +odd-apple +even-orange +odd-citrus +even-apple +odd-orange +even-citrus +odd-apple diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/date.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/date.test new file mode 100644 index 0000000..c9f4644 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/date.test @@ -0,0 +1,27 @@ +--TEST-- +"date" function +--TEMPLATE-- +{{ date().format('r') == date('now').format('r') ? 'OK' : 'KO' }} +{{ date(date1) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} +{{ date(date2) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} +{{ date(date3) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} +{{ date(date4) == date('2010-10-04 13:45') ? 'OK' : 'KO' }} +{{ date(date5) == date('1964-01-02 03:04') ? 'OK' : 'KO' }} +{{ date() > date('-1day') ? 'OK' : 'KO' }} +--DATA-- +date_default_timezone_set('UTC'); +return array( + 'date1' => mktime(13, 45, 0, 10, 4, 2010), + 'date2' => new DateTime('2010-10-04 13:45'), + 'date3' => '2010-10-04 13:45', + 'date4' => 1286199900, // DateTime::createFromFormat('Y-m-d H:i', '2010-10-04 13:45', new DateTimeZone('UTC'))->getTimestamp() -- A unixtimestamp is always GMT + 'date5' => -189291360, // DateTime::createFromFormat('Y-m-d H:i', '1964-01-02 03:04', new DateTimeZone('UTC'))->getTimestamp(), +) +--EXPECT-- +OK +OK +OK +OK +OK +OK +OK diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/date_namedargs.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/date_namedargs.test new file mode 100644 index 0000000..b9dd9e3 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/date_namedargs.test @@ -0,0 +1,11 @@ +--TEST-- +"date" function +--TEMPLATE-- +{{ date(date, "America/New_York")|date('d/m/Y H:i:s P', false) }} +{{ date(timezone="America/New_York", date=date)|date('d/m/Y H:i:s P', false) }} +--DATA-- +date_default_timezone_set('UTC'); +return array('date' => mktime(13, 45, 0, 10, 4, 2010)) +--EXPECT-- +04/10/2010 09:45:00 -04:00 +04/10/2010 09:45:00 -04:00 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dump.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dump.test new file mode 100644 index 0000000..f407237 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dump.test @@ -0,0 +1,16 @@ +--TEST-- +"dump" function +--CONDITION-- +!extension_loaded('xdebug') +--TEMPLATE-- +{{ dump('foo') }} +{{ dump('foo', 'bar') }} +--DATA-- +return array('foo' => 'foo', 'bar' => 'bar') +--CONFIG-- +return array('debug' => true, 'autoescape' => false); +--EXPECT-- +string(3) "foo" + +string(3) "foo" +string(3) "bar" diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dump_array.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dump_array.test new file mode 100644 index 0000000..889b7a9 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dump_array.test @@ -0,0 +1,19 @@ +--TEST-- +"dump" function, xdebug is not loaded or xdebug <2.2-dev is loaded +--CONDITION-- +!extension_loaded('xdebug') || (($r = new ReflectionExtension('xdebug')) && version_compare($r->getVersion(), '2.2-dev', '<')) +--TEMPLATE-- +{{ dump() }} +--DATA-- +return array('foo' => 'foo', 'bar' => 'bar') +--CONFIG-- +return array('debug' => true, 'autoescape' => false); +--EXPECT-- +array(3) { + ["foo"]=> + string(3) "foo" + ["bar"]=> + string(3) "bar" + ["global"]=> + string(6) "global" +} diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dynamic_function.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dynamic_function.test new file mode 100644 index 0000000..913fbc9 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/dynamic_function.test @@ -0,0 +1,10 @@ +--TEST-- +dynamic function +--TEMPLATE-- +{{ foo_path('bar') }} +{{ a_foo_b_bar('bar') }} +--DATA-- +return array() +--EXPECT-- +foo/bar +a/b/bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/assignment.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/assignment.test new file mode 100644 index 0000000..b7653b4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/assignment.test @@ -0,0 +1,13 @@ +--TEST-- +"include" function +--TEMPLATE-- +{% set tmp = include("foo.twig") %} + +FOO{{ tmp }}BAR +--TEMPLATE(foo.twig)-- +FOOBAR +--DATA-- +return array() +--EXPECT-- +FOO +FOOBARBAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/autoescaping.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/autoescaping.test new file mode 100644 index 0000000..56f8f3b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/autoescaping.test @@ -0,0 +1,10 @@ +--TEST-- +"include" function is safe for auto-escaping +--TEMPLATE-- +{{ include("foo.twig") }} +--TEMPLATE(foo.twig)-- +

    Test

    +--DATA-- +return array() +--EXPECT-- +

    Test

    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/basic.test new file mode 100644 index 0000000..a434182 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/basic.test @@ -0,0 +1,17 @@ +--TEST-- +"include" function +--TEMPLATE-- +FOO +{{ include("foo.twig") }} + +BAR +--TEMPLATE(foo.twig)-- +FOOBAR +--DATA-- +return array() +--EXPECT-- +FOO + +FOOBAR + +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/expression.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/expression.test new file mode 100644 index 0000000..aba30ce --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/expression.test @@ -0,0 +1,17 @@ +--TEST-- +"include" function allows expressions for the template to include +--TEMPLATE-- +FOO +{{ include(foo) }} + +BAR +--TEMPLATE(foo.twig)-- +FOOBAR +--DATA-- +return array('foo' => 'foo.twig') +--EXPECT-- +FOO + +FOOBAR + +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/ignore_missing.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/ignore_missing.test new file mode 100644 index 0000000..43a2ccc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/ignore_missing.test @@ -0,0 +1,10 @@ +--TEST-- +"include" function +--TEMPLATE-- +{{ include(["foo.twig", "bar.twig"], ignore_missing = true) }} +{{ include("foo.twig", ignore_missing = true) }} +{{ include("foo.twig", ignore_missing = true, variables = {}) }} +{{ include("foo.twig", ignore_missing = true, variables = {}, with_context = true) }} +--DATA-- +return array() +--EXPECT-- diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/missing.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/missing.test new file mode 100644 index 0000000..4d2f6cf --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/missing.test @@ -0,0 +1,8 @@ +--TEST-- +"include" function +--TEMPLATE-- +{{ include("foo.twig") }} +--DATA-- +return array(); +--EXCEPTION-- +Twig_Error_Loader: Template "foo.twig" is not defined in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/missing_nested.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/missing_nested.test new file mode 100644 index 0000000..78fddc7 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/missing_nested.test @@ -0,0 +1,16 @@ +--TEST-- +"include" function +--TEMPLATE-- +{% extends "base.twig" %} + +{% block content %} + {{ parent() }} +{% endblock %} +--TEMPLATE(base.twig)-- +{% block content %} + {{ include("foo.twig") }} +{% endblock %} +--DATA-- +return array(); +--EXCEPTION-- +Twig_Error_Loader: Template "foo.twig" is not defined in "base.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox.test new file mode 100644 index 0000000..7b9ccac --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox.test @@ -0,0 +1,13 @@ +--TEST-- +"include" tag sandboxed +--TEMPLATE-- +{{ include("foo.twig", sandboxed = true) }} +--TEMPLATE(foo.twig)-- + + +{{ foo|e }} +{{ foo|e }} +--DATA-- +return array() +--EXCEPTION-- +Twig_Sandbox_SecurityNotAllowedFilterError: Filter "e" is not allowed in "foo.twig" at line 4. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling.test new file mode 100644 index 0000000..8ffc492 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling.test @@ -0,0 +1,16 @@ +--TEST-- +"include" tag sandboxed +--TEMPLATE-- +{{ include("foo.twig", sandboxed = true) }} +{{ include("bar.twig") }} +--TEMPLATE(foo.twig)-- +foo +--TEMPLATE(bar.twig)-- +{{ foo|e }} +--DATA-- +return array('foo' => 'bar
    ') +--EXPECT-- +foo + + +bar<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling_ignore_missing.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling_ignore_missing.test new file mode 100644 index 0000000..8bf6e10 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling_ignore_missing.test @@ -0,0 +1,13 @@ +--TEST-- +"include" tag sandboxed +--TEMPLATE-- +{{ include("unknown.twig", sandboxed = true, ignore_missing = true) }} +{{ include("bar.twig") }} +--TEMPLATE(bar.twig)-- +{{ foo|e }} +--DATA-- +return array('foo' => 'bar
    ') +--EXPECT-- + + +bar<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/template_instance.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/template_instance.test new file mode 100644 index 0000000..18d405a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/template_instance.test @@ -0,0 +1,10 @@ +--TEST-- +"include" function accepts Twig_Template instance +--TEMPLATE-- +{{ include(foo) }} FOO +--TEMPLATE(foo.twig)-- +BAR +--DATA-- +return array('foo' => $twig->loadTemplate('foo.twig')) +--EXPECT-- +BAR FOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/templates_as_array.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/templates_as_array.test new file mode 100644 index 0000000..1a81006 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/templates_as_array.test @@ -0,0 +1,12 @@ +--TEST-- +"include" function +--TEMPLATE-- +{{ include(["foo.twig", "bar.twig"]) }} +{{- include(["bar.twig", "foo.twig"]) }} +--TEMPLATE(foo.twig)-- +foo +--DATA-- +return array() +--EXPECT-- +foo +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/with_context.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/with_context.test new file mode 100644 index 0000000..35611fb --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/with_context.test @@ -0,0 +1,16 @@ +--TEST-- +"include" function accept variables and with_context +--TEMPLATE-- +{{ include("foo.twig") }} +{{- include("foo.twig", with_context = false) }} +{{- include("foo.twig", {'foo1': 'bar'}) }} +{{- include("foo.twig", {'foo1': 'bar'}, with_context = false) }} +--TEMPLATE(foo.twig)-- +{% for k, v in _context %}{{ k }},{% endfor %} +--DATA-- +return array('foo' => 'bar') +--EXPECT-- +foo,global,_parent, +global,_parent, +foo,global,foo1,_parent, +foo1,global,_parent, diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/with_variables.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/with_variables.test new file mode 100644 index 0000000..b2ace94 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/include/with_variables.test @@ -0,0 +1,12 @@ +--TEST-- +"include" function accept variables +--TEMPLATE-- +{{ include("foo.twig", {'foo': 'bar'}) }} +{{- include("foo.twig", vars) }} +--TEMPLATE(foo.twig)-- +{{ foo }} +--DATA-- +return array('vars' => array('foo' => 'bar')) +--EXPECT-- +bar +bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/magic_call.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/magic_call.test new file mode 100644 index 0000000..9335443 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/magic_call.test @@ -0,0 +1,8 @@ +--TEST-- +__call calls +--TEMPLATE-- +{{ 'foo'|magic_call }} +--DATA-- +return array() +--EXPECT-- +magic_foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/magic_call53.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/magic_call53.test new file mode 100644 index 0000000..a0f55e1 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/magic_call53.test @@ -0,0 +1,12 @@ +--TEST-- +__staticCall calls +--CONDITION-- +version_compare(phpversion(), '5.3.0', '>=') +--TEMPLATE-- +{{ 'foo'|magic_call_string }} +{{ 'foo'|magic_call_array }} +--DATA-- +return array() +--EXPECT-- +static_magic_foo +static_magic_foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/max.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/max.test new file mode 100644 index 0000000..e6c94af --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/max.test @@ -0,0 +1,12 @@ +--TEST-- +"max" function +--TEMPLATE-- +{{ max([2, 1, 3, 5, 4]) }} +{{ max(2, 1, 3, 5, 4) }} +{{ max({2:"two", 1:"one", 3:"three", 5:"five", 4:"for"}) }} +--DATA-- +return array() +--EXPECT-- +5 +5 +two diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/min.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/min.test new file mode 100644 index 0000000..660471c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/min.test @@ -0,0 +1,12 @@ +--TEST-- +"min" function +--TEMPLATE-- +{{ min(2, 1, 3, 5, 4) }} +{{ min([2, 1, 3, 5, 4]) }} +{{ min({2:"two", 1:"one", 3:"three", 5:"five", 4:"for"}) }} +--DATA-- +return array() +--EXPECT-- +1 +1 +five diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/range.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/range.test new file mode 100644 index 0000000..e0377c8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/range.test @@ -0,0 +1,8 @@ +--TEST-- +"range" function +--TEMPLATE-- +{{ range(low=0+1, high=10+0, step=2)|join(',') }} +--DATA-- +return array() +--EXPECT-- +1,3,5,7,9 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/recursive_block_with_inheritance.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/recursive_block_with_inheritance.test new file mode 100644 index 0000000..bf0556d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/recursive_block_with_inheritance.test @@ -0,0 +1,21 @@ +--TEST-- +"block" function recursively called in a parent template +--TEMPLATE-- +{% extends "ordered_menu.twig" %} +{% block label %}"{{ parent() }}"{% endblock %} +{% block list %}{% set class = 'b' %}{{ parent() }}{% endblock %} +--TEMPLATE(ordered_menu.twig)-- +{% extends "menu.twig" %} +{% block list %}{% set class = class|default('a') %}
      {{ block('children') }}
    {% endblock %} +--TEMPLATE(menu.twig)-- +{% extends "base.twig" %} +{% block list %}
      {{ block('children') }}
    {% endblock %} +{% block children %}{% set currentItem = item %}{% for item in currentItem %}{{ block('item') }}{% endfor %}{% set item = currentItem %}{% endblock %} +{% block item %}
  • {% if item is not iterable %}{{ block('label') }}{% else %}{{ block('list') }}{% endif %}
  • {% endblock %} +{% block label %}{{ item }}{% endblock %} +--TEMPLATE(base.twig)-- +{{ block('list') }} +--DATA-- +return array('item' => array('1', '2', array('3.1', array('3.2.1', '3.2.2'), '3.4'))) +--EXPECT-- +
    1. "1"
    2. "2"
      1. "3.1"
        1. "3.2.1"
        2. "3.2.2"
      2. "3.4"
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/source.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/source.test new file mode 100644 index 0000000..0e094c3 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/source.test @@ -0,0 +1,17 @@ +--TEST-- +"source" function +--TEMPLATE-- +FOO +{{ source("foo.twig") }} + +BAR +--TEMPLATE(foo.twig)-- +{{ foo }}
    +--DATA-- +return array() +--EXPECT-- +FOO + +{{ foo }}
    + +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/special_chars.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/special_chars.test new file mode 100644 index 0000000..30c3df5 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/special_chars.test @@ -0,0 +1,8 @@ +--TEST-- +"§" custom function +--TEMPLATE-- +{{ §('foo') }} +--DATA-- +return array() +--EXPECT-- +§foo§ diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/static_calls.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/static_calls.test new file mode 100644 index 0000000..57e5be3 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/static_calls.test @@ -0,0 +1,10 @@ +--TEST-- +Functions as static method calls +--TEMPLATE-- +{{ static_call_string('foo') }} +{{ static_call_array('foo') }} +--DATA-- +return array('foo' => 'foo') +--EXPECT-- +*foo* +*foo* diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/template_from_string.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/template_from_string.test new file mode 100644 index 0000000..3d3b958 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/functions/template_from_string.test @@ -0,0 +1,15 @@ +--TEST-- +"template_from_string" function +--TEMPLATE-- +{% include template_from_string(template) %} + +{% include template_from_string("Hello {{ name }}") %} +{% include template_from_string('{% extends "parent.twig" %}{% block content %}Hello {{ name }}{% endblock %}') %} +--TEMPLATE(parent.twig)-- +{% block content %}{% endblock %} +--DATA-- +return array('name' => 'Fabien', 'template' => "Hello {{ name }}") +--EXPECT-- +Hello Fabien +Hello Fabien +Hello Fabien diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/default_values.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/default_values.test new file mode 100644 index 0000000..4ccff7b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/default_values.test @@ -0,0 +1,16 @@ +--TEST-- +macro +--TEMPLATE-- +{% from _self import test %} + +{% macro test(a, b = 'bar') -%} +{{ a }}{{ b }} +{%- endmacro %} + +{{ test('foo') }} +{{ test('bar', 'foo') }} +--DATA-- +return array(); +--EXPECT-- +foobar +barfoo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/nested_calls.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/nested_calls.test new file mode 100644 index 0000000..cd25428 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/nested_calls.test @@ -0,0 +1,18 @@ +--TEST-- +macro +--TEMPLATE-- +{% import _self as macros %} + +{% macro foo(data) %} + {{ data }} +{% endmacro %} + +{% macro bar() %} +
    +{% endmacro %} + +{{ macros.foo(macros.bar()) }} +--DATA-- +return array(); +--EXPECT-- +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/reserved_variables.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/reserved_variables.test new file mode 100644 index 0000000..cbfb921 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/reserved_variables.test @@ -0,0 +1,14 @@ +--TEST-- +macro +--TEMPLATE-- +{% from _self import test %} + +{% macro test(this) -%} + {{ this }} +{%- endmacro %} + +{{ test(this) }} +--DATA-- +return array('this' => 'foo'); +--EXPECT-- +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/simple.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/simple.test new file mode 100644 index 0000000..6a366cd --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/simple.test @@ -0,0 +1,22 @@ +--TEST-- +macro +--TEMPLATE-- +{% import _self as test %} +{% from _self import test %} + +{% macro test(a, b) -%} + {{ a|default('a') }}
    + {{- b|default('b') }}
    +{%- endmacro %} + +{{ test.test() }} +{{ test() }} +{{ test.test(1, "c") }} +{{ test(1, "c") }} +--DATA-- +return array(); +--EXPECT-- +a
    b
    +a
    b
    +1
    c
    +1
    c
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/varargs.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/varargs.test new file mode 100644 index 0000000..412c90f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/varargs.test @@ -0,0 +1,21 @@ +--TEST-- +macro with arbitrary arguments +--TEMPLATE-- +{% from _self import test1, test2 %} + +{% macro test1(var) %} + {{- var }}: {{ varargs|join(", ") }} +{% endmacro %} + +{% macro test2() %} + {{- varargs|join(", ") }} +{% endmacro %} + +{{ test1("foo", "bar", "foobar") }} +{{ test2("foo", "bar", "foobar") }} +--DATA-- +return array(); +--EXPECT-- +foo: bar, foobar + +foo, bar, foobar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/varargs_argument.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/varargs_argument.test new file mode 100644 index 0000000..800c262 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/varargs_argument.test @@ -0,0 +1,7 @@ +--TEST-- +macro with varargs argument +--TEMPLATE-- +{% macro test(varargs) %} +{% endmacro %} +--EXCEPTION-- +Twig_Error_Syntax: The argument "varargs" in macro "test" cannot be defined because the variable "varargs" is reserved for arbitrary arguments in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/with_filters.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/with_filters.test new file mode 100644 index 0000000..685626f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/macros/with_filters.test @@ -0,0 +1,14 @@ +--TEST-- +macro with a filter +--TEMPLATE-- +{% import _self as test %} + +{% macro test() %} + {% filter escape %}foo
    {% endfilter %} +{% endmacro %} + +{{ test.test() }} +--DATA-- +return array(); +--EXPECT-- +foo<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/block_names_unicity.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/block_names_unicity.test new file mode 100644 index 0000000..40c0673 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/block_names_unicity.test @@ -0,0 +1,19 @@ +--TEST-- +Block names are unique per template +--TEMPLATE-- +{% extends 'layout' %} +{% block content -%} + {% filter title -%} + second + {% endfilter %} +{% endblock %} +--TEMPLATE(layout)-- +{% filter title -%} + first +{% endfilter %} +{% block content %}{% endblock %} +--DATA-- +return array(); +--EXPECT-- +First +Second diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/combined_debug_info.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/combined_debug_info.test new file mode 100644 index 0000000..ff977ad --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/combined_debug_info.test @@ -0,0 +1,15 @@ +--TEST-- +Exception with bad line number +--TEMPLATE-- +{% block content %} + {{ foo }} + {{ include("foo") }} +{% endblock %} +index +--TEMPLATE(foo)-- +foo +{{ foo.bar }} +--DATA-- +return array('foo' => 'foo'); +--EXCEPTION-- +Twig_Error_Runtime: Impossible to access an attribute ("bar") on a string variable ("foo") in "foo" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/empty_token.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/empty_token.test new file mode 100644 index 0000000..65f6cd2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/empty_token.test @@ -0,0 +1,8 @@ +--TEST-- +Twig outputs 0 nodes correctly +--TEMPLATE-- +{{ foo }}0{{ foo }} +--DATA-- +return array('foo' => 'foo') +--EXPECT-- +foo0foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/issue_1143.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/issue_1143.test new file mode 100644 index 0000000..ff7c8bb --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/issue_1143.test @@ -0,0 +1,23 @@ +--TEST-- +error in twig extension +--TEMPLATE-- +{{ object.region is not null ? object.regionChoices[object.region] }} +--DATA-- +class House +{ + const REGION_S = 1; + const REGION_P = 2; + + public static $regionChoices = array(self::REGION_S => 'house.region.s', self::REGION_P => 'house.region.p'); + + public function getRegionChoices() + { + return self::$regionChoices; + } +} + +$object = new House(); +$object->region = 1; +return array('object' => $object) +--EXPECT-- +house.region.s diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/multi_word_tests.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/multi_word_tests.test new file mode 100644 index 0000000..269a305 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/multi_word_tests.test @@ -0,0 +1,10 @@ +--TEST-- +Twig allows multi-word tests without a custom node class +--TEMPLATE-- +{{ 'foo' is multi word ? 'yes' : 'no' }} +{{ 'foo bar' is multi word ? 'yes' : 'no' }} +--DATA-- +return array() +--EXPECT-- +no +yes diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/simple_xml_element.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/simple_xml_element.test new file mode 100644 index 0000000..60c3c51 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/simple_xml_element.test @@ -0,0 +1,19 @@ +--TEST-- +Twig is able to deal with SimpleXMLElement instances as variables +--CONDITION-- +version_compare(phpversion(), '5.3.0', '>=') +--TEMPLATE-- +Hello '{{ images.image.0.group }}'! +{{ images.image.0.group.attributes.myattr }} +{{ images.children().image.count() }} +{% for image in images %} + - {{ image.group }} +{% endfor %} +--DATA-- +return array('images' => new SimpleXMLElement('foobar')) +--EXPECT-- +Hello 'foo'! +example +2 + - foo + - bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/strings_like_numbers.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/strings_like_numbers.test new file mode 100644 index 0000000..e18e110 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/regression/strings_like_numbers.test @@ -0,0 +1,8 @@ +--TEST-- +Twig does not confuse strings with integers in getAttribute() +--TEMPLATE-- +{{ hash['2e2'] }} +--DATA-- +return array('hash' => array('2e2' => 'works')) +--EXPECT-- +works diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/basic.test new file mode 100644 index 0000000..2f6a3e1 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/basic.test @@ -0,0 +1,26 @@ +--TEST-- +"autoescape" tag applies escaping on its children +--TEMPLATE-- +{% autoescape %} +{{ var }}
    +{% endautoescape %} +{% autoescape 'html' %} +{{ var }}
    +{% endautoescape %} +{% autoescape false %} +{{ var }}
    +{% endautoescape %} +{% autoescape true %} +{{ var }}
    +{% endautoescape %} +{% autoescape false %} +{{ var }}
    +{% endautoescape %} +--DATA-- +return array('var' => '
    ') +--EXPECT-- +<br />
    +<br />
    +

    +<br />
    +

    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/blocks.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/blocks.test new file mode 100644 index 0000000..05ab83c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/blocks.test @@ -0,0 +1,12 @@ +--TEST-- +"autoescape" tag applies escaping on embedded blocks +--TEMPLATE-- +{% autoescape 'html' %} + {% block foo %} + {{ var }} + {% endblock %} +{% endautoescape %} +--DATA-- +return array('var' => '
    ') +--EXPECT-- +<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/double_escaping.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/double_escaping.test new file mode 100644 index 0000000..9c09724 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/double_escaping.test @@ -0,0 +1,10 @@ +--TEST-- +"autoescape" tag does not double-escape +--TEMPLATE-- +{% autoescape 'html' %} +{{ var|escape }} +{% endautoescape %} +--DATA-- +return array('var' => '
    ') +--EXPECT-- +<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/functions.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/functions.test new file mode 100644 index 0000000..653c41b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/functions.test @@ -0,0 +1,83 @@ +--TEST-- +"autoescape" tag applies escaping after calling functions +--TEMPLATE-- + +autoescape false +{% autoescape false %} + +safe_br +{{ safe_br() }} + +unsafe_br +{{ unsafe_br() }} + +{% endautoescape %} + +autoescape 'html' +{% autoescape 'html' %} + +safe_br +{{ safe_br() }} + +unsafe_br +{{ unsafe_br() }} + +unsafe_br()|raw +{{ (unsafe_br())|raw }} + +safe_br()|escape +{{ (safe_br())|escape }} + +safe_br()|raw +{{ (safe_br())|raw }} + +unsafe_br()|escape +{{ (unsafe_br())|escape }} + +{% endautoescape %} + +autoescape js +{% autoescape 'js' %} + +safe_br +{{ safe_br() }} + +{% endautoescape %} +--DATA-- +return array() +--EXPECT-- + +autoescape false + +safe_br +
    + +unsafe_br +
    + + +autoescape 'html' + +safe_br +
    + +unsafe_br +<br /> + +unsafe_br()|raw +
    + +safe_br()|escape +<br /> + +safe_br()|raw +
    + +unsafe_br()|escape +<br /> + + +autoescape js + +safe_br +\u003Cbr\u0020\/\u003E diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/literal.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/literal.test new file mode 100644 index 0000000..e389d4d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/literal.test @@ -0,0 +1,45 @@ +--TEST-- +"autoescape" tag does not apply escaping on literals +--TEMPLATE-- +{% autoescape 'html' %} + +1. Simple literal +{{ "
    " }} + +2. Conditional expression with only literals +{{ true ? "
    " : "
    " }} + +3. Conditional expression with a variable +{{ true ? "
    " : someVar }} + +4. Nested conditionals with only literals +{{ true ? (true ? "
    " : "
    ") : "\n" }} + +5. Nested conditionals with a variable +{{ true ? (true ? "
    " : someVar) : "\n" }} + +6. Nested conditionals with a variable marked safe +{{ true ? (true ? "
    " : someVar|raw) : "\n" }} + +{% endautoescape %} +--DATA-- +return array() +--EXPECT-- + +1. Simple literal +
    + +2. Conditional expression with only literals +
    + +3. Conditional expression with a variable +<br /> + +4. Nested conditionals with only literals +
    + +5. Nested conditionals with a variable +<br /> + +6. Nested conditionals with a variable marked safe +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/nested.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/nested.test new file mode 100644 index 0000000..798e6fe --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/nested.test @@ -0,0 +1,26 @@ +--TEST-- +"autoescape" tags can be nested at will +--TEMPLATE-- +{{ var }} +{% autoescape 'html' %} + {{ var }} + {% autoescape false %} + {{ var }} + {% autoescape 'html' %} + {{ var }} + {% endautoescape %} + {{ var }} + {% endautoescape %} + {{ var }} +{% endautoescape %} +{{ var }} +--DATA-- +return array('var' => '
    ') +--EXPECT-- +<br /> + <br /> +
    + <br /> +
    + <br /> +<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/objects.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/objects.test new file mode 100644 index 0000000..e896aa4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/objects.test @@ -0,0 +1,26 @@ +--TEST-- +"autoescape" tag applies escaping to object method calls +--TEMPLATE-- +{% autoescape 'html' %} +{{ user.name }} +{{ user.name|lower }} +{{ user }} +{% endautoescape %} +--DATA-- +class UserForAutoEscapeTest +{ + public function getName() + { + return 'Fabien
    '; + } + + public function __toString() + { + return 'Fabien
    '; + } +} +return array('user' => new UserForAutoEscapeTest()) +--EXPECT-- +Fabien<br /> +fabien<br /> +Fabien<br /> diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/raw.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/raw.test new file mode 100644 index 0000000..9f1cedd --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/raw.test @@ -0,0 +1,10 @@ +--TEST-- +"autoescape" tag does not escape when raw is used as a filter +--TEMPLATE-- +{% autoescape 'html' %} +{{ var|raw }} +{% endautoescape %} +--DATA-- +return array('var' => '
    ') +--EXPECT-- +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/strategy.legacy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/strategy.legacy.test new file mode 100644 index 0000000..c3f8edd --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/strategy.legacy.test @@ -0,0 +1,11 @@ +--TEST-- +"autoescape" tag accepts an escaping strategy +--TEMPLATE-- +{% autoescape true js %}{{ var }}{% endautoescape %} + +{% autoescape true html %}{{ var }}{% endautoescape %} +--DATA-- +return array('var' => '
    "') +--EXPECT-- +\u003Cbr\u0020\/\u003E\u0022 +<br />" diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/strategy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/strategy.test new file mode 100644 index 0000000..5b69449 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/strategy.test @@ -0,0 +1,11 @@ +--TEST-- +"autoescape" tag accepts an escaping strategy +--TEMPLATE-- +{% autoescape 'js' %}{{ var }}{% endautoescape %} + +{% autoescape 'html' %}{{ var }}{% endautoescape %} +--DATA-- +return array('var' => '
    "') +--EXPECT-- +\u003Cbr\u0020\/\u003E\u0022 +<br />" diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/type.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/type.test new file mode 100644 index 0000000..1250f0d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/type.test @@ -0,0 +1,69 @@ +--TEST-- +escape types +--TEMPLATE-- + +1. autoescape 'html' |escape('js') + +{% autoescape 'html' %} + +{% endautoescape %} + +2. autoescape 'html' |escape('js') + +{% autoescape 'html' %} + +{% endautoescape %} + +3. autoescape 'js' |escape('js') + +{% autoescape 'js' %} + +{% endautoescape %} + +4. no escape + +{% autoescape false %} + +{% endautoescape %} + +5. |escape('js')|escape('html') + +{% autoescape false %} + +{% endautoescape %} + +6. autoescape 'html' |escape('js')|escape('html') + +{% autoescape 'html' %} + +{% endautoescape %} + +--DATA-- +return array('msg' => "<>\n'\"") +--EXPECT-- + +1. autoescape 'html' |escape('js') + + + +2. autoescape 'html' |escape('js') + + + +3. autoescape 'js' |escape('js') + + + +4. no escape + + + +5. |escape('js')|escape('html') + + + +6. autoescape 'html' |escape('js')|escape('html') + + + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_filters.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_filters.test new file mode 100644 index 0000000..7821a9a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_filters.test @@ -0,0 +1,131 @@ +--TEST-- +"autoescape" tag applies escaping after calling filters +--TEMPLATE-- +{% autoescape 'html' %} + +(escape_and_nl2br is an escaper filter) + +1. Don't escape escaper filter output +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is not escaped ) +{{ var|escape_and_nl2br }} + +2. Don't escape escaper filter output +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is not escaped, |raw is redundant ) +{{ var|escape_and_nl2br|raw }} + +3. Explicit escape +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is explicitly escaped by |escape ) +{{ var|escape_and_nl2br|escape }} + +4. Escape non-escaper filter output +( var is upper-cased by |upper, + the output is auto-escaped ) +{{ var|upper }} + +5. Escape if last filter is not an escaper +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is upper-cased by |upper, + the output is auto-escaped as |upper is not an escaper ) +{{ var|escape_and_nl2br|upper }} + +6. Don't escape escaper filter output +( var is upper cased by upper, + the output is escaped by |escape_and_nl2br, line-breaks are added, + the output is not escaped as |escape_and_nl2br is an escaper ) +{{ var|upper|escape_and_nl2br }} + +7. Escape if last filter is not an escaper +( the output of |format is "" ~ var ~ "", + the output is auto-escaped ) +{{ "%s"|format(var) }} + +8. Escape if last filter is not an escaper +( the output of |format is "" ~ var ~ "", + |raw is redundant, + the output is auto-escaped ) +{{ "%s"|raw|format(var) }} + +9. Don't escape escaper filter output +( the output of |format is "" ~ var ~ "", + the output is not escaped due to |raw filter at the end ) +{{ "%s"|format(var)|raw }} + +10. Don't escape escaper filter output +( the output of |format is "" ~ var ~ "", + the output is not escaped due to |raw filter at the end, + the |raw filter on var is redundant ) +{{ "%s"|format(var|raw)|raw }} + +{% endautoescape %} +--DATA-- +return array('var' => "\nTwig") +--EXPECT-- + +(escape_and_nl2br is an escaper filter) + +1. Don't escape escaper filter output +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is not escaped ) +<Fabien>
    +Twig + +2. Don't escape escaper filter output +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is not escaped, |raw is redundant ) +<Fabien>
    +Twig + +3. Explicit escape +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is explicitly escaped by |escape ) +&lt;Fabien&gt;<br /> +Twig + +4. Escape non-escaper filter output +( var is upper-cased by |upper, + the output is auto-escaped ) +<FABIEN> +TWIG + +5. Escape if last filter is not an escaper +( var is escaped by |escape_and_nl2br, line-breaks are added, + the output is upper-cased by |upper, + the output is auto-escaped as |upper is not an escaper ) +&LT;FABIEN&GT;<BR /> +TWIG + +6. Don't escape escaper filter output +( var is upper cased by upper, + the output is escaped by |escape_and_nl2br, line-breaks are added, + the output is not escaped as |escape_and_nl2br is an escaper ) +<FABIEN>
    +TWIG + +7. Escape if last filter is not an escaper +( the output of |format is "" ~ var ~ "", + the output is auto-escaped ) +<b><Fabien> +Twig</b> + +8. Escape if last filter is not an escaper +( the output of |format is "" ~ var ~ "", + |raw is redundant, + the output is auto-escaped ) +<b><Fabien> +Twig</b> + +9. Don't escape escaper filter output +( the output of |format is "" ~ var ~ "", + the output is not escaped due to |raw filter at the end ) + +Twig + +10. Don't escape escaper filter output +( the output of |format is "" ~ var ~ "", + the output is not escaped due to |raw filter at the end, + the |raw filter on var is redundant ) + +Twig diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_filters_arguments.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_filters_arguments.test new file mode 100644 index 0000000..f58a1e0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_filters_arguments.test @@ -0,0 +1,23 @@ +--TEST-- +"autoescape" tag do not applies escaping on filter arguments +--TEMPLATE-- +{% autoescape 'html' %} +{{ var|nl2br("
    ") }} +{{ var|nl2br("
    "|escape) }} +{{ var|nl2br(sep) }} +{{ var|nl2br(sep|raw) }} +{{ var|nl2br(sep|escape) }} +{% endautoescape %} +--DATA-- +return array('var' => "\nTwig", 'sep' => '
    ') +--EXPECT-- +<Fabien>
    +Twig +<Fabien><br /> +Twig +<Fabien>
    +Twig +<Fabien>
    +Twig +<Fabien><br /> +Twig diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_pre_escape_filters.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_pre_escape_filters.test new file mode 100644 index 0000000..134c77e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_pre_escape_filters.test @@ -0,0 +1,68 @@ +--TEST-- +"autoescape" tag applies escaping after calling filters, and before calling pre_escape filters +--TEMPLATE-- +{% autoescape 'html' %} + +(nl2br is pre_escaped for "html" and declared safe for "html") + +1. Pre-escape and don't post-escape +( var|escape|nl2br ) +{{ var|nl2br }} + +2. Don't double-pre-escape +( var|escape|nl2br ) +{{ var|escape|nl2br }} + +3. Don't escape safe values +( var|raw|nl2br ) +{{ var|raw|nl2br }} + +4. Don't escape safe values +( var|escape|nl2br|nl2br ) +{{ var|nl2br|nl2br }} + +5. Re-escape values that are escaped for an other contexts +( var|escape_something|escape|nl2br ) +{{ var|escape_something|nl2br }} + +6. Still escape when using filters not declared safe +( var|escape|nl2br|upper|escape ) +{{ var|nl2br|upper }} + +{% endautoescape %} +--DATA-- +return array('var' => "\nTwig") +--EXPECT-- + +(nl2br is pre_escaped for "html" and declared safe for "html") + +1. Pre-escape and don't post-escape +( var|escape|nl2br ) +<Fabien>
    +Twig + +2. Don't double-pre-escape +( var|escape|nl2br ) +<Fabien>
    +Twig + +3. Don't escape safe values +( var|raw|nl2br ) +
    +Twig + +4. Don't escape safe values +( var|escape|nl2br|nl2br ) +<Fabien>

    +Twig + +5. Re-escape values that are escaped for an other contexts +( var|escape_something|escape|nl2br ) +<FABIEN>
    +TWIG + +6. Still escape when using filters not declared safe +( var|escape|nl2br|upper|escape ) +&LT;FABIEN&GT;<BR /> +TWIG + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_preserves_safety_filters.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_preserves_safety_filters.test new file mode 100644 index 0000000..32d3943 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/autoescape/with_preserves_safety_filters.test @@ -0,0 +1,50 @@ +--TEST-- +"autoescape" tag handles filters preserving the safety +--TEMPLATE-- +{% autoescape 'html' %} + +(preserves_safety is preserving safety for "html") + +1. Unsafe values are still unsafe +( var|preserves_safety|escape ) +{{ var|preserves_safety }} + +2. Safe values are still safe +( var|escape|preserves_safety ) +{{ var|escape|preserves_safety }} + +3. Re-escape values that are escaped for an other contexts +( var|escape_something|preserves_safety|escape ) +{{ var|escape_something|preserves_safety }} + +4. Still escape when using filters not declared safe +( var|escape|preserves_safety|replace({'FABIEN': 'FABPOT'})|escape ) +{{ var|escape|preserves_safety|replace({'FABIEN': 'FABPOT'}) }} + +{% endautoescape %} +--DATA-- +return array('var' => "\nTwig") +--EXPECT-- + +(preserves_safety is preserving safety for "html") + +1. Unsafe values are still unsafe +( var|preserves_safety|escape ) +<FABIEN> +TWIG + +2. Safe values are still safe +( var|escape|preserves_safety ) +<FABIEN> +TWIG + +3. Re-escape values that are escaped for an other contexts +( var|escape_something|preserves_safety|escape ) +<FABIEN> +TWIG + +4. Still escape when using filters not declared safe +( var|escape|preserves_safety|replace({'FABIEN': 'FABPOT'})|escape ) +&LT;FABPOT&GT; +TWIG + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/basic.test new file mode 100644 index 0000000..360dcf0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/basic.test @@ -0,0 +1,11 @@ +--TEST-- +"block" tag +--TEMPLATE-- +{% block title1 %}FOO{% endblock %} +{% block title2 foo|lower %} +--TEMPLATE(foo.twig)-- +{% block content %}{% endblock %} +--DATA-- +return array('foo' => 'bar') +--EXPECT-- +FOObar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/block_unique_name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/block_unique_name.test new file mode 100644 index 0000000..bc89ec8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/block_unique_name.test @@ -0,0 +1,11 @@ +--TEST-- +"block" tag +--TEMPLATE-- +{% block content %} + {% block content %} + {% endblock %} +{% endblock %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: The block 'content' has already been defined line 2 in "index.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/special_chars.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/special_chars.test new file mode 100644 index 0000000..be17fed --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/block/special_chars.test @@ -0,0 +1,10 @@ +--TEST-- +"§" special chars in a block name +--TEMPLATE-- +{% block § %} +§ +{% endblock § %} +--DATA-- +return array() +--EXPECT-- +§ diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/block.legacy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/block.legacy.test new file mode 100644 index 0000000..10c8f07 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/block.legacy.test @@ -0,0 +1,20 @@ +--TEST-- +Deprecating a block with "deprecated" tag +--TEMPLATE-- +{% use 'greeting.twig' %} + +{{ block('welcome') }} + +--TEMPLATE(greeting.twig)-- +{% block welcome %} + {% deprecated 'The "welcome" block is deprecated, use "hello" instead.' %} + {{ block('hello') }} +{% endblock %} + +{% block hello %} +Hello Fabien +{% endblock %} +--DATA-- +return array() +--EXPECT-- + Hello Fabien diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/macro.legacy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/macro.legacy.test new file mode 100644 index 0000000..c7c7d4e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/macro.legacy.test @@ -0,0 +1,21 @@ +--TEST-- +Deprecating a macro with "deprecated" tag +--TEMPLATE-- +{% import 'greeting.twig' as greeting %} + +{{ greeting.welcome('Fabien') }} + +--TEMPLATE(greeting.twig)-- +{% macro welcome(name) %} + {% deprecated 'The "welcome" macro is deprecated, use "hello" instead.' %} + {% import _self as self %} + {{ self.hello(name) }} +{% endmacro %} + +{% macro hello(name) %} +Hello {{ name }} +{% endmacro %} +--DATA-- +return array() +--EXPECT-- + Hello Fabien diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/template.legacy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/template.legacy.test new file mode 100644 index 0000000..4546d4e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/deprecated/template.legacy.test @@ -0,0 +1,12 @@ +--TEST-- +Deprecating a template with "deprecated" tag +--TEMPLATE-- +{% extends 'greeting.twig' %} + +{% deprecated 'The "index.twig" template is deprecated, use "greeting.twig" instead.' %} +--TEMPLATE(greeting.twig)-- +Hello Fabien +--DATA-- +return array() +--EXPECT-- +Hello Fabien diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/basic.test new file mode 100644 index 0000000..f44296e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/basic.test @@ -0,0 +1,35 @@ +--TEST-- +"embed" tag +--TEMPLATE-- +FOO +{% embed "foo.twig" %} + {% block c1 %} + {{ parent() }} + block1extended + {% endblock %} +{% endembed %} + +BAR +--TEMPLATE(foo.twig)-- +A +{% block c1 %} + block1 +{% endblock %} +B +{% block c2 %} + block2 +{% endblock %} +C +--DATA-- +return array() +--EXPECT-- +FOO + +A + block1 + + block1extended + B + block2 +C +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/complex_dynamic_parent.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/complex_dynamic_parent.test new file mode 100644 index 0000000..de5ea7e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/complex_dynamic_parent.test @@ -0,0 +1,35 @@ +--TEST-- +"embed" tag +--TEMPLATE-- +FOO +{% embed foo ~ ".twig" %} + {% block c1 %} + {{ parent() }} + block1extended + {% endblock %} +{% endembed %} + +BAR +--TEMPLATE(foo.twig)-- +A +{% block c1 %} + block1 +{% endblock %} +B +{% block c2 %} + block2 +{% endblock %} +C +--DATA-- +return array('foo' => 'foo') +--EXPECT-- +FOO + +A + block1 + + block1extended + B + block2 +C +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/dynamic_parent.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/dynamic_parent.test new file mode 100644 index 0000000..2a125e6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/dynamic_parent.test @@ -0,0 +1,35 @@ +--TEST-- +"embed" tag +--TEMPLATE-- +FOO +{% embed foo %} + {% block c1 %} + {{ parent() }} + block1extended + {% endblock %} +{% endembed %} + +BAR +--TEMPLATE(foo.twig)-- +A +{% block c1 %} + block1 +{% endblock %} +B +{% block c2 %} + block2 +{% endblock %} +C +--DATA-- +return array('foo' => 'foo.twig') +--EXPECT-- +FOO + +A + block1 + + block1extended + B + block2 +C +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/error_line.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/error_line.test new file mode 100644 index 0000000..4314737 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/error_line.test @@ -0,0 +1,16 @@ +--TEST-- +"embed" tag +--TEMPLATE(index.twig)-- +FOO +{% embed "foo.twig" %} + {% block c1 %} + {{ nothing }} + {% endblock %} +{% endembed %} +BAR +--TEMPLATE(foo.twig)-- +{% block c1 %}{% endblock %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Runtime: Variable "nothing" does not exist in "index.twig" at line 5. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/multiple.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/multiple.test new file mode 100644 index 0000000..da161e6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/multiple.test @@ -0,0 +1,50 @@ +--TEST-- +"embed" tag +--TEMPLATE-- +FOO +{% embed "foo.twig" %} + {% block c1 %} + {{ parent() }} + block1extended + {% endblock %} +{% endembed %} + +{% embed "foo.twig" %} + {% block c1 %} + {{ parent() }} + block1extended + {% endblock %} +{% endembed %} + +BAR +--TEMPLATE(foo.twig)-- +A +{% block c1 %} + block1 +{% endblock %} +B +{% block c2 %} + block2 +{% endblock %} +C +--DATA-- +return array() +--EXPECT-- +FOO + +A + block1 + + block1extended + B + block2 +C + +A + block1 + + block1extended + B + block2 +C +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/nested.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/nested.test new file mode 100644 index 0000000..81563dc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/nested.test @@ -0,0 +1,42 @@ +--TEST-- +"embed" tag +--TEMPLATE-- +{% embed "foo.twig" %} + {% block c1 %} + {{ parent() }} + {% embed "foo.twig" %} + {% block c1 %} + {{ parent() }} + block1extended + {% endblock %} + {% endembed %} + + {% endblock %} +{% endembed %} +--TEMPLATE(foo.twig)-- +A +{% block c1 %} + block1 +{% endblock %} +B +{% block c2 %} + block2 +{% endblock %} +C +--DATA-- +return array() +--EXPECT-- +A + block1 + + +A + block1 + + block1extended + B + block2 +C + B + block2 +C diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/with_extends.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/with_extends.test new file mode 100644 index 0000000..2c1dd58 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/embed/with_extends.test @@ -0,0 +1,60 @@ +--TEST-- +"embed" tag +--TEMPLATE-- +{% extends "base.twig" %} + +{% block c1 %} + {{ parent() }} + blockc1baseextended +{% endblock %} + +{% block c2 %} + {{ parent() }} + + {% embed "foo.twig" %} + {% block c1 %} + {{ parent() }} + block1extended + {% endblock %} + {% endembed %} + {{ parent() }} +{% endblock %} +--TEMPLATE(base.twig)-- +A +{% block c1 %} + blockc1base +{% endblock %} +{% block c2 %} + blockc2base +{% endblock %} +B +--TEMPLATE(foo.twig)-- +A +{% block c1 %} + block1 +{% endblock %} +B +{% block c2 %} + block2 +{% endblock %} +C +--DATA-- +return array() +--EXPECT-- +A + blockc1base + + blockc1baseextended + blockc2base + + + +A + block1 + + block1extended + B + block2 +C blockc2base + +B \ No newline at end of file diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/basic.test new file mode 100644 index 0000000..82094f2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/basic.test @@ -0,0 +1,10 @@ +--TEST-- +"filter" tag applies a filter on its children +--TEMPLATE-- +{% filter upper %} +Some text with a {{ var }} +{% endfilter %} +--DATA-- +return array('var' => 'var') +--EXPECT-- +SOME TEXT WITH A VAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/json_encode.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/json_encode.test new file mode 100644 index 0000000..3e7148b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/json_encode.test @@ -0,0 +1,8 @@ +--TEST-- +"filter" tag applies a filter on its children +--TEMPLATE-- +{% filter json_encode|raw %}test{% endfilter %} +--DATA-- +return array() +--EXPECT-- +"test" diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/multiple.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/multiple.test new file mode 100644 index 0000000..75512ef --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/multiple.test @@ -0,0 +1,10 @@ +--TEST-- +"filter" tags accept multiple chained filters +--TEMPLATE-- +{% filter lower|title %} + {{ var }} +{% endfilter %} +--DATA-- +return array('var' => 'VAR') +--EXPECT-- + Var diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/nested.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/nested.test new file mode 100644 index 0000000..7e4e4eb --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/nested.test @@ -0,0 +1,16 @@ +--TEST-- +"filter" tags can be nested at will +--TEMPLATE-- +{% filter lower|title %} + {{ var }} + {% filter upper %} + {{ var }} + {% endfilter %} + {{ var }} +{% endfilter %} +--DATA-- +return array('var' => 'var') +--EXPECT-- + Var + Var + Var diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/with_for_tag.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/with_for_tag.test new file mode 100644 index 0000000..22745ea --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/with_for_tag.test @@ -0,0 +1,13 @@ +--TEST-- +"filter" tag applies the filter on "for" tags +--TEMPLATE-- +{% filter upper %} +{% for item in items %} +{{ item }} +{% endfor %} +{% endfilter %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- +A +B diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/with_if_tag.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/with_if_tag.test new file mode 100644 index 0000000..afd95b2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/filter/with_if_tag.test @@ -0,0 +1,29 @@ +--TEST-- +"filter" tag applies the filter on "if" tags +--TEMPLATE-- +{% filter upper %} +{% if items %} +{{ items|join(', ') }} +{% endif %} + +{% if items.3 is defined %} +FOO +{% else %} +{{ items.1 }} +{% endif %} + +{% if items.3 is defined %} +FOO +{% elseif items.1 %} +{{ items.0 }} +{% endif %} + +{% endfilter %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- +A, B + +B + +A diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/condition.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/condition.test new file mode 100644 index 0000000..380531f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/condition.test @@ -0,0 +1,14 @@ +--TEST-- +"for" tag takes a condition +--TEMPLATE-- +{% for i in 1..5 if i is odd -%} + {{ loop.index }}.{{ i }}{{ foo.bar }} +{% endfor %} +--DATA-- +return array('foo' => array('bar' => 'X')) +--CONFIG-- +return array('strict_variables' => false) +--EXPECT-- +1.1X +2.3X +3.5X diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/context.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/context.test new file mode 100644 index 0000000..ddc6930 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/context.test @@ -0,0 +1,18 @@ +--TEST-- +"for" tag keeps the context safe +--TEMPLATE-- +{% for item in items %} + {% for item in items %} + * {{ item }} + {% endfor %} + * {{ item }} +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- + * a + * b + * a + * a + * b + * b diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/else.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/else.test new file mode 100644 index 0000000..20ccc88 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/else.test @@ -0,0 +1,23 @@ +--TEST-- +"for" tag can use an "else" clause +--TEMPLATE-- +{% for item in items %} + * {{ item }} +{% else %} + no item +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- + * a + * b +--DATA-- +return array('items' => array()) +--EXPECT-- + no item +--DATA-- +return array() +--CONFIG-- +return array('strict_variables' => false) +--EXPECT-- + no item diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/inner_variables.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/inner_variables.test new file mode 100644 index 0000000..49fb9ca --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/inner_variables.test @@ -0,0 +1,17 @@ +--TEST-- +"for" tag does not reset inner variables +--TEMPLATE-- +{% for i in 1..2 %} + {% for j in 0..2 %} + {{k}}{% set k = k+1 %} {{ loop.parent.loop.index }} + {% endfor %} +{% endfor %} +--DATA-- +return array('k' => 0) +--EXPECT-- + 0 1 + 1 1 + 2 1 + 3 2 + 4 2 + 5 2 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/keys.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/keys.test new file mode 100644 index 0000000..4e22cb4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/keys.test @@ -0,0 +1,11 @@ +--TEST-- +"for" tag can iterate over keys +--TEMPLATE-- +{% for key in items|keys %} + * {{ key }} +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- + * 0 + * 1 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/keys_and_values.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/keys_and_values.test new file mode 100644 index 0000000..4c21168 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/keys_and_values.test @@ -0,0 +1,11 @@ +--TEST-- +"for" tag can iterate over keys and values +--TEMPLATE-- +{% for key, item in items %} + * {{ key }}/{{ item }} +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- + * 0/a + * 1/b diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_context.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_context.test new file mode 100644 index 0000000..93bc76a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_context.test @@ -0,0 +1,19 @@ +--TEST-- +"for" tag adds a loop variable to the context +--TEMPLATE-- +{% for item in items %} + * {{ loop.index }}/{{ loop.index0 }} + * {{ loop.revindex }}/{{ loop.revindex0 }} + * {{ loop.first }}/{{ loop.last }}/{{ loop.length }} + +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- + * 1/0 + * 2/1 + * 1//2 + + * 2/1 + * 1/0 + * /1/2 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_context_local.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_context_local.test new file mode 100644 index 0000000..58af2c3 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_context_local.test @@ -0,0 +1,10 @@ +--TEST-- +"for" tag adds a loop variable to the context locally +--TEMPLATE-- +{% for item in items %} +{% endfor %} +{% if loop is not defined %}WORKS{% endif %} +--DATA-- +return array('items' => array()) +--EXPECT-- +WORKS diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_not_defined.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_not_defined.test new file mode 100644 index 0000000..6a2af63 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_not_defined.test @@ -0,0 +1,10 @@ +--TEST-- +"for" tag +--TEMPLATE-- +{% for i, item in items if i > 0 %} + {{ loop.last }} +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXCEPTION-- +Twig_Error_Syntax: The "loop.last" variable is not defined when looping with a condition in "index.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_not_defined_cond.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_not_defined_cond.test new file mode 100644 index 0000000..1e819ca --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/loop_not_defined_cond.test @@ -0,0 +1,9 @@ +--TEST-- +"for" tag +--TEMPLATE-- +{% for i, item in items if loop.last > 0 %} +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXCEPTION-- +Twig_Error_Syntax: The "loop" variable cannot be used in a looping condition in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/nested_else.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/nested_else.test new file mode 100644 index 0000000..f8b9f6b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/nested_else.test @@ -0,0 +1,17 @@ +--TEST-- +"for" tag can use an "else" clause +--TEMPLATE-- +{% for item in items %} + {% for item in items1 %} + * {{ item }} + {% else %} + no {{ item }} + {% endfor %} +{% else %} + no item1 +{% endfor %} +--DATA-- +return array('items' => array('a', 'b'), 'items1' => array()) +--EXPECT-- +no a + no b diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/objects.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/objects.test new file mode 100644 index 0000000..5034437 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/objects.test @@ -0,0 +1,43 @@ +--TEST-- +"for" tag iterates over iterable objects +--TEMPLATE-- +{% for item in items %} + * {{ item }} + * {{ loop.index }}/{{ loop.index0 }} + * {{ loop.first }} + +{% endfor %} + +{% for key, value in items %} + * {{ key }}/{{ value }} +{% endfor %} + +{% for key in items|keys %} + * {{ key }} +{% endfor %} +--DATA-- +class ItemsIterator implements Iterator +{ + protected $values = array('foo' => 'bar', 'bar' => 'foo'); + public function current() { return current($this->values); } + public function key() { return key($this->values); } + public function next() { return next($this->values); } + public function rewind() { return reset($this->values); } + public function valid() { return false !== current($this->values); } +} +return array('items' => new ItemsIterator()) +--EXPECT-- + * bar + * 1/0 + * 1 + + * foo + * 2/1 + * + + + * foo/bar + * bar/foo + + * foo + * bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/objects_countable.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/objects_countable.test new file mode 100644 index 0000000..4a1ff61 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/objects_countable.test @@ -0,0 +1,47 @@ +--TEST-- +"for" tag iterates over iterable and countable objects +--TEMPLATE-- +{% for item in items %} + * {{ item }} + * {{ loop.index }}/{{ loop.index0 }} + * {{ loop.revindex }}/{{ loop.revindex0 }} + * {{ loop.first }}/{{ loop.last }}/{{ loop.length }} + +{% endfor %} + +{% for key, value in items %} + * {{ key }}/{{ value }} +{% endfor %} + +{% for key in items|keys %} + * {{ key }} +{% endfor %} +--DATA-- +class ItemsIteratorCountable implements Iterator, Countable +{ + protected $values = array('foo' => 'bar', 'bar' => 'foo'); + public function current() { return current($this->values); } + public function key() { return key($this->values); } + public function next() { return next($this->values); } + public function rewind() { return reset($this->values); } + public function valid() { return false !== current($this->values); } + public function count() { return count($this->values); } +} +return array('items' => new ItemsIteratorCountable()) +--EXPECT-- + * bar + * 1/0 + * 2/1 + * 1//2 + + * foo + * 2/1 + * 1/0 + * /1/2 + + + * foo/bar + * bar/foo + + * foo + * bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/recursive.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/recursive.test new file mode 100644 index 0000000..17b2e22 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/recursive.test @@ -0,0 +1,18 @@ +--TEST-- +"for" tags can be nested +--TEMPLATE-- +{% for key, item in items %} +* {{ key }} ({{ loop.length }}): +{% for value in item %} + * {{ value }} ({{ loop.length }}) +{% endfor %} +{% endfor %} +--DATA-- +return array('items' => array('a' => array('a1', 'a2', 'a3'), 'b' => array('b1'))) +--EXPECT-- +* a (2): + * a1 (3) + * a2 (3) + * a3 (3) +* b (2): + * b1 (1) diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/values.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/values.test new file mode 100644 index 0000000..82f2ae8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/for/values.test @@ -0,0 +1,11 @@ +--TEST-- +"for" tag iterates over item values +--TEMPLATE-- +{% for item in items %} + * {{ item }} +{% endfor %} +--DATA-- +return array('items' => array('a', 'b')) +--EXPECT-- + * a + * b diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/from.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/from.test new file mode 100644 index 0000000..5f5da0e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/from.test @@ -0,0 +1,14 @@ +--TEST-- +global variables +--TEMPLATE-- +{% include "included.twig" %} +{% from "included.twig" import foobar %} +{{ foobar() }} +--TEMPLATE(included.twig)-- +{% macro foobar() %} +called foobar +{% endmacro %} +--DATA-- +return array(); +--EXPECT-- +called foobar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/if/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/if/basic.test new file mode 100644 index 0000000..c1c3d27 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/if/basic.test @@ -0,0 +1,22 @@ +--TEST-- +"if" creates a condition +--TEMPLATE-- +{% if a is defined %} + {{ a }} +{% elseif b is defined %} + {{ b }} +{% else %} + NOTHING +{% endif %} +--DATA-- +return array('a' => 'a') +--EXPECT-- + a +--DATA-- +return array('b' => 'b') +--EXPECT-- + b +--DATA-- +return array() +--EXPECT-- + NOTHING diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/if/expression.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/if/expression.test new file mode 100644 index 0000000..edfb73d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/if/expression.test @@ -0,0 +1,22 @@ +--TEST-- +"if" takes an expression as a test +--TEMPLATE-- +{% if a < 2 %} + A1 +{% elseif a > 10 %} + A2 +{% else %} + A3 +{% endif %} +--DATA-- +return array('a' => 1) +--EXPECT-- + A1 +--DATA-- +return array('a' => 12) +--EXPECT-- + A2 +--DATA-- +return array('a' => 7) +--EXPECT-- + A3 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/basic.test new file mode 100644 index 0000000..8fe1a6c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/basic.test @@ -0,0 +1,16 @@ +--TEST-- +"include" tag +--TEMPLATE-- +FOO +{% include "foo.twig" %} + +BAR +--TEMPLATE(foo.twig)-- +FOOBAR +--DATA-- +return array() +--EXPECT-- +FOO + +FOOBAR +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/expression.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/expression.test new file mode 100644 index 0000000..eaeeb11 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/expression.test @@ -0,0 +1,16 @@ +--TEST-- +"include" tag allows expressions for the template to include +--TEMPLATE-- +FOO +{% include foo %} + +BAR +--TEMPLATE(foo.twig)-- +FOOBAR +--DATA-- +return array('foo' => 'foo.twig') +--EXPECT-- +FOO + +FOOBAR +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/ignore_missing.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/ignore_missing.test new file mode 100644 index 0000000..24aed06 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/ignore_missing.test @@ -0,0 +1,10 @@ +--TEST-- +"include" tag +--TEMPLATE-- +{% include ["foo.twig", "bar.twig"] ignore missing %} +{% include "foo.twig" ignore missing %} +{% include "foo.twig" ignore missing with {} %} +{% include "foo.twig" ignore missing with {} only %} +--DATA-- +return array() +--EXPECT-- diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/missing.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/missing.test new file mode 100644 index 0000000..f25e871 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/missing.test @@ -0,0 +1,8 @@ +--TEST-- +"include" tag +--TEMPLATE-- +{% include "foo.twig" %} +--DATA-- +return array(); +--EXCEPTION-- +Twig_Error_Loader: Template "foo.twig" is not defined in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/missing_nested.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/missing_nested.test new file mode 100644 index 0000000..86c1864 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/missing_nested.test @@ -0,0 +1,16 @@ +--TEST-- +"include" tag +--TEMPLATE-- +{% extends "base.twig" %} + +{% block content %} + {{ parent() }} +{% endblock %} +--TEMPLATE(base.twig)-- +{% block content %} + {% include "foo.twig" %} +{% endblock %} +--DATA-- +return array(); +--EXCEPTION-- +Twig_Error_Loader: Template "foo.twig" is not defined in "base.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/only.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/only.test new file mode 100644 index 0000000..77760a0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/only.test @@ -0,0 +1,16 @@ +--TEST-- +"include" tag accept variables and only +--TEMPLATE-- +{% include "foo.twig" %} +{% include "foo.twig" only %} +{% include "foo.twig" with {'foo1': 'bar'} %} +{% include "foo.twig" with {'foo1': 'bar'} only %} +--TEMPLATE(foo.twig)-- +{% for k, v in _context %}{{ k }},{% endfor %} +--DATA-- +return array('foo' => 'bar') +--EXPECT-- +foo,global,_parent, +global,_parent, +foo,global,foo1,_parent, +foo1,global,_parent, diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/template_instance.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/template_instance.test new file mode 100644 index 0000000..6ba064a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/template_instance.test @@ -0,0 +1,10 @@ +--TEST-- +"include" tag accepts Twig_Template instance +--TEMPLATE-- +{% include foo %} FOO +--TEMPLATE(foo.twig)-- +BAR +--DATA-- +return array('foo' => $twig->loadTemplate('foo.twig')) +--EXPECT-- +BAR FOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/templates_as_array.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/templates_as_array.test new file mode 100644 index 0000000..ab670ee --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/templates_as_array.test @@ -0,0 +1,12 @@ +--TEST-- +"include" tag +--TEMPLATE-- +{% include ["foo.twig", "bar.twig"] %} +{% include ["bar.twig", "foo.twig"] %} +--TEMPLATE(foo.twig)-- +foo +--DATA-- +return array() +--EXPECT-- +foo +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/with_variables.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/with_variables.test new file mode 100644 index 0000000..41384ac --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/include/with_variables.test @@ -0,0 +1,12 @@ +--TEST-- +"include" tag accept variables +--TEMPLATE-- +{% include "foo.twig" with {'foo': 'bar'} %} +{% include "foo.twig" with vars %} +--TEMPLATE(foo.twig)-- +{{ foo }} +--DATA-- +return array('vars' => array('foo' => 'bar')) +--EXPECT-- +bar +bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/basic.test new file mode 100644 index 0000000..0778a4b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/basic.test @@ -0,0 +1,14 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends "foo.twig" %} + +{% block content %} +FOO +{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %}{% endblock %} +--DATA-- +return array() +--EXPECT-- +FOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/block_expr.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/block_expr.test new file mode 100644 index 0000000..9a81499 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/block_expr.test @@ -0,0 +1,32 @@ +--TEST-- +block_expr +--TEMPLATE-- +{% extends "base.twig" %} + +{% block element -%} + Element: + {{- parent() -}} +{% endblock %} +--TEMPLATE(base.twig)-- +{% spaceless %} +{% block element -%} +
    + {%- if item.children is defined %} + {%- for item in item.children %} + {{- block('element') -}} + {% endfor %} + {%- endif -%} +
    +{%- endblock %} +{% endspaceless %} +--DATA-- +return array( + 'item' => array( + 'children' => array( + null, + null, + ) + ) +) +--EXPECT-- +Element:
    Element:
    Element:
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/block_expr2.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/block_expr2.test new file mode 100644 index 0000000..3e868c0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/block_expr2.test @@ -0,0 +1,34 @@ +--TEST-- +block_expr2 +--TEMPLATE-- +{% extends "base2.twig" %} + +{% block element -%} + Element: + {{- parent() -}} +{% endblock %} +--TEMPLATE(base2.twig)-- +{% extends "base.twig" %} +--TEMPLATE(base.twig)-- +{% spaceless %} +{% block element -%} +
    + {%- if item.children is defined %} + {%- for item in item.children %} + {{- block('element') -}} + {% endfor %} + {%- endif -%} +
    +{%- endblock %} +{% endspaceless %} +--DATA-- +return array( + 'item' => array( + 'children' => array( + null, + null, + ) + ) +) +--EXPECT-- +Element:
    Element:
    Element:
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/conditional.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/conditional.test new file mode 100644 index 0000000..8576e77 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/conditional.test @@ -0,0 +1,14 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends standalone ? foo : 'bar.twig' %} + +{% block content %}{{ parent() }}FOO{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %}FOO{% endblock %} +--TEMPLATE(bar.twig)-- +{% block content %}BAR{% endblock %} +--DATA-- +return array('foo' => 'foo.twig', 'standalone' => true) +--EXPECT-- +FOOFOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/dynamic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/dynamic.test new file mode 100644 index 0000000..ee06ddc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/dynamic.test @@ -0,0 +1,14 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends foo %} + +{% block content %} +FOO +{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %}{% endblock %} +--DATA-- +return array('foo' => 'foo.twig') +--EXPECT-- +FOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/empty.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/empty.test new file mode 100644 index 0000000..784f357 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/empty.test @@ -0,0 +1,10 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends "foo.twig" %} +--TEMPLATE(foo.twig)-- +{% block content %}FOO{% endblock %} +--DATA-- +return array() +--EXPECT-- +FOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array.test new file mode 100644 index 0000000..a1cb1ce --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array.test @@ -0,0 +1,12 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends ["foo.twig", "bar.twig"] %} +--TEMPLATE(bar.twig)-- +{% block content %} +foo +{% endblock %} +--DATA-- +return array() +--EXPECT-- +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_empty_name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_empty_name.test new file mode 100644 index 0000000..acc74f6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_empty_name.test @@ -0,0 +1,12 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends ["", "bar.twig"] %} +--TEMPLATE(bar.twig)-- +{% block content %} +foo +{% endblock %} +--DATA-- +return array() +--EXPECT-- +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_null_name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_null_name.test new file mode 100644 index 0000000..cfa648d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_null_name.test @@ -0,0 +1,12 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends [null, "bar.twig"] %} +--TEMPLATE(bar.twig)-- +{% block content %} +foo +{% endblock %} +--DATA-- +return array() +--EXPECT-- +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/multiple.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/multiple.test new file mode 100644 index 0000000..dfc2b6c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/multiple.test @@ -0,0 +1,12 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends "layout.twig" %}{% block content %}{{ parent() }}index {% endblock %} +--TEMPLATE(layout.twig)-- +{% extends "base.twig" %}{% block content %}{{ parent() }}layout {% endblock %} +--TEMPLATE(base.twig)-- +{% block content %}base {% endblock %} +--DATA-- +return array() +--EXPECT-- +base layout index diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/multiple_dynamic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/multiple_dynamic.test new file mode 100644 index 0000000..1d3e639 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/multiple_dynamic.test @@ -0,0 +1,22 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% set foo = 1 %} +{{ include('parent.twig') }} +{{ include('parent.twig') }} +{% set foo = 2 %} +{{ include('parent.twig') }} +--TEMPLATE(parent.twig)-- +{% extends foo~'_parent.twig' %}{% block content %}{{ parent() }} parent{% endblock %} +--TEMPLATE(1_parent.twig)-- +{% block content %}1{% endblock %} +--TEMPLATE(2_parent.twig)-- +{% block content %}2{% endblock %} +--DATA-- +return array() +--EXPECT-- +1 parent + +1 parent + +2 parent diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks.test new file mode 100644 index 0000000..faca925 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks.test @@ -0,0 +1,22 @@ +--TEST-- +"block" tag +--TEMPLATE-- +{% extends "foo.twig" %} + +{% block content %} + {% block subcontent %} + {% block subsubcontent %} + SUBSUBCONTENT + {% endblock %} + {% endblock %} +{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %} + {% block subcontent %} + SUBCONTENT + {% endblock %} +{% endblock %} +--DATA-- +return array() +--EXPECT-- +SUBSUBCONTENT diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks_parent_only.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks_parent_only.test new file mode 100644 index 0000000..0ad11d0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks_parent_only.test @@ -0,0 +1,15 @@ +--TEST-- +"block" tag +--TEMPLATE-- +{% block content %} + CONTENT + {%- block subcontent -%} + SUBCONTENT + {%- endblock -%} + ENDCONTENT +{% endblock %} +--TEMPLATE(foo.twig)-- +--DATA-- +return array() +--EXPECT-- +CONTENTSUBCONTENTENDCONTENT diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_inheritance.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_inheritance.test new file mode 100644 index 0000000..71e3cdf --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/nested_inheritance.test @@ -0,0 +1,16 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends "layout.twig" %} +{% block inside %}INSIDE{% endblock inside %} +--TEMPLATE(layout.twig)-- +{% extends "base.twig" %} +{% block body %} + {% block inside '' %} +{% endblock body %} +--TEMPLATE(base.twig)-- +{% block body '' %} +--DATA-- +return array() +--EXPECT-- +INSIDE diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent.test new file mode 100644 index 0000000..4f975db --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent.test @@ -0,0 +1,12 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends "foo.twig" %} + +{% block content %}{{ parent() }}FOO{{ parent() }}{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %}BAR{% endblock %} +--DATA-- +return array() +--EXPECT-- +BARFOOBAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_change.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_change.test new file mode 100644 index 0000000..a8bc90c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_change.test @@ -0,0 +1,16 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends foo ? 'foo.twig' : 'bar.twig' %} +--TEMPLATE(foo.twig)-- +FOO +--TEMPLATE(bar.twig)-- +BAR +--DATA-- +return array('foo' => true) +--EXPECT-- +FOO +--DATA-- +return array('foo' => false) +--EXPECT-- +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_in_a_block.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_in_a_block.test new file mode 100644 index 0000000..cca6dbc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_in_a_block.test @@ -0,0 +1,8 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% block content %} + {% extends "foo.twig" %} +{% endblock %} +--EXCEPTION-- +Twig_Error_Syntax: Cannot extend from a block in "index.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_isolation.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_isolation.test new file mode 100644 index 0000000..6281671 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_isolation.test @@ -0,0 +1,20 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends "base.twig" %} +{% block content %}{% include "included.twig" %}{% endblock %} + +{% block footer %}Footer{% endblock %} +--TEMPLATE(included.twig)-- +{% extends "base.twig" %} +{% block content %}Included Content{% endblock %} +--TEMPLATE(base.twig)-- +{% block content %}Default Content{% endblock %} + +{% block footer %}Default Footer{% endblock %} +--DATA-- +return array() +--EXPECT-- +Included Content +Default Footer +Footer diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_nested.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_nested.test new file mode 100644 index 0000000..71e7c20 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_nested.test @@ -0,0 +1,28 @@ +--TEST-- +"extends" tag +--TEMPLATE-- +{% extends "foo.twig" %} + +{% block content %} + {% block inside %} + INSIDE OVERRIDDEN + {% endblock %} + + BEFORE + {{ parent() }} + AFTER +{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %} + BAR +{% endblock %} +--DATA-- +return array() +--EXPECT-- + +INSIDE OVERRIDDEN + + BEFORE + BAR + + AFTER diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends.test new file mode 100644 index 0000000..e29b1ac --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends.test @@ -0,0 +1,8 @@ +--TEST-- +"parent" tag +--TEMPLATE-- +{% block content %} + {{ parent() }} +{% endblock %} +--EXCEPTION-- +Twig_Error_Syntax: Calling "parent" on a template that does not extend nor "use" another template is forbidden in "index.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends_but_traits.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends_but_traits.test new file mode 100644 index 0000000..63c7305 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends_but_traits.test @@ -0,0 +1,14 @@ +--TEST-- +"parent" tag +--TEMPLATE-- +{% use 'foo.twig' %} + +{% block content %} + {{ parent() }} +{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %}BAR{% endblock %} +--DATA-- +return array() +--EXPECT-- +BAR diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/template_instance.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/template_instance.test new file mode 100644 index 0000000..d1876a5 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/template_instance.test @@ -0,0 +1,14 @@ +--TEST-- +"extends" tag accepts Twig_Template instance +--TEMPLATE-- +{% extends foo %} + +{% block content %} +{{ parent() }}FOO +{% endblock %} +--TEMPLATE(foo.twig)-- +{% block content %}BAR{% endblock %} +--DATA-- +return array('foo' => $twig->loadTemplate('foo.twig')) +--EXPECT-- +BARFOO diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/use.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/use.test new file mode 100644 index 0000000..8f9ece7 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/inheritance/use.test @@ -0,0 +1,44 @@ +--TEST-- +"parent" function +--TEMPLATE-- +{% extends "parent.twig" %} + +{% use "use1.twig" %} +{% use "use2.twig" %} + +{% block content_parent %} + {{ parent() }} +{% endblock %} + +{% block content_use1 %} + {{ parent() }} +{% endblock %} + +{% block content_use2 %} + {{ parent() }} +{% endblock %} + +{% block content %} + {{ block('content_use1_only') }} + {{ block('content_use2_only') }} +{% endblock %} +--TEMPLATE(parent.twig)-- +{% block content_parent 'content_parent' %} +{% block content_use1 'content_parent' %} +{% block content_use2 'content_parent' %} +{% block content '' %} +--TEMPLATE(use1.twig)-- +{% block content_use1 'content_use1' %} +{% block content_use2 'content_use1' %} +{% block content_use1_only 'content_use1_only' %} +--TEMPLATE(use2.twig)-- +{% block content_use2 'content_use2' %} +{% block content_use2_only 'content_use2_only' %} +--DATA-- +return array() +--EXPECT-- + content_parent + content_use1 + content_use2 + content_use1_only + content_use2_only diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/basic.test new file mode 100644 index 0000000..eef0c10 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/basic.test @@ -0,0 +1,17 @@ +--TEST-- +"macro" tag +--TEMPLATE-- +{% import _self as macros %} + +{{ macros.input('username') }} +{{ macros.input('password', null, 'password', 1) }} + +{% macro input(name, value, type, size) %} + +{% endmacro %} +--DATA-- +return array() +--EXPECT-- + + + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/endmacro_name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/endmacro_name.test new file mode 100644 index 0000000..ae6203b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/endmacro_name.test @@ -0,0 +1,16 @@ +--TEST-- +"macro" tag supports name for endmacro +--TEMPLATE-- +{% import _self as macros %} + +{{ macros.foo() }} +{{ macros.bar() }} + +{% macro foo() %}foo{% endmacro %} +{% macro bar() %}bar{% endmacro bar %} +--DATA-- +return array() +--EXPECT-- +foo +bar + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/external.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/external.test new file mode 100644 index 0000000..5cd3dae --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/external.test @@ -0,0 +1,17 @@ +--TEST-- +"macro" tag +--TEMPLATE-- +{% import 'forms.twig' as forms %} + +{{ forms.input('username') }} +{{ forms.input('password', null, 'password', 1) }} +--TEMPLATE(forms.twig)-- +{% macro input(name, value, type, size) %} + +{% endmacro %} +--DATA-- +return array() +--EXPECT-- + + + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/from.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/from.test new file mode 100644 index 0000000..205f591 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/from.test @@ -0,0 +1,18 @@ +--TEST-- +"macro" tag +--TEMPLATE-- +{% from 'forms.twig' import foo %} +{% from 'forms.twig' import foo as foobar, bar %} + +{{ foo('foo') }} +{{ foobar('foo') }} +{{ bar('foo') }} +--TEMPLATE(forms.twig)-- +{% macro foo(name) %}foo{{ name }}{% endmacro %} +{% macro bar(name) %}bar{{ name }}{% endmacro %} +--DATA-- +return array() +--EXPECT-- +foofoo +foofoo +barfoo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/from_with_reserved_name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/from_with_reserved_name.test new file mode 100644 index 0000000..2de9765 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/from_with_reserved_name.test @@ -0,0 +1,9 @@ +--TEST-- +"from" tag with reserved name +--TEMPLATE-- +{% from 'forms.twig' import templateName %} +--TEMPLATE(forms.twig)-- +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: "templateName" cannot be an imported macro as it is a reserved keyword in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/global.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/global.test new file mode 100644 index 0000000..6b37176 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/global.test @@ -0,0 +1,14 @@ +--TEST-- +"macro" tag +--TEMPLATE-- +{% from 'forms.twig' import foo %} + +{{ foo('foo') }} +{{ foo() }} +--TEMPLATE(forms.twig)-- +{% macro foo(name) %}{{ name|default('foo') }}{{ global }}{% endmacro %} +--DATA-- +return array() +--EXPECT-- +fooglobal +fooglobal diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/import_with_reserved_nam.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/import_with_reserved_nam.test new file mode 100644 index 0000000..7bd93c6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/import_with_reserved_nam.test @@ -0,0 +1,11 @@ +--TEST-- +"from" tag with reserved name +--TEMPLATE-- +{% import 'forms.twig' as macros %} + +{{ macros.parent() }} +--TEMPLATE(forms.twig)-- +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: "parent" cannot be called as macro as it is a reserved keyword in "index.twig" at line 4. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/reserved_name.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/reserved_name.test new file mode 100644 index 0000000..f7c102f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/reserved_name.test @@ -0,0 +1,10 @@ +--TEST-- +"macro" tag with reserved name +--TEMPLATE-- +{% macro parent(arg1, arg2) %} + parent +{% endmacro %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: "parent" cannot be used as a macro name as it is a reserved keyword in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/self_import.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/self_import.test new file mode 100644 index 0000000..17756cb --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/self_import.test @@ -0,0 +1,17 @@ +--TEST-- +"macro" tag +--TEMPLATE-- +{% import _self as forms %} + +{{ forms.input('username') }} +{{ forms.input('password', null, 'password', 1) }} + +{% macro input(name, value, type, size) %} + +{% endmacro %} +--DATA-- +return array() +--EXPECT-- + + + diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/special_chars.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/special_chars.test new file mode 100644 index 0000000..3721770 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/special_chars.test @@ -0,0 +1,14 @@ +--TEST-- +"§" as a macro name +--TEMPLATE-- +{% import _self as macros %} + +{{ macros.§('foo') }} + +{% macro §(foo) %} + §{{ foo }}§ +{% endmacro %} +--DATA-- +return array() +--EXPECT-- +§foo§ diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/super_globals.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/super_globals.test new file mode 100644 index 0000000..5679462 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/macro/super_globals.test @@ -0,0 +1,14 @@ +--TEST-- +Super globals as macro arguments +--TEMPLATE-- +{% import _self as macros %} + +{{ macros.foo('foo') }} + +{% macro foo(GET) %} + {{ GET }} +{% endmacro %} +--DATA-- +return array() +--EXPECT-- +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/basic.legacy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/basic.legacy.test new file mode 100644 index 0000000..0445e85 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/basic.legacy.test @@ -0,0 +1,10 @@ +--TEST-- +"raw" tag +--TEMPLATE-- +{% raw %} +{{ foo }} +{% endraw %} +--DATA-- +return array() +--EXPECT-- +{{ foo }} diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/mixed_usage_with_raw.legacy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/mixed_usage_with_raw.legacy.test new file mode 100644 index 0000000..99deefc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/mixed_usage_with_raw.legacy.test @@ -0,0 +1,10 @@ +--TEST-- +"raw" tag +--TEMPLATE-- +{% raw %} +{{ foo }} +{% endverbatim %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: Unexpected end of file: Unclosed "raw" block in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/whitespace_control.legacy.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/whitespace_control.legacy.test new file mode 100644 index 0000000..352bb18 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/raw/whitespace_control.legacy.test @@ -0,0 +1,56 @@ +--TEST-- +"raw" tag +--TEMPLATE-- +1*** + +{%- raw %} + {{ 'bla' }} +{% endraw %} + +1*** +2*** + +{%- raw -%} + {{ 'bla' }} +{% endraw %} + +2*** +3*** + +{%- raw -%} + {{ 'bla' }} +{% endraw -%} + +3*** +4*** + +{%- raw -%} + {{ 'bla' }} +{%- endraw %} + +4*** +5*** + +{%- raw -%} + {{ 'bla' }} +{%- endraw -%} + +5*** +--DATA-- +return array() +--EXPECT-- +1*** + {{ 'bla' }} + + +1*** +2***{{ 'bla' }} + + +2*** +3***{{ 'bla' }} +3*** +4***{{ 'bla' }} + +4*** +5***{{ 'bla' }}5*** diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/not_valid1.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/not_valid1.test new file mode 100644 index 0000000..dfddc15 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/not_valid1.test @@ -0,0 +1,11 @@ +--TEST-- +sandbox tag +--TEMPLATE-- +{%- sandbox %} + {%- include "foo.twig" %} + a +{%- endsandbox %} +--TEMPLATE(foo.twig)-- +foo +--EXCEPTION-- +Twig_Error_Syntax: Only "include" tags are allowed within a "sandbox" section in "index.twig" at line 4. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/not_valid2.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/not_valid2.test new file mode 100644 index 0000000..a33a13e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/not_valid2.test @@ -0,0 +1,14 @@ +--TEST-- +sandbox tag +--TEMPLATE-- +{%- sandbox %} + {%- include "foo.twig" %} + + {% if 1 %} + {%- include "foo.twig" %} + {% endif %} +{%- endsandbox %} +--TEMPLATE(foo.twig)-- +foo +--EXCEPTION-- +Twig_Error_Syntax: Only "include" tags are allowed within a "sandbox" section in "index.twig" at line 5. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/simple.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/simple.test new file mode 100644 index 0000000..de20f3d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/sandbox/simple.test @@ -0,0 +1,22 @@ +--TEST-- +sandbox tag +--TEMPLATE-- +{%- sandbox %} + {%- include "foo.twig" %} +{%- endsandbox %} + +{%- sandbox %} + {%- include "foo.twig" %} + {%- include "foo.twig" %} +{%- endsandbox %} + +{%- sandbox %}{% include "foo.twig" %}{% endsandbox %} +--TEMPLATE(foo.twig)-- +foo +--DATA-- +return array() +--EXPECT-- +foo +foo +foo +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/basic.test new file mode 100644 index 0000000..a5a9f83 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/basic.test @@ -0,0 +1,20 @@ +--TEST-- +"set" tag +--TEMPLATE-- +{% set foo = 'foo' %} +{% set bar = 'foo
    ' %} + +{{ foo }} +{{ bar }} + +{% set foo, bar = 'foo', 'bar' %} + +{{ foo }}{{ bar }} +--DATA-- +return array() +--EXPECT-- +foo +foo<br /> + + +foobar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/capture-empty.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/capture-empty.test new file mode 100644 index 0000000..ec657f0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/capture-empty.test @@ -0,0 +1,9 @@ +--TEST-- +"set" tag block empty capture +--TEMPLATE-- +{% set foo %}{% endset %} + +{% if foo %}FAIL{% endif %} +--DATA-- +return array() +--EXPECT-- diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/capture.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/capture.test new file mode 100644 index 0000000..f156a1a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/capture.test @@ -0,0 +1,10 @@ +--TEST-- +"set" tag block capture +--TEMPLATE-- +{% set foo %}f
    o
    o{% endset %} + +{{ foo }} +--DATA-- +return array() +--EXPECT-- +f
    o
    o diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/expression.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/expression.test new file mode 100644 index 0000000..8ff434a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/set/expression.test @@ -0,0 +1,12 @@ +--TEST-- +"set" tag +--TEMPLATE-- +{% set foo, bar = 'foo' ~ 'bar', 'bar' ~ 'foo' %} + +{{ foo }} +{{ bar }} +--DATA-- +return array() +--EXPECT-- +foobar +barfoo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/spaceless/simple.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/spaceless/simple.test new file mode 100644 index 0000000..dd06dec --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/spaceless/simple.test @@ -0,0 +1,12 @@ +--TEST-- +"spaceless" tag removes whites between HTML tags +--TEMPLATE-- +{% spaceless %} + +
    foo
    + +{% endspaceless %} +--DATA-- +return array() +--EXPECT-- +
    foo
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/special_chars.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/special_chars.test new file mode 100644 index 0000000..789b4ba --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/special_chars.test @@ -0,0 +1,8 @@ +--TEST-- +"§" custom tag +--TEMPLATE-- +{% § %} +--DATA-- +return array() +--EXPECT-- +§ diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/trim_block.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/trim_block.test new file mode 100644 index 0000000..1d2273f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/trim_block.test @@ -0,0 +1,74 @@ +--TEST-- +Whitespace trimming on tags. +--TEMPLATE-- +{{ 5 * '{#-'|length }} +{{ '{{-'|length * 5 + '{%-'|length }} + +Trim on control tag: +{% for i in range(1, 9) -%} + {{ i }} +{%- endfor %} + + +Trim on output tag: +{% for i in range(1, 9) %} + {{- i -}} +{% endfor %} + + +Trim comments: + +{#- Invisible -#} + +After the comment. + +Trim leading space: +{% if leading %} + + {{- leading }} +{% endif %} + +{%- if leading %} + {{- leading }} + +{%- endif %} + + +Trim trailing space: +{% if trailing -%} + {{ trailing -}} + +{% endif -%} + +Combined: + +{%- if both -%} +
      +
    • {{- both -}}
    • +
    + +{%- endif -%} + +end +--DATA-- +return array('leading' => 'leading space', 'trailing' => 'trailing space', 'both' => 'both') +--EXPECT-- +15 +18 + +Trim on control tag: +123456789 + +Trim on output tag: +123456789 + +Trim comments:After the comment. + +Trim leading space: +leading space +leading space + +Trim trailing space: +trailing spaceCombined:
      +
    • both
    • +
    end diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/aliases.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/aliases.test new file mode 100644 index 0000000..f887006 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/aliases.test @@ -0,0 +1,12 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "blocks.twig" with content as foo %} + +{{ block('foo') }} +--TEMPLATE(blocks.twig)-- +{% block content 'foo' %} +--DATA-- +return array() +--EXPECT-- +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/basic.test new file mode 100644 index 0000000..7364d76 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/basic.test @@ -0,0 +1,12 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "blocks.twig" %} + +{{ block('content') }} +--TEMPLATE(blocks.twig)-- +{% block content 'foo' %} +--DATA-- +return array() +--EXPECT-- +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/deep.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/deep.test new file mode 100644 index 0000000..b551a1e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/deep.test @@ -0,0 +1,22 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "foo.twig" %} + +{{ block('content') }} +{{ block('foo') }} +{{ block('bar') }} +--TEMPLATE(foo.twig)-- +{% use "bar.twig" %} + +{% block content 'foo' %} +{% block foo 'foo' %} +--TEMPLATE(bar.twig)-- +{% block content 'bar' %} +{% block bar 'bar' %} +--DATA-- +return array() +--EXPECT-- +foo +foo +bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/deep_empty.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/deep_empty.test new file mode 100644 index 0000000..05cca68 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/deep_empty.test @@ -0,0 +1,10 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "foo.twig" %} +--TEMPLATE(foo.twig)-- +{% use "bar.twig" %} +--TEMPLATE(bar.twig)-- +--DATA-- +return array() +--EXPECT-- diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/inheritance.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/inheritance.test new file mode 100644 index 0000000..0d0d470 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/inheritance.test @@ -0,0 +1,25 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "parent.twig" %} + +{{ block('container') }} +--TEMPLATE(parent.twig)-- +{% use "ancestor.twig" %} + +{% block sub_container %} +
    overridden sub_container
    +{% endblock %} +--TEMPLATE(ancestor.twig)-- +{% block container %} +
    {{ block('sub_container') }}
    +{% endblock %} + +{% block sub_container %} +
    sub_container
    +{% endblock %} +--DATA-- +return array() +--EXPECT-- +
    overridden sub_container
    +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/inheritance2.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/inheritance2.test new file mode 100644 index 0000000..df95599 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/inheritance2.test @@ -0,0 +1,24 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "ancestor.twig" %} +{% use "parent.twig" %} + +{{ block('container') }} +--TEMPLATE(parent.twig)-- +{% block sub_container %} +
    overridden sub_container
    +{% endblock %} +--TEMPLATE(ancestor.twig)-- +{% block container %} +
    {{ block('sub_container') }}
    +{% endblock %} + +{% block sub_container %} +
    sub_container
    +{% endblock %} +--DATA-- +return array() +--EXPECT-- +
    overridden sub_container
    +
    diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/multiple.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/multiple.test new file mode 100644 index 0000000..198be0c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/multiple.test @@ -0,0 +1,21 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "foo.twig" %} +{% use "bar.twig" %} + +{{ block('content') }} +{{ block('foo') }} +{{ block('bar') }} +--TEMPLATE(foo.twig)-- +{% block content 'foo' %} +{% block foo 'foo' %} +--TEMPLATE(bar.twig)-- +{% block content 'bar' %} +{% block bar 'bar' %} +--DATA-- +return array() +--EXPECT-- +bar +foo +bar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/multiple_aliases.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/multiple_aliases.test new file mode 100644 index 0000000..8de871a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/multiple_aliases.test @@ -0,0 +1,23 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use "foo.twig" with content as foo_content %} +{% use "bar.twig" %} + +{{ block('content') }} +{{ block('foo') }} +{{ block('bar') }} +{{ block('foo_content') }} +--TEMPLATE(foo.twig)-- +{% block content 'foo' %} +{% block foo 'foo' %} +--TEMPLATE(bar.twig)-- +{% block content 'bar' %} +{% block bar 'bar' %} +--DATA-- +return array() +--EXPECT-- +bar +foo +bar +foo diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block.test new file mode 100644 index 0000000..59db23d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block.test @@ -0,0 +1,24 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use 'file2.html.twig' with foobar as base_base_foobar %} +{% block foobar %} + {{- block('base_base_foobar') -}} + Content of block (second override) +{% endblock foobar %} +--TEMPLATE(file2.html.twig)-- +{% use 'file1.html.twig' with foobar as base_foobar %} +{% block foobar %} + {{- block('base_foobar') -}} + Content of block (first override) +{% endblock foobar %} +--TEMPLATE(file1.html.twig)-- +{% block foobar -%} + Content of block +{% endblock foobar %} +--DATA-- +return array() +--EXPECT-- +Content of block +Content of block (first override) +Content of block (second override) diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block2.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block2.test new file mode 100644 index 0000000..d3f302d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block2.test @@ -0,0 +1,24 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use 'file2.html.twig'%} +{% block foobar %} + {{- parent() -}} + Content of block (second override) +{% endblock foobar %} +--TEMPLATE(file2.html.twig)-- +{% use 'file1.html.twig' %} +{% block foobar %} + {{- parent() -}} + Content of block (first override) +{% endblock foobar %} +--TEMPLATE(file1.html.twig)-- +{% block foobar -%} + Content of block +{% endblock foobar %} +--DATA-- +return array() +--EXPECT-- +Content of block +Content of block (first override) +Content of block (second override) diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block3.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block3.test new file mode 100644 index 0000000..95b55a4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/parent_block3.test @@ -0,0 +1,38 @@ +--TEST-- +"use" tag +--TEMPLATE-- +{% use 'file2.html.twig' %} +{% use 'file1.html.twig' with foo %} +{% block foo %} + {{- parent() -}} + Content of foo (second override) +{% endblock foo %} +{% block bar %} + {{- parent() -}} + Content of bar (second override) +{% endblock bar %} +--TEMPLATE(file2.html.twig)-- +{% use 'file1.html.twig' %} +{% block foo %} + {{- parent() -}} + Content of foo (first override) +{% endblock foo %} +{% block bar %} + {{- parent() -}} + Content of bar (first override) +{% endblock bar %} +--TEMPLATE(file1.html.twig)-- +{% block foo -%} + Content of foo +{% endblock foo %} +{% block bar -%} + Content of bar +{% endblock bar %} +--DATA-- +return array() +--EXPECT-- +Content of foo +Content of foo (first override) +Content of foo (second override) +Content of bar +Content of bar (second override) diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/use_with_parent.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/use_with_parent.test new file mode 100644 index 0000000..3fe2ad8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/use/use_with_parent.test @@ -0,0 +1,24 @@ +--TEST-- +"use" tag with a parent block +--TEMPLATE-- +{% extends "parent.twig" %} + +{% use 'blocks.twig' %} + +{% block body %} + {{ parent() -}} + CHILD + {{ block('content') }} +{% endblock %} +--TEMPLATE(parent.twig)-- +{% block body %} + PARENT +{% endblock %} +--TEMPLATE(blocks.twig)-- +{% block content 'BLOCK' %} +--DATA-- +return array() +--EXPECT-- +PARENT +CHILD + BLOCK diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/basic.test new file mode 100644 index 0000000..a95be55 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/basic.test @@ -0,0 +1,10 @@ +--TEST-- +"verbatim" tag +--TEMPLATE-- +{% verbatim %} +{{ foo }} +{% endverbatim %} +--DATA-- +return array() +--EXPECT-- +{{ foo }} diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/mixed_usage_with_raw.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/mixed_usage_with_raw.test new file mode 100644 index 0000000..28626a8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/mixed_usage_with_raw.test @@ -0,0 +1,10 @@ +--TEST-- +"verbatim" tag +--TEMPLATE-- +{% verbatim %} +{{ foo }} +{% endraw %} +--DATA-- +return array() +--EXCEPTION-- +Twig_Error_Syntax: Unexpected end of file: Unclosed "verbatim" block in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/whitespace_control.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/whitespace_control.test new file mode 100644 index 0000000..eb61044 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/verbatim/whitespace_control.test @@ -0,0 +1,56 @@ +--TEST-- +"verbatim" tag +--TEMPLATE-- +1*** + +{%- verbatim %} + {{ 'bla' }} +{% endverbatim %} + +1*** +2*** + +{%- verbatim -%} + {{ 'bla' }} +{% endverbatim %} + +2*** +3*** + +{%- verbatim -%} + {{ 'bla' }} +{% endverbatim -%} + +3*** +4*** + +{%- verbatim -%} + {{ 'bla' }} +{%- endverbatim %} + +4*** +5*** + +{%- verbatim -%} + {{ 'bla' }} +{%- endverbatim -%} + +5*** +--DATA-- +return array() +--EXPECT-- +1*** + {{ 'bla' }} + + +1*** +2***{{ 'bla' }} + + +2*** +3***{{ 'bla' }} +3*** +4***{{ 'bla' }} + +4*** +5***{{ 'bla' }}5*** diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/basic.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/basic.test new file mode 100644 index 0000000..264ca5e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/basic.test @@ -0,0 +1,13 @@ +--TEST-- +"with" tag +--TEMPLATE-- +{% with %} + {% set bar = 'BAZ' %} + {{ foo }}{{ bar }} +{% endwith %} +{{ foo }}{{ bar }} +--DATA-- +return array('foo' => 'foo', 'bar' => 'bar') +--EXPECT-- +fooBAZ +foobar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/expression.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/expression.test new file mode 100644 index 0000000..32ed091 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/expression.test @@ -0,0 +1,10 @@ +--TEST-- +"with" tag with expression +--TEMPLATE-- +{% with {foo: 'foo', bar: 'BAZ'} %} + {{ foo }}{{ bar }} +{% endwith %} +--DATA-- +return array('foo' => 'baz') +--EXPECT-- +fooBAZ diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/nested.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/nested.test new file mode 100644 index 0000000..98e3aef --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/nested.test @@ -0,0 +1,15 @@ +--TEST-- +nested "with" tags +--TEMPLATE-- +{% set foo, bar = 'foo', 'bar' %} +{% with {bar: 'BAZ'} %} + {% with {foo: 'FOO'} %} + {{ foo }}{{ bar }} + {% endwith %} +{% endwith %} +{{ foo }}{{ bar }} +--DATA-- +return array() +--EXPECT-- +FOOBAZ + foobar diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/with_no_hash.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/with_no_hash.test new file mode 100644 index 0000000..93689f4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/with_no_hash.test @@ -0,0 +1,10 @@ +--TEST-- +"with" tag with an expression that is not a hash +--TEMPLATE-- +{% with vars %} + {{ foo }}{{ bar }} +{% endwith %} +--DATA-- +return array('vars' => 'no-hash') +--EXCEPTION-- +Twig_Error_Runtime: Variables passed to the "with" tag must be a hash in "index.twig" at line 2. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/with_only.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/with_only.test new file mode 100644 index 0000000..6247617 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tags/with/with_only.test @@ -0,0 +1,10 @@ +--TEST-- +"with" tag with expression and only +--TEMPLATE-- +{% with {foo: 'foo', bar: 'BAZ'} only %} + {{ foo }}{{ bar }}{{ baz }} +{% endwith %} +--DATA-- +return array('foo' => 'baz', 'baz' => 'baz') +--EXCEPTION-- +Twig_Error_Runtime: Variable "baz" does not exist in "index.twig" at line 3. diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/array.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/array.test new file mode 100644 index 0000000..1429d37 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/array.test @@ -0,0 +1,24 @@ +--TEST-- +array index test +--TEMPLATE-- +{% for key, value in days %} +{{ key }} +{% endfor %} +--DATA-- +return array('days' => array( + 1 => array('money' => 9), + 2 => array('money' => 21), + 3 => array('money' => 38), + 4 => array('money' => 6), + 18 => array('money' => 6), + 19 => array('money' => 3), + 31 => array('money' => 11), +)); +--EXPECT-- +1 +2 +3 +4 +18 +19 +31 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/constant.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/constant.test new file mode 100644 index 0000000..60218ac --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/constant.test @@ -0,0 +1,14 @@ +--TEST-- +"const" test +--TEMPLATE-- +{{ 8 is constant('E_NOTICE') ? 'ok' : 'no' }} +{{ 'bar' is constant('TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} +{{ value is constant('TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} +{{ 2 is constant('ARRAY_AS_PROPS', object) ? 'ok' : 'no' }} +--DATA-- +return array('value' => 'bar', 'object' => new ArrayObject(array('hi'))); +--EXPECT-- +ok +ok +ok +ok \ No newline at end of file diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined.test new file mode 100644 index 0000000..d4e204e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined.test @@ -0,0 +1,129 @@ +--TEST-- +"defined" test +--TEMPLATE-- +{{ definedVar is defined ? 'ok' : 'ko' }} +{{ definedVar is not defined ? 'ko' : 'ok' }} +{{ undefinedVar is defined ? 'ko' : 'ok' }} +{{ undefinedVar is not defined ? 'ok' : 'ko' }} +{{ zeroVar is defined ? 'ok' : 'ko' }} +{{ nullVar is defined ? 'ok' : 'ko' }} +{{ nested.definedVar is defined ? 'ok' : 'ko' }} +{{ nested['definedVar'] is defined ? 'ok' : 'ko' }} +{{ nested.definedVar is not defined ? 'ko' : 'ok' }} +{{ nested.undefinedVar is defined ? 'ko' : 'ok' }} +{{ nested['undefinedVar'] is defined ? 'ko' : 'ok' }} +{{ nested.undefinedVar is not defined ? 'ok' : 'ko' }} +{{ nested.zeroVar is defined ? 'ok' : 'ko' }} +{{ nested.nullVar is defined ? 'ok' : 'ko' }} +{{ nested.definedArray.0 is defined ? 'ok' : 'ko' }} +{{ nested['definedArray'][0] is defined ? 'ok' : 'ko' }} +{{ object.foo is defined ? 'ok' : 'ko' }} +{{ object.undefinedMethod is defined ? 'ko' : 'ok' }} +{{ object.getFoo() is defined ? 'ok' : 'ko' }} +{{ object.getFoo('a') is defined ? 'ok' : 'ko' }} +{{ object.undefinedMethod() is defined ? 'ko' : 'ok' }} +{{ object.undefinedMethod('a') is defined ? 'ko' : 'ok' }} +{{ object.self.foo is defined ? 'ok' : 'ko' }} +{{ object.self.undefinedMethod is defined ? 'ko' : 'ok' }} +{{ object.undefinedMethod.self is defined ? 'ko' : 'ok' }} +{{ 0 is defined ? 'ok' : 'ko' }} +{{ "foo" is defined ? 'ok' : 'ko' }} +{{ true is defined ? 'ok' : 'ko' }} +{{ false is defined ? 'ok' : 'ko' }} +{{ null is defined ? 'ok' : 'ko' }} +{{ [1, 2] is defined ? 'ok' : 'ko' }} +{{ { foo: "bar" } is defined ? 'ok' : 'ko' }} +--DATA-- +return array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'nullVar' => null, + 'nested' => array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'nullVar' => null, + 'definedArray' => array(0), + ), + 'object' => new TwigTestFoo(), +); +--EXPECT-- +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +--DATA-- +return array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'nullVar' => null, + 'nested' => array( + 'definedVar' => 'defined', + 'zeroVar' => 0, + 'nullVar' => null, + 'definedArray' => array(0), + ), + 'object' => new TwigTestFoo(), +); +--CONFIG-- +return array('strict_variables' => false) +--EXPECT-- +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_attribute.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_attribute.test new file mode 100644 index 0000000..4a5b8dc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_attribute.test @@ -0,0 +1,35 @@ +--TEST-- +"defined" support for attribute +--TEMPLATE-- +{{ attribute(nested, "definedVar") is defined ? 'ok' : 'ko' }} +{{ attribute(nested, "undefinedVar") is not defined ? 'ok' : 'ko' }} +{{ attribute(nested, definedVarName) is defined ? 'ok' : 'ko' }} +{{ attribute(nested, undefinedVarName) is not defined ? 'ok' : 'ko' }} +--DATA-- +return array( + 'nested' => array( + 'definedVar' => 'defined', + ), + 'definedVarName' => 'definedVar', + 'undefinedVarName' => 'undefinedVar', +); +--EXPECT-- +ok +ok +ok +ok +--DATA-- +return array( + 'nested' => array( + 'definedVar' => 'defined', + ), + 'definedVarName' => 'definedVar', + 'undefinedVarName' => 'undefinedVar', +); +--CONFIG-- +return array('strict_variables' => false) +--EXPECT-- +ok +ok +ok +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_blocks.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_blocks.test new file mode 100644 index 0000000..64d7d04 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_blocks.test @@ -0,0 +1,38 @@ +--TEST-- +"defined" support for blocks +--TEMPLATE-- +{% extends 'parent' %} +{% block icon %}icon{% endblock %} +{% block body %} + {{ parent() }} + {{ block('foo') is defined ? 'ok' : 'ko' }} + {{ block('footer') is defined ? 'ok' : 'ko' }} + {{ block('icon') is defined ? 'ok' : 'ko' }} + {{ block('block1') is defined ? 'ok' : 'ko' }} + {%- embed 'embed' %} + {% block content %}content{% endblock %} + {% endembed %} +{% endblock %} +{% use 'blocks' %} +--TEMPLATE(parent)-- +{% block body %} + {{ block('icon') is defined ? 'ok' : 'ko' -}} +{% endblock %} +{% block footer %}{% endblock %} +--TEMPLATE(embed)-- +{{ block('icon') is defined ? 'ok' : 'ko' }} +{{ block('content') is defined ? 'ok' : 'ko' }} +{{ block('block1') is defined ? 'ok' : 'ko' }} +--TEMPLATE(blocks)-- +{% block block1 %}{%endblock %} +--DATA-- +return array() +--EXPECT-- +ok + ko + ok + ok + ok +ko +ok +ko diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_blocks_with_template.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_blocks_with_template.test new file mode 100644 index 0000000..2c65165 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_blocks_with_template.test @@ -0,0 +1,17 @@ +--TEST-- +"defined" support for blocks with a template argument +--TEMPLATE-- +{{ block('foo', 'included.twig') is defined ? 'ok' : 'ko' }} +{{ block('foo', included_loaded) is defined ? 'ok' : 'ko' }} +{{ block('foo', included_loaded_internal) is defined ? 'ok' : 'ko' }} +--TEMPLATE(included.twig)-- +{% block foo %}FOO{% endblock %} +--DATA-- +return array( + 'included_loaded' => $twig->load('included.twig'), + 'included_loaded_internal' => $twig->loadTemplate('included.twig'), +) +--EXPECT-- +ok +ok +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_constants.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_constants.test new file mode 100644 index 0000000..2fa9929 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/defined_for_constants.test @@ -0,0 +1,14 @@ +--TEST-- +"defined" support for constants +--TEMPLATE-- +{{ constant('DATE_W3C') is defined ? 'ok' : 'ko' }} +{{ constant('ARRAY_AS_PROPS', object) is defined ? 'ok' : 'ko' }} +{{ constant('FOOBAR') is not defined ? 'ok' : 'ko' }} +{{ constant('FOOBAR', object) is not defined ? 'ok' : 'ko' }} +--DATA-- +return array('expect' => DATE_W3C, 'object' => new ArrayObject(array('hi'))); +--EXPECT-- +ok +ok +ok +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/dynamic_test.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/dynamic_test.test new file mode 100644 index 0000000..e50d410 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/dynamic_test.test @@ -0,0 +1,14 @@ +--TEST-- +dynamic test +--TEMPLATE-- +{{ 'bar' is test_bar ? '1' :'0' }} +{{ 'foo' is test_foo ? '1' :'0' }} +{{ 'bar' is test_foo ? '1' :'0' }} +{{ 'foo' is test_bar ? '1' :'0' }} +--DATA-- +return array() +--EXPECT-- +1 +1 +0 +0 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/empty.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/empty.test new file mode 100644 index 0000000..807c0ed --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/empty.test @@ -0,0 +1,42 @@ +--TEST-- +"empty" test +--TEMPLATE-- +{{ string_empty is empty ? 'ok' : 'ko' }} +{{ string_zero is empty ? 'ko' : 'ok' }} +{{ value_null is empty ? 'ok' : 'ko' }} +{{ value_false is empty ? 'ok' : 'ko' }} +{{ value_int_zero is empty ? 'ko' : 'ok' }} +{{ array_empty is empty ? 'ok' : 'ko' }} +{{ array_not_empty is empty ? 'ko' : 'ok' }} +{{ magically_callable is empty ? 'ko' : 'ok' }} +{{ countable_empty is empty ? 'ok' : 'ko' }} +{{ countable_not_empty is empty ? 'ko' : 'ok' }} +{{ tostring_empty is empty ? 'ok' : 'ko' }} +{{ tostring_not_empty is empty ? 'ko' : 'ok' }} +{{ markup_empty is empty ? 'ok' : 'ko' }} +{{ markup_not_empty is empty ? 'ko' : 'ok' }} +--DATA-- +return array( + 'string_empty' => '', 'string_zero' => '0', + 'value_null' => null, 'value_false' => false, 'value_int_zero' => 0, + 'array_empty' => array(), 'array_not_empty' => array(1, 2), + 'magically_callable' => new MagicCallStub(), + 'countable_empty' => new CountableStub(array()), 'countable_not_empty' => new CountableStub(array(1, 2)), + 'tostring_empty' => new ToStringStub(''), 'tostring_not_empty' => new ToStringStub('0' /* edge case of using "0" as the string */), + 'markup_empty' => new Twig_Markup('', 'UTF-8'), 'markup_not_empty' => new Twig_Markup('test', 'UTF-8'), +); +--EXPECT-- +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/even.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/even.test new file mode 100644 index 0000000..695b4c2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/even.test @@ -0,0 +1,14 @@ +--TEST-- +"even" test +--TEMPLATE-- +{{ 1 is even ? 'ko' : 'ok' }} +{{ 2 is even ? 'ok' : 'ko' }} +{{ 1 is not even ? 'ok' : 'ko' }} +{{ 2 is not even ? 'ko' : 'ok' }} +--DATA-- +return array() +--EXPECT-- +ok +ok +ok +ok diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/in.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/in.test new file mode 100644 index 0000000..545f51f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/in.test @@ -0,0 +1,128 @@ +--TEST-- +Twig supports the in operator +--TEMPLATE-- +{% if bar in foo %} +TRUE +{% endif %} +{% if not (bar in foo) %} +{% else %} +TRUE +{% endif %} +{% if bar not in foo %} +{% else %} +TRUE +{% endif %} +{% if 'a' in bar %} +TRUE +{% endif %} +{% if 'c' not in bar %} +TRUE +{% endif %} +{% if '' in bar %} +TRUE +{% endif %} +{% if '' in '' %} +TRUE +{% endif %} +{% if '0' not in '' %} +TRUE +{% endif %} +{% if 'a' not in '0' %} +TRUE +{% endif %} +{% if '0' in '0' %} +TRUE +{% endif %} + +{{ false in [0, 1] ? 'TRUE' : 'FALSE' }} +{{ true in [0, 1] ? 'TRUE' : 'FALSE' }} +{{ '0' in [0, 1] ? 'TRUE' : 'FALSE' }} +{{ '' in [0, 1] ? 'TRUE' : 'FALSE' }} +{{ 0 in ['', 1] ? 'TRUE' : 'FALSE' }} + +{{ '' in 'foo' ? 'TRUE' : 'FALSE' }} +{{ 0 in 'foo' ? 'TRUE' : 'FALSE' }} +{{ false in 'foo' ? 'TRUE' : 'FALSE' }} +{{ false in '100' ? 'TRUE' : 'FALSE' }} +{{ true in '100' ? 'TRUE' : 'FALSE' }} + +{{ [] in [true, false] ? 'TRUE' : 'FALSE' }} +{{ [] in [true, ''] ? 'TRUE' : 'FALSE' }} +{{ [] in [true, []] ? 'TRUE' : 'FALSE' }} + +{{ resource ? 'TRUE' : 'FALSE' }} +{{ resource in 'foo'~resource ? 'TRUE' : 'FALSE' }} +{{ object in 'stdClass' ? 'TRUE' : 'FALSE' }} +{{ [] in 'Array' ? 'TRUE' : 'FALSE' }} +{{ dir_object in 'foo'~dir_object ? 'TRUE' : 'FALSE' }} + +{{ ''~resource in resource ? 'TRUE' : 'FALSE' }} +{{ 'stdClass' in object ? 'TRUE' : 'FALSE' }} +{{ 'Array' in [] ? 'TRUE' : 'FALSE' }} +{{ ''~dir_object in dir_object ? 'TRUE' : 'FALSE' }} + +{{ resource in [''~resource] ? 'TRUE' : 'FALSE' }} +{{ resource in [resource + 1 - 1] ? 'TRUE' : 'FALSE' }} +{{ dir_object in [''~dir_object] ? 'TRUE' : 'FALSE' }} + +{{ 5 in 125 ? 'TRUE' : 'FALSE' }} +{{ 5 in '125' ? 'TRUE' : 'FALSE' }} +{{ '5' in 125 ? 'TRUE' : 'FALSE' }} +{{ '5' in '125' ? 'TRUE' : 'FALSE' }} + +{{ 5.5 in 125.5 ? 'TRUE' : 'FALSE' }} +{{ 5.5 in '125.5' ? 'TRUE' : 'FALSE' }} +{{ '5.5' in 125.5 ? 'TRUE' : 'FALSE' }} +--DATA-- +return array('bar' => 'bar', 'foo' => array('bar' => 'bar'), 'dir_object' => new SplFileInfo(dirname(__FILE__)), 'object' => new stdClass(), 'resource' => opendir(dirname(__FILE__))) +--EXPECT-- +TRUE +TRUE +TRUE +TRUE +TRUE +TRUE +TRUE +TRUE +TRUE +TRUE + +TRUE +TRUE +TRUE +TRUE +TRUE + +TRUE +FALSE +FALSE +FALSE +FALSE + +TRUE +FALSE +TRUE + +TRUE +FALSE +FALSE +FALSE +FALSE + +FALSE +FALSE +FALSE +FALSE + +FALSE +FALSE +FALSE + +FALSE +TRUE +FALSE +TRUE + +FALSE +TRUE +FALSE diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/in_with_objects.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/in_with_objects.test new file mode 100644 index 0000000..8e08061 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/in_with_objects.test @@ -0,0 +1,19 @@ +--TEST-- +Twig supports the in operator when using objects +--TEMPLATE-- +{% if object in object_list %} +TRUE +{% endif %} +--DATA-- +$foo = new TwigTestFoo(); +$foo1 = new TwigTestFoo(); + +$foo->position = $foo1; +$foo1->position = $foo; + +return array( + 'object' => $foo, + 'object_list' => array($foo1, $foo), +); +--EXPECT-- +TRUE diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/iterable.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/iterable.test new file mode 100644 index 0000000..ec52550 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/iterable.test @@ -0,0 +1,19 @@ +--TEST-- +"iterable" test +--TEMPLATE-- +{{ foo is iterable ? 'ok' : 'ko' }} +{{ traversable is iterable ? 'ok' : 'ko' }} +{{ obj is iterable ? 'ok' : 'ko' }} +{{ val is iterable ? 'ok' : 'ko' }} +--DATA-- +return array( + 'foo' => array(), + 'traversable' => new ArrayIterator(array()), + 'obj' => new stdClass(), + 'val' => 'test', +); +--EXPECT-- +ok +ok +ko +ko \ No newline at end of file diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/null_coalesce.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/null_coalesce.test new file mode 100644 index 0000000..3d148c8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/null_coalesce.test @@ -0,0 +1,30 @@ +--TEST-- +Twig supports the ?? operator +--TEMPLATE-- +{{ 'OK' ?? 'KO' }} +{{ null ?? 'OK' }} +{{ bar ?? 'KO' }} +{{ baz ?? 'OK' }} +{{ foo.bar ?? 'KO' }} +{{ foo.missing ?? 'OK' }} +{{ foo.bar.baz.missing ?? 'OK' }} +{{ foo['bar'] ?? 'KO' }} +{{ foo['missing'] ?? 'OK' }} +{{ nope ?? nada ?? 'OK' }} +{{ 1 + nope ?? nada ?? 2 }} +{{ 1 + nope ?? 3 + nada ?? 2 }} +--DATA-- +return array('bar' => 'OK', 'foo' => array('bar' => 'OK')) +--EXPECT-- +OK +OK +OK +OK +OK +OK +OK +OK +OK +OK +3 +6 diff --git a/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/odd.test b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/odd.test new file mode 100644 index 0000000..1b8311e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Fixtures/tests/odd.test @@ -0,0 +1,10 @@ +--TEST-- +"odd" test +--TEMPLATE-- +{{ 1 is odd ? 'ok' : 'ko' }} +{{ 2 is odd ? 'ko' : 'ok' }} +--DATA-- +return array() +--EXPECT-- +ok +ok \ No newline at end of file diff --git a/vendor/twig/twig/test/Twig/Tests/IntegrationTest.php b/vendor/twig/twig/test/Twig/Tests/IntegrationTest.php new file mode 100644 index 0000000..a07c8ac --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/IntegrationTest.php @@ -0,0 +1,333 @@ +position = 0; + } + + public function current() + { + return $this->array[$this->position]; + } + + public function key() + { + return 'a'; + } + + public function next() + { + ++$this->position; + } + + public function valid() + { + return isset($this->array[$this->position]); + } +} + +class TwigTestTokenParser_§ extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node_Print(new Twig_Node_Expression_Constant('§', -1), -1); + } + + public function getTag() + { + return '§'; + } +} + +class TwigTestExtension extends Twig_Extension +{ + public function getTokenParsers() + { + return array( + new TwigTestTokenParser_§(), + ); + } + + public function getFilters() + { + return array( + new Twig_SimpleFilter('§', array($this, '§Filter')), + new Twig_SimpleFilter('escape_and_nl2br', array($this, 'escape_and_nl2br'), array('needs_environment' => true, 'is_safe' => array('html'))), + new Twig_SimpleFilter('nl2br', array($this, 'nl2br'), array('pre_escape' => 'html', 'is_safe' => array('html'))), + new Twig_SimpleFilter('escape_something', array($this, 'escape_something'), array('is_safe' => array('something'))), + new Twig_SimpleFilter('preserves_safety', array($this, 'preserves_safety'), array('preserves_safety' => array('html'))), + new Twig_SimpleFilter('static_call_string', 'TwigTestExtension::staticCall'), + new Twig_SimpleFilter('static_call_array', array('TwigTestExtension', 'staticCall')), + new Twig_SimpleFilter('magic_call', array($this, 'magicCall')), + new Twig_SimpleFilter('magic_call_string', 'TwigTestExtension::magicStaticCall'), + new Twig_SimpleFilter('magic_call_array', array('TwigTestExtension', 'magicStaticCall')), + new Twig_SimpleFilter('*_path', array($this, 'dynamic_path')), + new Twig_SimpleFilter('*_foo_*_bar', array($this, 'dynamic_foo')), + ); + } + + public function getFunctions() + { + return array( + new Twig_SimpleFunction('§', array($this, '§Function')), + new Twig_SimpleFunction('safe_br', array($this, 'br'), array('is_safe' => array('html'))), + new Twig_SimpleFunction('unsafe_br', array($this, 'br')), + new Twig_SimpleFunction('static_call_string', 'TwigTestExtension::staticCall'), + new Twig_SimpleFunction('static_call_array', array('TwigTestExtension', 'staticCall')), + new Twig_SimpleFunction('*_path', array($this, 'dynamic_path')), + new Twig_SimpleFunction('*_foo_*_bar', array($this, 'dynamic_foo')), + ); + } + + public function getTests() + { + return array( + new Twig_SimpleTest('multi word', array($this, 'is_multi_word')), + new Twig_SimpleTest('test_*', array($this, 'dynamic_test')), + ); + } + + public function §Filter($value) + { + return "§{$value}§"; + } + + public function §Function($value) + { + return "§{$value}§"; + } + + /** + * nl2br which also escapes, for testing escaper filters. + */ + public function escape_and_nl2br($env, $value, $sep = '
    ') + { + return $this->nl2br(twig_escape_filter($env, $value, 'html'), $sep); + } + + /** + * nl2br only, for testing filters with pre_escape. + */ + public function nl2br($value, $sep = '
    ') + { + // not secure if $value contains html tags (not only entities) + // don't use + return str_replace("\n", "$sep\n", $value); + } + + public function dynamic_path($element, $item) + { + return $element.'/'.$item; + } + + public function dynamic_foo($foo, $bar, $item) + { + return $foo.'/'.$bar.'/'.$item; + } + + public function dynamic_test($element, $item) + { + return $element === $item; + } + + public function escape_something($value) + { + return strtoupper($value); + } + + public function preserves_safety($value) + { + return strtoupper($value); + } + + public static function staticCall($value) + { + return "*$value*"; + } + + public function br() + { + return '
    '; + } + + public function is_multi_word($value) + { + return false !== strpos($value, ' '); + } + + public function __call($method, $arguments) + { + if ('magicCall' !== $method) { + throw new BadMethodCallException('Unexpected call to __call'); + } + + return 'magic_'.$arguments[0]; + } + + public static function __callStatic($method, $arguments) + { + if ('magicStaticCall' !== $method) { + throw new BadMethodCallException('Unexpected call to __callStatic'); + } + + return 'static_magic_'.$arguments[0]; + } +} + +/** + * This class is used in tests for the "length" filter and "empty" test. It asserts that __call is not + * used to convert such objects to strings. + */ +class MagicCallStub +{ + public function __call($name, $args) + { + throw new Exception('__call shall not be called'); + } +} + +class ToStringStub +{ + /** + * @var string + */ + private $string; + + public function __construct($string) + { + $this->string = $string; + } + + public function __toString() + { + return $this->string; + } +} + +/** + * This class is used in tests for the length filter and empty test to show + * that when \Countable is implemented, it is preferred over the __toString() + * method. + */ +class CountableStub implements \Countable +{ + private $count; + + public function __construct($count) + { + $this->count = $count; + } + + public function count() + { + return $this->count; + } + + public function __toString() + { + throw new Exception('__toString shall not be called on \Countables'); + } +} + +/** + * This class is used in tests for the length filter. + */ +class IteratorAggregateStub implements \IteratorAggregate +{ + private $data; + + public function __construct(array $data) + { + $this->data = $data; + } + + public function getIterator() + { + return new ArrayIterator($this->data); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/autoescape/filename.legacy.test b/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/autoescape/filename.legacy.test new file mode 100644 index 0000000..b091ad3 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/autoescape/filename.legacy.test @@ -0,0 +1,18 @@ +--TEST-- +"filename" autoescape strategy +--TEMPLATE-- +{{ br -}} +{{ include('index.html.twig') -}} +{{ include('index.txt.twig') -}} +--TEMPLATE(index.html.twig)-- +{{ br -}} +--TEMPLATE(index.txt.twig)-- +{{ br -}} +--DATA-- +return array('br' => '
    ') +--CONFIG-- +return array('autoescape' => 'filename') +--EXPECT-- +<br /> +<br /> +
    diff --git a/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/functions/undefined_block.legacy.test b/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/functions/undefined_block.legacy.test new file mode 100644 index 0000000..62e24f0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/functions/undefined_block.legacy.test @@ -0,0 +1,12 @@ +--TEST-- +"block" function with undefined block +--TEMPLATE-- +{% extends "base.twig" %} +{% block foo %}{{ parent() }}{{ block('unknown') }}{{ block('bar') }}{% endblock %} +--TEMPLATE(base.twig)-- +{% block foo %}Foo{% endblock %} +{% block bar %}Bar{% endblock %} +--DATA-- +return array() +--EXPECT-- +FooBarBar diff --git a/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/test.legacy.test b/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/test.legacy.test new file mode 100644 index 0000000..d9c1d50 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/LegacyFixtures/test.legacy.test @@ -0,0 +1,8 @@ +--TEST-- +Old test classes usage +--TEMPLATE-- +{{ 'foo' is multi word ? 'yes' : 'no' }} +--DATA-- +return array() +--EXPECT-- +no diff --git a/vendor/twig/twig/test/Twig/Tests/LegacyIntegrationTest.php b/vendor/twig/twig/test/Twig/Tests/LegacyIntegrationTest.php new file mode 100644 index 0000000..2ed7580 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/LegacyIntegrationTest.php @@ -0,0 +1,54 @@ + new Twig_Test_Method($this, 'is_multi_word'), + ); + } + + public function is_multi_word($value) + { + return false !== strpos($value, ' '); + } + + public function getName() + { + return 'legacy_integration_test'; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/LexerTest.php b/vendor/twig/twig/test/Twig/Tests/LexerTest.php new file mode 100644 index 0000000..ffe9a23 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/LexerTest.php @@ -0,0 +1,347 @@ +getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize('{{ foo }}', 'foo'); + $this->assertEquals('foo', $stream->getFilename()); + $this->assertEquals('{{ foo }}', $stream->getSource()); + } + + public function testNameLabelForTag() + { + $template = '{% § %}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + + $stream->expect(Twig_Token::BLOCK_START_TYPE); + $this->assertSame('§', $stream->expect(Twig_Token::NAME_TYPE)->getValue()); + } + + public function testNameLabelForFunction() + { + $template = '{{ §() }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + + $stream->expect(Twig_Token::VAR_START_TYPE); + $this->assertSame('§', $stream->expect(Twig_Token::NAME_TYPE)->getValue()); + } + + public function testBracketsNesting() + { + $template = '{{ {"a":{"b":"c"}} }}'; + + $this->assertEquals(2, $this->countToken($template, Twig_Token::PUNCTUATION_TYPE, '{')); + $this->assertEquals(2, $this->countToken($template, Twig_Token::PUNCTUATION_TYPE, '}')); + } + + protected function countToken($template, $type, $value = null) + { + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + + $count = 0; + while (!$stream->isEOF()) { + $token = $stream->next(); + if ($type === $token->getType()) { + if (null === $value || $value === $token->getValue()) { + ++$count; + } + } + } + + return $count; + } + + public function testLineDirective() + { + $template = "foo\n" + ."bar\n" + ."{% line 10 %}\n" + ."{{\n" + ."baz\n" + ."}}\n"; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + + // foo\nbar\n + $this->assertSame(1, $stream->expect(Twig_Token::TEXT_TYPE)->getLine()); + // \n (after {% line %}) + $this->assertSame(10, $stream->expect(Twig_Token::TEXT_TYPE)->getLine()); + // {{ + $this->assertSame(11, $stream->expect(Twig_Token::VAR_START_TYPE)->getLine()); + // baz + $this->assertSame(12, $stream->expect(Twig_Token::NAME_TYPE)->getLine()); + } + + public function testLineDirectiveInline() + { + $template = "foo\n" + ."bar{% line 10 %}{{\n" + ."baz\n" + ."}}\n"; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + + // foo\nbar + $this->assertSame(1, $stream->expect(Twig_Token::TEXT_TYPE)->getLine()); + // {{ + $this->assertSame(10, $stream->expect(Twig_Token::VAR_START_TYPE)->getLine()); + // baz + $this->assertSame(11, $stream->expect(Twig_Token::NAME_TYPE)->getLine()); + } + + public function testLongComments() + { + $template = '{# '.str_repeat('*', 100000).' #}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $lexer->tokenize(new Twig_Source($template, 'index')); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testLongVerbatim() + { + $template = '{% verbatim %}'.str_repeat('*', 100000).'{% endverbatim %}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $lexer->tokenize(new Twig_Source($template, 'index')); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testLongVar() + { + $template = '{{ '.str_repeat('x', 100000).' }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $lexer->tokenize(new Twig_Source($template, 'index')); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testLongBlock() + { + $template = '{% '.str_repeat('x', 100000).' %}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $lexer->tokenize(new Twig_Source($template, 'index')); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testBigNumbers() + { + $template = '{{ 922337203685477580700 }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->next(); + $node = $stream->next(); + $this->assertEquals('922337203685477580700', $node->getValue()); + } + + public function testStringWithEscapedDelimiter() + { + $tests = array( + "{{ 'foo \' bar' }}" => 'foo \' bar', + '{{ "foo \" bar" }}' => 'foo " bar', + ); + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + foreach ($tests as $template => $expected) { + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->expect(Twig_Token::VAR_START_TYPE); + $stream->expect(Twig_Token::STRING_TYPE, $expected); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + } + + public function testStringWithInterpolation() + { + $template = 'foo {{ "bar #{ baz + 1 }" }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->expect(Twig_Token::TEXT_TYPE, 'foo '); + $stream->expect(Twig_Token::VAR_START_TYPE); + $stream->expect(Twig_Token::STRING_TYPE, 'bar '); + $stream->expect(Twig_Token::INTERPOLATION_START_TYPE); + $stream->expect(Twig_Token::NAME_TYPE, 'baz'); + $stream->expect(Twig_Token::OPERATOR_TYPE, '+'); + $stream->expect(Twig_Token::NUMBER_TYPE, '1'); + $stream->expect(Twig_Token::INTERPOLATION_END_TYPE); + $stream->expect(Twig_Token::VAR_END_TYPE); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testStringWithEscapedInterpolation() + { + $template = '{{ "bar \#{baz+1}" }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->expect(Twig_Token::VAR_START_TYPE); + $stream->expect(Twig_Token::STRING_TYPE, 'bar #{baz+1}'); + $stream->expect(Twig_Token::VAR_END_TYPE); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testStringWithHash() + { + $template = '{{ "bar # baz" }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->expect(Twig_Token::VAR_START_TYPE); + $stream->expect(Twig_Token::STRING_TYPE, 'bar # baz'); + $stream->expect(Twig_Token::VAR_END_TYPE); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unclosed """ + */ + public function testStringWithUnterminatedInterpolation() + { + $template = '{{ "bar #{x" }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $lexer->tokenize(new Twig_Source($template, 'index')); + } + + public function testStringWithNestedInterpolations() + { + $template = '{{ "bar #{ "foo#{bar}" }" }}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->expect(Twig_Token::VAR_START_TYPE); + $stream->expect(Twig_Token::STRING_TYPE, 'bar '); + $stream->expect(Twig_Token::INTERPOLATION_START_TYPE); + $stream->expect(Twig_Token::STRING_TYPE, 'foo'); + $stream->expect(Twig_Token::INTERPOLATION_START_TYPE); + $stream->expect(Twig_Token::NAME_TYPE, 'bar'); + $stream->expect(Twig_Token::INTERPOLATION_END_TYPE); + $stream->expect(Twig_Token::INTERPOLATION_END_TYPE); + $stream->expect(Twig_Token::VAR_END_TYPE); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testStringWithNestedInterpolationsInBlock() + { + $template = '{% foo "bar #{ "foo#{bar}" }" %}'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->expect(Twig_Token::BLOCK_START_TYPE); + $stream->expect(Twig_Token::NAME_TYPE, 'foo'); + $stream->expect(Twig_Token::STRING_TYPE, 'bar '); + $stream->expect(Twig_Token::INTERPOLATION_START_TYPE); + $stream->expect(Twig_Token::STRING_TYPE, 'foo'); + $stream->expect(Twig_Token::INTERPOLATION_START_TYPE); + $stream->expect(Twig_Token::NAME_TYPE, 'bar'); + $stream->expect(Twig_Token::INTERPOLATION_END_TYPE); + $stream->expect(Twig_Token::INTERPOLATION_END_TYPE); + $stream->expect(Twig_Token::BLOCK_END_TYPE); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + public function testOperatorEndingWithALetterAtTheEndOfALine() + { + $template = "{{ 1 and\n0}}"; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $stream = $lexer->tokenize(new Twig_Source($template, 'index')); + $stream->expect(Twig_Token::VAR_START_TYPE); + $stream->expect(Twig_Token::NUMBER_TYPE, 1); + $stream->expect(Twig_Token::OPERATOR_TYPE, 'and'); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without throwing any exceptions + $this->addToAssertionCount(1); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unclosed "variable" in "index" at line 3 + */ + public function testUnterminatedVariable() + { + $template = ' + +{{ + +bar + + +'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $lexer->tokenize(new Twig_Source($template, 'index')); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unclosed "block" in "index" at line 3 + */ + public function testUnterminatedBlock() + { + $template = ' + +{% + +bar + + +'; + + $lexer = new Twig_Lexer(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $lexer->tokenize(new Twig_Source($template, 'index')); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/ArrayTest.php b/vendor/twig/twig/test/Twig/Tests/Loader/ArrayTest.php new file mode 100644 index 0000000..5930639 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/ArrayTest.php @@ -0,0 +1,137 @@ + 'bar')); + + $this->assertEquals('bar', $loader->getSource('foo')); + } + + /** + * @group legacy + * @expectedException Twig_Error_Loader + */ + public function testGetSourceWhenTemplateDoesNotExist() + { + $loader = new Twig_Loader_Array(array()); + + $loader->getSource('foo'); + } + + /** + * @expectedException Twig_Error_Loader + */ + public function testGetSourceContextWhenTemplateDoesNotExist() + { + $loader = new Twig_Loader_Array(array()); + + $loader->getSourceContext('foo'); + } + + public function testGetCacheKey() + { + $loader = new Twig_Loader_Array(array('foo' => 'bar')); + + $this->assertEquals('foo:bar', $loader->getCacheKey('foo')); + } + + public function testGetCacheKeyWhenTemplateHasDuplicateContent() + { + $loader = new Twig_Loader_Array(array( + 'foo' => 'bar', + 'baz' => 'bar', + )); + + $this->assertEquals('foo:bar', $loader->getCacheKey('foo')); + $this->assertEquals('baz:bar', $loader->getCacheKey('baz')); + } + + public function testGetCacheKeyIsProtectedFromEdgeCollisions() + { + $loader = new Twig_Loader_Array(array( + 'foo__' => 'bar', + 'foo' => '__bar', + )); + + $this->assertEquals('foo__:bar', $loader->getCacheKey('foo__')); + $this->assertEquals('foo:__bar', $loader->getCacheKey('foo')); + } + + /** + * @expectedException Twig_Error_Loader + */ + public function testGetCacheKeyWhenTemplateDoesNotExist() + { + $loader = new Twig_Loader_Array(array()); + + $loader->getCacheKey('foo'); + } + + public function testSetTemplate() + { + $loader = new Twig_Loader_Array(array()); + $loader->setTemplate('foo', 'bar'); + + $this->assertEquals('bar', $loader->getSourceContext('foo')->getCode()); + } + + public function testIsFresh() + { + $loader = new Twig_Loader_Array(array('foo' => 'bar')); + $this->assertTrue($loader->isFresh('foo', time())); + } + + /** + * @expectedException Twig_Error_Loader + */ + public function testIsFreshWhenTemplateDoesNotExist() + { + $loader = new Twig_Loader_Array(array()); + + $loader->isFresh('foo', time()); + } + + public function testTemplateReference() + { + $name = new Twig_Test_Loader_TemplateReference('foo'); + $loader = new Twig_Loader_Array(array('foo' => 'bar')); + + $loader->getCacheKey($name); + $loader->getSourceContext($name); + $loader->isFresh($name, time()); + $loader->setTemplate($name, 'foo:bar'); + + // add a dummy assertion here to satisfy PHPUnit, the only thing we want to test is that the code above + // can be executed without crashing PHP + $this->addToAssertionCount(1); + } +} + +class Twig_Test_Loader_TemplateReference +{ + private $name; + + public function __construct($name) + { + $this->name = $name; + } + + public function __toString() + { + return $this->name; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/ChainTest.php b/vendor/twig/twig/test/Twig/Tests/Loader/ChainTest.php new file mode 100644 index 0000000..8a8a84a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/ChainTest.php @@ -0,0 +1,124 @@ + 'bar')), + new Twig_Loader_Array(array('foo' => 'foobar', 'bar' => 'foo')), + )); + + $this->assertEquals('bar', $loader->getSource('foo')); + $this->assertEquals('foo', $loader->getSource('bar')); + } + + public function testGetSourceContext() + { + $path = dirname(__FILE__).'/../Fixtures'; + $loader = new Twig_Loader_Chain(array( + new Twig_Loader_Array(array('foo' => 'bar')), + new Twig_Loader_Array(array('errors/index.html' => 'baz')), + new Twig_Loader_Filesystem(array($path)), + )); + + $this->assertEquals('foo', $loader->getSourceContext('foo')->getName()); + $this->assertSame('', $loader->getSourceContext('foo')->getPath()); + + $this->assertEquals('errors/index.html', $loader->getSourceContext('errors/index.html')->getName()); + $this->assertSame('', $loader->getSourceContext('errors/index.html')->getPath()); + $this->assertEquals('baz', $loader->getSourceContext('errors/index.html')->getCode()); + + $this->assertEquals('errors/base.html', $loader->getSourceContext('errors/base.html')->getName()); + $this->assertEquals(realpath($path.'/errors/base.html'), realpath($loader->getSourceContext('errors/base.html')->getPath())); + $this->assertNotEquals('baz', $loader->getSourceContext('errors/base.html')->getCode()); + } + + /** + * @expectedException Twig_Error_Loader + */ + public function testGetSourceContextWhenTemplateDoesNotExist() + { + $loader = new Twig_Loader_Chain(array()); + + $loader->getSourceContext('foo'); + } + + /** + * @group legacy + * @expectedException Twig_Error_Loader + */ + public function testGetSourceWhenTemplateDoesNotExist() + { + $loader = new Twig_Loader_Chain(array()); + + $loader->getSource('foo'); + } + + public function testGetCacheKey() + { + $loader = new Twig_Loader_Chain(array( + new Twig_Loader_Array(array('foo' => 'bar')), + new Twig_Loader_Array(array('foo' => 'foobar', 'bar' => 'foo')), + )); + + $this->assertEquals('foo:bar', $loader->getCacheKey('foo')); + $this->assertEquals('bar:foo', $loader->getCacheKey('bar')); + } + + /** + * @expectedException Twig_Error_Loader + */ + public function testGetCacheKeyWhenTemplateDoesNotExist() + { + $loader = new Twig_Loader_Chain(array()); + + $loader->getCacheKey('foo'); + } + + public function testAddLoader() + { + $loader = new Twig_Loader_Chain(); + $loader->addLoader(new Twig_Loader_Array(array('foo' => 'bar'))); + + $this->assertEquals('bar', $loader->getSourceContext('foo')->getCode()); + } + + public function testExists() + { + $loader1 = $this->getMockBuilder('Twig_ChainTestLoaderWithExistsInterface')->getMock(); + $loader1->expects($this->once())->method('exists')->will($this->returnValue(false)); + $loader1->expects($this->never())->method('getSourceContext'); + + // can be removed in 2.0 + $loader2 = $this->getMockBuilder('Twig_ChainTestLoaderInterface')->getMock(); + //$loader2 = $this->getMockBuilder(array('Twig_LoaderInterface', 'Twig_SourceContextLoaderInterface'))->getMock(); + $loader2->expects($this->once())->method('getSourceContext')->will($this->returnValue(new Twig_Source('content', 'index'))); + + $loader = new Twig_Loader_Chain(); + $loader->addLoader($loader1); + $loader->addLoader($loader2); + + $this->assertTrue($loader->exists('foo')); + } +} + +interface Twig_ChainTestLoaderInterface extends Twig_LoaderInterface, Twig_SourceContextLoaderInterface +{ +} + +interface Twig_ChainTestLoaderWithExistsInterface extends Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface +{ +} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/FilesystemTest.php b/vendor/twig/twig/test/Twig/Tests/Loader/FilesystemTest.php new file mode 100644 index 0000000..3200fd6 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/FilesystemTest.php @@ -0,0 +1,241 @@ +assertEquals('errors/index.html', $loader->getSourceContext('errors/index.html')->getName()); + $this->assertEquals(realpath($path.'/errors/index.html'), realpath($loader->getSourceContext('errors/index.html')->getPath())); + } + + /** + * @dataProvider getSecurityTests + */ + public function testSecurity($template) + { + $loader = new Twig_Loader_Filesystem(array(dirname(__FILE__).'/../Fixtures')); + + try { + $loader->getCacheKey($template); + $this->fail(); + } catch (Twig_Error_Loader $e) { + $this->assertNotContains('Unable to find template', $e->getMessage()); + } + } + + public function getSecurityTests() + { + return array( + array("AutoloaderTest\0.php"), + array('..\\AutoloaderTest.php'), + array('..\\\\\\AutoloaderTest.php'), + array('../AutoloaderTest.php'), + array('..////AutoloaderTest.php'), + array('./../AutoloaderTest.php'), + array('.\\..\\AutoloaderTest.php'), + array('././././././../AutoloaderTest.php'), + array('.\\./.\\./.\\./../AutoloaderTest.php'), + array('foo/../../AutoloaderTest.php'), + array('foo\\..\\..\\AutoloaderTest.php'), + array('foo/../bar/../../AutoloaderTest.php'), + array('foo/bar/../../../AutoloaderTest.php'), + array('filters/../../AutoloaderTest.php'), + array('filters//..//..//AutoloaderTest.php'), + array('filters\\..\\..\\AutoloaderTest.php'), + array('filters\\\\..\\\\..\\\\AutoloaderTest.php'), + array('filters\\//../\\/\\..\\AutoloaderTest.php'), + array('/../AutoloaderTest.php'), + ); + } + + /** + * @dataProvider getBasePaths + */ + public function testPaths($basePath, $cacheKey, $rootPath) + { + $loader = new Twig_Loader_Filesystem(array($basePath.'/normal', $basePath.'/normal_bis'), $rootPath); + $loader->setPaths(array($basePath.'/named', $basePath.'/named_bis'), 'named'); + $loader->addPath($basePath.'/named_ter', 'named'); + $loader->addPath($basePath.'/normal_ter'); + $loader->prependPath($basePath.'/normal_final'); + $loader->prependPath($basePath.'/named/../named_quater', 'named'); + $loader->prependPath($basePath.'/named_final', 'named'); + + $this->assertEquals(array( + $basePath.'/normal_final', + $basePath.'/normal', + $basePath.'/normal_bis', + $basePath.'/normal_ter', + ), $loader->getPaths()); + $this->assertEquals(array( + $basePath.'/named_final', + $basePath.'/named/../named_quater', + $basePath.'/named', + $basePath.'/named_bis', + $basePath.'/named_ter', + ), $loader->getPaths('named')); + + // do not use realpath here as it would make the test unuseful + $this->assertEquals($cacheKey, str_replace('\\', '/', $loader->getCacheKey('@named/named_absolute.html'))); + $this->assertEquals("path (final)\n", $loader->getSourceContext('index.html')->getCode()); + $this->assertEquals("path (final)\n", $loader->getSourceContext('@__main__/index.html')->getCode()); + $this->assertEquals("named path (final)\n", $loader->getSourceContext('@named/index.html')->getCode()); + } + + public function getBasePaths() + { + return array( + array( + dirname(__FILE__).'/Fixtures', + 'test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html', + null, + ), + array( + dirname(__FILE__).'/Fixtures/../Fixtures', + 'test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html', + null, + ), + array( + 'test/Twig/Tests/Loader/Fixtures', + 'test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html', + getcwd(), + ), + array( + 'Fixtures', + 'Fixtures/named_quater/named_absolute.html', + getcwd().'/test/Twig/Tests/Loader', + ), + array( + 'Fixtures', + 'Fixtures/named_quater/named_absolute.html', + getcwd().'/test/../test/Twig/Tests/Loader', + ), + ); + } + + public function testEmptyConstructor() + { + $loader = new Twig_Loader_Filesystem(); + $this->assertEquals(array(), $loader->getPaths()); + } + + public function testGetNamespaces() + { + $loader = new Twig_Loader_Filesystem(sys_get_temp_dir()); + $this->assertEquals(array(Twig_Loader_Filesystem::MAIN_NAMESPACE), $loader->getNamespaces()); + + $loader->addPath(sys_get_temp_dir(), 'named'); + $this->assertEquals(array(Twig_Loader_Filesystem::MAIN_NAMESPACE, 'named'), $loader->getNamespaces()); + } + + public function testFindTemplateExceptionNamespace() + { + $basePath = dirname(__FILE__).'/Fixtures'; + + $loader = new Twig_Loader_Filesystem(array($basePath.'/normal')); + $loader->addPath($basePath.'/named', 'named'); + + try { + $loader->getSourceContext('@named/nowhere.html'); + } catch (Exception $e) { + $this->assertInstanceof('Twig_Error_Loader', $e); + $this->assertContains('Unable to find template "@named/nowhere.html"', $e->getMessage()); + } + } + + public function testFindTemplateWithCache() + { + $basePath = dirname(__FILE__).'/Fixtures'; + + $loader = new Twig_Loader_Filesystem(array($basePath.'/normal')); + $loader->addPath($basePath.'/named', 'named'); + + // prime the cache for index.html in the named namespace + $namedSource = $loader->getSourceContext('@named/index.html')->getCode(); + $this->assertEquals("named path\n", $namedSource); + + // get index.html from the main namespace + $this->assertEquals("path\n", $loader->getSourceContext('index.html')->getCode()); + } + + public function testLoadTemplateAndRenderBlockWithCache() + { + $loader = new Twig_Loader_Filesystem(array()); + $loader->addPath(dirname(__FILE__).'/Fixtures/themes/theme2'); + $loader->addPath(dirname(__FILE__).'/Fixtures/themes/theme1'); + $loader->addPath(dirname(__FILE__).'/Fixtures/themes/theme1', 'default_theme'); + + $twig = new Twig_Environment($loader); + + $template = $twig->loadTemplate('blocks.html.twig'); + $this->assertSame('block from theme 1', $template->renderBlock('b1', array())); + + $template = $twig->loadTemplate('blocks.html.twig'); + $this->assertSame('block from theme 2', $template->renderBlock('b2', array())); + } + + public function getArrayInheritanceTests() + { + return array( + 'valid array inheritance' => array('array_inheritance_valid_parent.html.twig'), + 'array inheritance with null first template' => array('array_inheritance_null_parent.html.twig'), + 'array inheritance with empty first template' => array('array_inheritance_empty_parent.html.twig'), + 'array inheritance with non-existent first template' => array('array_inheritance_nonexistent_parent.html.twig'), + ); + } + + /** + * @dataProvider getArrayInheritanceTests + * + * @param $templateName string Template name with array inheritance + */ + public function testArrayInheritance($templateName) + { + $loader = new Twig_Loader_Filesystem(array()); + $loader->addPath(dirname(__FILE__).'/Fixtures/inheritance'); + + $twig = new Twig_Environment($loader); + + $template = $twig->loadTemplate($templateName); + $this->assertSame('VALID Child', $template->renderBlock('body', array())); + } + + /** + * @requires PHP 5.3 + */ + public function testLoadTemplateFromPhar() + { + $loader = new Twig_Loader_Filesystem(array()); + // phar-sample.phar was created with the following script: + // $f = new Phar('phar-test.phar'); + // $f->addFromString('hello.twig', 'hello from phar'); + $loader->addPath('phar://'.dirname(__FILE__).'/Fixtures/phar/phar-sample.phar'); + $this->assertSame('hello from phar', $loader->getSourceContext('hello.twig')->getCode()); + } + + public function testTemplateExistsAlwaysReturnsBool() + { + $loader = new Twig_Loader_Filesystem(array()); + $this->assertFalse($loader->exists("foo\0.twig")); + $this->assertFalse($loader->exists('../foo.twig')); + $this->assertFalse($loader->exists('@foo')); + $this->assertFalse($loader->exists('foo')); + $this->assertFalse($loader->exists('@foo/bar.twig')); + + $loader->addPath(__DIR__.'/Fixtures/normal'); + $this->assertTrue($loader->exists('index.html')); + $loader->addPath(__DIR__.'/Fixtures/normal', 'foo'); + $this->assertTrue($loader->exists('@foo/index.html')); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_empty_parent.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_empty_parent.html.twig new file mode 100644 index 0000000..6977ebf --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_empty_parent.html.twig @@ -0,0 +1,3 @@ +{% extends ['','parent.html.twig'] %} + +{% block body %}{{ parent() }} Child{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_nonexistent_parent.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_nonexistent_parent.html.twig new file mode 100644 index 0000000..5b50a8b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_nonexistent_parent.html.twig @@ -0,0 +1,3 @@ +{% extends ['nonexistent.html.twig','parent.html.twig'] %} + +{% block body %}{{ parent() }} Child{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_null_parent.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_null_parent.html.twig new file mode 100644 index 0000000..a16b3ad --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_null_parent.html.twig @@ -0,0 +1,3 @@ +{% extends [null,'parent.html.twig'] %} + +{% block body %}{{ parent() }} Child{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_valid_parent.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_valid_parent.html.twig new file mode 100644 index 0000000..4940dad --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_valid_parent.html.twig @@ -0,0 +1,3 @@ +{% extends ['parent.html.twig','spare_parent.html.twig'] %} + +{% block body %}{{ parent() }} Child{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/parent.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/parent.html.twig new file mode 100644 index 0000000..d594c0e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/parent.html.twig @@ -0,0 +1 @@ +{% block body %}VALID{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/spare_parent.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/spare_parent.html.twig new file mode 100644 index 0000000..70b7360 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/inheritance/spare_parent.html.twig @@ -0,0 +1 @@ +{% block body %}SPARE PARENT{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named/index.html new file mode 100644 index 0000000..9e5449c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named/index.html @@ -0,0 +1 @@ +named path diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_bis/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_bis/index.html new file mode 100644 index 0000000..d3a272b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_bis/index.html @@ -0,0 +1 @@ +named path (bis) diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_final/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_final/index.html new file mode 100644 index 0000000..9f05d15 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_final/index.html @@ -0,0 +1 @@ +named path (final) diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html new file mode 100644 index 0000000..b1fb5f5 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html @@ -0,0 +1 @@ +named path (quater) diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_ter/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_ter/index.html new file mode 100644 index 0000000..24fb68a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/named_ter/index.html @@ -0,0 +1 @@ +named path (ter) diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal/index.html new file mode 100644 index 0000000..e7a8fd4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal/index.html @@ -0,0 +1 @@ +path diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_bis/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_bis/index.html new file mode 100644 index 0000000..bfa9160 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_bis/index.html @@ -0,0 +1 @@ +path (bis) diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_final/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_final/index.html new file mode 100644 index 0000000..73a089b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_final/index.html @@ -0,0 +1 @@ +path (final) diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_ter/index.html b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_ter/index.html new file mode 100644 index 0000000..b7ad97d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/normal_ter/index.html @@ -0,0 +1 @@ +path (ter) diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/phar/phar-sample.phar b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/phar/phar-sample.phar new file mode 100644 index 0000000..092bbfa Binary files /dev/null and b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/phar/phar-sample.phar differ diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/themes/theme1/blocks.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/themes/theme1/blocks.html.twig new file mode 100644 index 0000000..dd0cbc2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/themes/theme1/blocks.html.twig @@ -0,0 +1,3 @@ +{% block b1 %}block from theme 1{% endblock %} + +{% block b2 %}block from theme 1{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/themes/theme2/blocks.html.twig b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/themes/theme2/blocks.html.twig new file mode 100644 index 0000000..07cf9db --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Loader/Fixtures/themes/theme2/blocks.html.twig @@ -0,0 +1,3 @@ +{% use '@default_theme/blocks.html.twig' %} + +{% block b2 %}block from theme 2{% endblock %} diff --git a/vendor/twig/twig/test/Twig/Tests/NativeExtensionTest.php b/vendor/twig/twig/test/Twig/Tests/NativeExtensionTest.php new file mode 100644 index 0000000..50736dc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/NativeExtensionTest.php @@ -0,0 +1,32 @@ + '{{ d1.date }}{{ d2.date }}')), array( + 'debug' => true, + 'cache' => false, + 'autoescape' => false, + )); + + $d1 = new DateTime(); + $d2 = new DateTime(); + $output = $twig->render('index', compact('d1', 'd2')); + + // If it fails, PHP will crash. + $this->assertEquals($output, $d1->date.$d2->date); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/AutoEscapeTest.php b/vendor/twig/twig/test/Twig/Tests/Node/AutoEscapeTest.php new file mode 100644 index 0000000..25d1602 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/AutoEscapeTest.php @@ -0,0 +1,32 @@ +assertEquals($body, $node->getNode('body')); + $this->assertTrue($node->getAttribute('value')); + } + + public function getTests() + { + $body = new Twig_Node(array(new Twig_Node_Text('foo', 1))); + $node = new Twig_Node_AutoEscape(true, $body, 1); + + return array( + array($node, "// line 1\necho \"foo\";"), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/BlockReferenceTest.php b/vendor/twig/twig/test/Twig/Tests/Node/BlockReferenceTest.php new file mode 100644 index 0000000..84dac9b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/BlockReferenceTest.php @@ -0,0 +1,31 @@ +assertEquals('foo', $node->getAttribute('name')); + } + + public function getTests() + { + return array( + array(new Twig_Node_BlockReference('foo', 1), <<displayBlock('foo', \$context, \$blocks); +EOF + ), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/BlockTest.php b/vendor/twig/twig/test/Twig/Tests/Node/BlockTest.php new file mode 100644 index 0000000..e7246dc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/BlockTest.php @@ -0,0 +1,39 @@ +assertEquals($body, $node->getNode('body')); + $this->assertEquals('foo', $node->getAttribute('name')); + } + + public function getTests() + { + $body = new Twig_Node_Text('foo', 1); + $node = new Twig_Node_Block('foo', $body, 1); + + return array( + array($node, <<assertEquals($expr, $node->getNode('expr')); + } + + public function getTests() + { + $tests = array(); + + $expr = new Twig_Node_Expression_Constant('This section is deprecated', 1); + $node = new Twig_Node_Deprecated($expr, 1, 'deprecated'); + $node->setTemplateName('foo.twig'); + + $tests[] = array($node, <<setTemplateName('foo.twig'); + + $tests[] = array($node, <<getMockBuilder('Twig_LoaderInterface')->getMock()); + $environment->addFunction(new Twig_SimpleFunction('foo', 'foo', array())); + + $expr = new Twig_Node_Expression_Function('foo', new Twig_Node(), 1); + $node = new Twig_Node_Deprecated($expr, 1, 'deprecated'); + $node->setTemplateName('foo.twig'); + + $compiler = $this->getCompiler($environment); + $varName = $compiler->getVarName(); + + $tests[] = array($node, <<assertEquals($expr, $node->getNode('expr')); + } + + public function getTests() + { + $tests = array(); + + $expr = new Twig_Node_Expression_Constant('foo', 1); + $node = new Twig_Node_Do($expr, 1); + $tests[] = array($node, "// line 1\n\"foo\";"); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/ArrayTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ArrayTest.php new file mode 100644 index 0000000..4f83ab1 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ArrayTest.php @@ -0,0 +1,37 @@ +assertEquals($foo, $node->getNode(1)); + } + + public function getTests() + { + $elements = array( + new Twig_Node_Expression_Constant('foo', 1), + new Twig_Node_Expression_Constant('bar', 1), + + new Twig_Node_Expression_Constant('bar', 1), + new Twig_Node_Expression_Constant('foo', 1), + ); + $node = new Twig_Node_Expression_Array($elements, 1); + + return array( + array($node, 'array("foo" => "bar", "bar" => "foo")'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/AssignNameTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/AssignNameTest.php new file mode 100644 index 0000000..bf365de --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/AssignNameTest.php @@ -0,0 +1,29 @@ +assertEquals('foo', $node->getAttribute('name')); + } + + public function getTests() + { + $node = new Twig_Node_Expression_AssignName('foo', 1); + + return array( + array($node, '$context["foo"]'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/AddTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/AddTest.php new file mode 100644 index 0000000..02310a1 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/AddTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_Add($left, $right, 1); + + return array( + array($node, '(1 + 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/AndTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/AndTest.php new file mode 100644 index 0000000..2df3c8e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/AndTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_And($left, $right, 1); + + return array( + array($node, '(1 && 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/ConcatTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/ConcatTest.php new file mode 100644 index 0000000..759e482 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/ConcatTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_Concat($left, $right, 1); + + return array( + array($node, '(1 . 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/DivTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/DivTest.php new file mode 100644 index 0000000..0e54b10 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/DivTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_Div($left, $right, 1); + + return array( + array($node, '(1 / 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/FloorDivTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/FloorDivTest.php new file mode 100644 index 0000000..5813dce --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/FloorDivTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_FloorDiv($left, $right, 1); + + return array( + array($node, '(int) floor((1 / 2))'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/ModTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/ModTest.php new file mode 100644 index 0000000..4c663c7 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/ModTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_Mod($left, $right, 1); + + return array( + array($node, '(1 % 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/MulTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/MulTest.php new file mode 100644 index 0000000..e92c95e --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/MulTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_Mul($left, $right, 1); + + return array( + array($node, '(1 * 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/OrTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/OrTest.php new file mode 100644 index 0000000..ec37c83 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/OrTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_Or($left, $right, 1); + + return array( + array($node, '(1 || 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/SubTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/SubTest.php new file mode 100644 index 0000000..061cb27 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Binary/SubTest.php @@ -0,0 +1,34 @@ +assertEquals($left, $node->getNode('left')); + $this->assertEquals($right, $node->getNode('right')); + } + + public function getTests() + { + $left = new Twig_Node_Expression_Constant(1, 1); + $right = new Twig_Node_Expression_Constant(2, 1); + $node = new Twig_Node_Expression_Binary_Sub($left, $right, 1); + + return array( + array($node, '(1 - 2)'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/CallTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/CallTest.php new file mode 100644 index 0000000..883bb61 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/CallTest.php @@ -0,0 +1,143 @@ + 'function', 'name' => 'date')); + $this->assertEquals(array('U', null), $node->getArguments('date', array('format' => 'U', 'timestamp' => null))); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Positional arguments cannot be used after named arguments for function "date". + */ + public function testGetArgumentsWhenPositionalArgumentsAfterNamedArguments() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'date')); + $node->getArguments('date', array('timestamp' => 123456, 'Y-m-d')); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Argument "format" is defined twice for function "date". + */ + public function testGetArgumentsWhenArgumentIsDefinedTwice() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'date')); + $node->getArguments('date', array('Y-m-d', 'format' => 'U')); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown argument "unknown" for function "date(format, timestamp)". + */ + public function testGetArgumentsWithWrongNamedArgumentName() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'date')); + $node->getArguments('date', array('Y-m-d', 'timestamp' => null, 'unknown' => '')); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown arguments "unknown1", "unknown2" for function "date(format, timestamp)". + */ + public function testGetArgumentsWithWrongNamedArgumentNames() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'date')); + $node->getArguments('date', array('Y-m-d', 'timestamp' => null, 'unknown1' => '', 'unknown2' => '')); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Argument "case_sensitivity" could not be assigned for function "substr_compare(main_str, str, offset, length, case_sensitivity)" because it is mapped to an internal PHP function which cannot determine default value for optional argument "length". + */ + public function testResolveArgumentsWithMissingValueForOptionalArgument() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'substr_compare')); + $node->getArguments('substr_compare', array('abcd', 'bc', 'offset' => 1, 'case_sensitivity' => true)); + } + + public function testResolveArgumentsOnlyNecessaryArgumentsForCustomFunction() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'custom_function')); + + $this->assertEquals(array('arg1'), $node->getArguments(array($this, 'customFunction'), array('arg1' => 'arg1'))); + } + + public function testGetArgumentsForStaticMethod() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'custom_static_function')); + $this->assertEquals(array('arg1'), $node->getArguments(__CLASS__.'::customStaticFunction', array('arg1' => 'arg1'))); + } + + /** + * @expectedException LogicException + * @expectedExceptionMessage The last parameter of "Twig_Tests_Node_Expression_CallTest::customFunctionWithArbitraryArguments" for function "foo" must be an array with default value, eg. "array $arg = array()". + */ + public function testResolveArgumentsWithMissingParameterForArbitraryArguments() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'foo', 'is_variadic' => true)); + $node->getArguments(array($this, 'customFunctionWithArbitraryArguments'), array()); + } + + public static function customStaticFunction($arg1, $arg2 = 'default', $arg3 = array()) + { + } + + public function customFunction($arg1, $arg2 = 'default', $arg3 = array()) + { + } + + public function customFunctionWithArbitraryArguments() + { + } + + /** + * @expectedException LogicException + * @expectedExceptionMessageRegExp #^The last parameter of "custom_Twig_Tests_Node_Expression_CallTest_function" for function "foo" must be an array with default value, eg\. "array \$arg \= array\(\)"\.$# + */ + public function testResolveArgumentsWithMissingParameterForArbitraryArgumentsOnFunction() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'foo', 'is_variadic' => true)); + $node->getArguments('custom_Twig_Tests_Node_Expression_CallTest_function', array()); + } + + /** + * @expectedException LogicException + * @expectedExceptionMessageRegExp #^The last parameter of "CallableTestClass\:\:__invoke" for function "foo" must be an array with default value, eg\. "array \$arg \= array\(\)"\.$# + */ + public function testResolveArgumentsWithMissingParameterForArbitraryArgumentsOnObject() + { + $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'foo', 'is_variadic' => true)); + $node->getArguments(new CallableTestClass(), array()); + } +} + +class Twig_Tests_Node_Expression_Call extends Twig_Node_Expression_Call +{ + public function getArguments($callable, $arguments) + { + return parent::getArguments($callable, $arguments); + } +} + +class CallableTestClass +{ + public function __invoke($required) + { + } +} + +function custom_Twig_Tests_Node_Expression_CallTest_function($required) +{ +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/ConditionalTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ConditionalTest.php new file mode 100644 index 0000000..a3e8bad --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ConditionalTest.php @@ -0,0 +1,38 @@ +assertEquals($expr1, $node->getNode('expr1')); + $this->assertEquals($expr2, $node->getNode('expr2')); + $this->assertEquals($expr3, $node->getNode('expr3')); + } + + public function getTests() + { + $tests = array(); + + $expr1 = new Twig_Node_Expression_Constant(1, 1); + $expr2 = new Twig_Node_Expression_Constant(2, 1); + $expr3 = new Twig_Node_Expression_Constant(3, 1); + $node = new Twig_Node_Expression_Conditional($expr1, $expr2, $expr3, 1); + $tests[] = array($node, '((1) ? (2) : (3))'); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/ConstantTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ConstantTest.php new file mode 100644 index 0000000..2ff9318 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ConstantTest.php @@ -0,0 +1,30 @@ +assertEquals('foo', $node->getAttribute('value')); + } + + public function getTests() + { + $tests = array(); + + $node = new Twig_Node_Expression_Constant('foo', 1); + $tests[] = array($node, '"foo"'); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/FilterTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/FilterTest.php new file mode 100644 index 0000000..5f34b1d --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/FilterTest.php @@ -0,0 +1,154 @@ +assertEquals($expr, $node->getNode('node')); + $this->assertEquals($name, $node->getNode('filter')); + $this->assertEquals($args, $node->getNode('arguments')); + } + + public function getTests() + { + $environment = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $environment->addFilter(new Twig_SimpleFilter('bar', 'bar', array('needs_environment' => true))); + $environment->addFilter(new Twig_SimpleFilter('barbar', 'twig_tests_filter_barbar', array('needs_context' => true, 'is_variadic' => true))); + + $tests = array(); + + $expr = new Twig_Node_Expression_Constant('foo', 1); + $node = $this->createFilter($expr, 'upper'); + $node = $this->createFilter($node, 'number_format', array(new Twig_Node_Expression_Constant(2, 1), new Twig_Node_Expression_Constant('.', 1), new Twig_Node_Expression_Constant(',', 1))); + + if (function_exists('mb_get_info')) { + $tests[] = array($node, 'twig_number_format_filter($this->env, twig_upper_filter($this->env, "foo"), 2, ".", ",")'); + } else { + $tests[] = array($node, 'twig_number_format_filter($this->env, strtoupper("foo"), 2, ".", ",")'); + } + + // named arguments + $date = new Twig_Node_Expression_Constant(0, 1); + $node = $this->createFilter($date, 'date', array( + 'timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1), + 'format' => new Twig_Node_Expression_Constant('d/m/Y H:i:s P', 1), + )); + $tests[] = array($node, 'twig_date_format_filter($this->env, 0, "d/m/Y H:i:s P", "America/Chicago")'); + + // skip an optional argument + $date = new Twig_Node_Expression_Constant(0, 1); + $node = $this->createFilter($date, 'date', array( + 'timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1), + )); + $tests[] = array($node, 'twig_date_format_filter($this->env, 0, null, "America/Chicago")'); + + // underscores vs camelCase for named arguments + $string = new Twig_Node_Expression_Constant('abc', 1); + $node = $this->createFilter($string, 'reverse', array( + 'preserve_keys' => new Twig_Node_Expression_Constant(true, 1), + )); + $tests[] = array($node, 'twig_reverse_filter($this->env, "abc", true)'); + $node = $this->createFilter($string, 'reverse', array( + 'preserveKeys' => new Twig_Node_Expression_Constant(true, 1), + )); + $tests[] = array($node, 'twig_reverse_filter($this->env, "abc", true)'); + + // filter as an anonymous function + if (PHP_VERSION_ID >= 50300) { + $node = $this->createFilter(new Twig_Node_Expression_Constant('foo', 1), 'anonymous'); + $tests[] = array($node, 'call_user_func_array($this->env->getFilter(\'anonymous\')->getCallable(), array("foo"))'); + } + + // needs environment + $node = $this->createFilter($string, 'bar'); + $tests[] = array($node, 'bar($this->env, "abc")', $environment); + + $node = $this->createFilter($string, 'bar', array(new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'bar($this->env, "abc", "bar")', $environment); + + // arbitrary named arguments + $node = $this->createFilter($string, 'barbar'); + $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc")', $environment); + + $node = $this->createFilter($string, 'barbar', array('foo' => new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", null, null, array("foo" => "bar"))', $environment); + + $node = $this->createFilter($string, 'barbar', array('arg2' => new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", null, "bar")', $environment); + + $node = $this->createFilter($string, 'barbar', array( + new Twig_Node_Expression_Constant('1', 1), + new Twig_Node_Expression_Constant('2', 1), + new Twig_Node_Expression_Constant('3', 1), + 'foo' => new Twig_Node_Expression_Constant('bar', 1), + )); + $tests[] = array($node, 'twig_tests_filter_barbar($context, "abc", "1", "2", array(0 => "3", "foo" => "bar"))', $environment); + + return $tests; + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown argument "foobar" for filter "date(format, timezone)" at line 1. + */ + public function testCompileWithWrongNamedArgumentName() + { + $date = new Twig_Node_Expression_Constant(0, 1); + $node = $this->createFilter($date, 'date', array( + 'foobar' => new Twig_Node_Expression_Constant('America/Chicago', 1), + )); + + $compiler = $this->getCompiler(); + $compiler->compile($node); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Value for argument "from" is required for filter "replace" at line 1. + */ + public function testCompileWithMissingNamedArgument() + { + $value = new Twig_Node_Expression_Constant(0, 1); + $node = $this->createFilter($value, 'replace', array( + 'to' => new Twig_Node_Expression_Constant('foo', 1), + )); + + $compiler = $this->getCompiler(); + $compiler->compile($node); + } + + protected function createFilter($node, $name, array $arguments = array()) + { + $name = new Twig_Node_Expression_Constant($name, 1); + $arguments = new Twig_Node($arguments); + + return new Twig_Node_Expression_Filter($node, $name, $arguments, 1); + } + + protected function getEnvironment() + { + if (PHP_VERSION_ID >= 50300) { + return include 'PHP53/FilterInclude.php'; + } + + return parent::getEnvironment(); + } +} + +function twig_tests_filter_barbar($context, $string, $arg1 = null, $arg2 = null, array $args = array()) +{ +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/FunctionTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/FunctionTest.php new file mode 100644 index 0000000..2e82e2f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/FunctionTest.php @@ -0,0 +1,110 @@ +assertEquals($name, $node->getAttribute('name')); + $this->assertEquals($args, $node->getNode('arguments')); + } + + public function getTests() + { + $environment = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $environment->addFunction(new Twig_SimpleFunction('foo', 'foo', array())); + $environment->addFunction(new Twig_SimpleFunction('bar', 'bar', array('needs_environment' => true))); + $environment->addFunction(new Twig_SimpleFunction('foofoo', 'foofoo', array('needs_context' => true))); + $environment->addFunction(new Twig_SimpleFunction('foobar', 'foobar', array('needs_environment' => true, 'needs_context' => true))); + $environment->addFunction(new Twig_SimpleFunction('barbar', 'twig_tests_function_barbar', array('is_variadic' => true))); + + $tests = array(); + + $node = $this->createFunction('foo'); + $tests[] = array($node, 'foo()', $environment); + + $node = $this->createFunction('foo', array(new Twig_Node_Expression_Constant('bar', 1), new Twig_Node_Expression_Constant('foobar', 1))); + $tests[] = array($node, 'foo("bar", "foobar")', $environment); + + $node = $this->createFunction('bar'); + $tests[] = array($node, 'bar($this->env)', $environment); + + $node = $this->createFunction('bar', array(new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'bar($this->env, "bar")', $environment); + + $node = $this->createFunction('foofoo'); + $tests[] = array($node, 'foofoo($context)', $environment); + + $node = $this->createFunction('foofoo', array(new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'foofoo($context, "bar")', $environment); + + $node = $this->createFunction('foobar'); + $tests[] = array($node, 'foobar($this->env, $context)', $environment); + + $node = $this->createFunction('foobar', array(new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'foobar($this->env, $context, "bar")', $environment); + + // named arguments + $node = $this->createFunction('date', array( + 'timezone' => new Twig_Node_Expression_Constant('America/Chicago', 1), + 'date' => new Twig_Node_Expression_Constant(0, 1), + )); + $tests[] = array($node, 'twig_date_converter($this->env, 0, "America/Chicago")'); + + // arbitrary named arguments + $node = $this->createFunction('barbar'); + $tests[] = array($node, 'twig_tests_function_barbar()', $environment); + + $node = $this->createFunction('barbar', array('foo' => new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'twig_tests_function_barbar(null, null, array("foo" => "bar"))', $environment); + + $node = $this->createFunction('barbar', array('arg2' => new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'twig_tests_function_barbar(null, "bar")', $environment); + + $node = $this->createFunction('barbar', array( + new Twig_Node_Expression_Constant('1', 1), + new Twig_Node_Expression_Constant('2', 1), + new Twig_Node_Expression_Constant('3', 1), + 'foo' => new Twig_Node_Expression_Constant('bar', 1), + )); + $tests[] = array($node, 'twig_tests_function_barbar("1", "2", array(0 => "3", "foo" => "bar"))', $environment); + + // function as an anonymous function + if (PHP_VERSION_ID >= 50300) { + $node = $this->createFunction('anonymous', array(new Twig_Node_Expression_Constant('foo', 1))); + $tests[] = array($node, 'call_user_func_array($this->env->getFunction(\'anonymous\')->getCallable(), array("foo"))'); + } + + return $tests; + } + + protected function createFunction($name, array $arguments = array()) + { + return new Twig_Node_Expression_Function($name, new Twig_Node($arguments), 1); + } + + protected function getEnvironment() + { + if (PHP_VERSION_ID >= 50300) { + return include 'PHP53/FunctionInclude.php'; + } + + return parent::getEnvironment(); + } +} + +function twig_tests_function_barbar($arg1 = null, $arg2 = null, array $args = array()) +{ +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/GetAttrTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/GetAttrTest.php new file mode 100644 index 0000000..2764478 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/GetAttrTest.php @@ -0,0 +1,50 @@ +addElement(new Twig_Node_Expression_Name('foo', 1)); + $args->addElement(new Twig_Node_Expression_Constant('bar', 1)); + $node = new Twig_Node_Expression_GetAttr($expr, $attr, $args, Twig_Template::ARRAY_CALL, 1); + + $this->assertEquals($expr, $node->getNode('node')); + $this->assertEquals($attr, $node->getNode('attribute')); + $this->assertEquals($args, $node->getNode('arguments')); + $this->assertEquals(Twig_Template::ARRAY_CALL, $node->getAttribute('type')); + } + + public function getTests() + { + $tests = array(); + + $expr = new Twig_Node_Expression_Name('foo', 1); + $attr = new Twig_Node_Expression_Constant('bar', 1); + $args = new Twig_Node_Expression_Array(array(), 1); + $node = new Twig_Node_Expression_GetAttr($expr, $attr, $args, Twig_Template::ANY_CALL, 1); + $tests[] = array($node, sprintf('%s%s, "bar", array())', $this->getAttributeGetter(), $this->getVariableGetter('foo', 1))); + + $node = new Twig_Node_Expression_GetAttr($expr, $attr, $args, Twig_Template::ARRAY_CALL, 1); + $tests[] = array($node, sprintf('%s%s, "bar", array(), "array")', $this->getAttributeGetter(), $this->getVariableGetter('foo', 1))); + + $args = new Twig_Node_Expression_Array(array(), 1); + $args->addElement(new Twig_Node_Expression_Name('foo', 1)); + $args->addElement(new Twig_Node_Expression_Constant('bar', 1)); + $node = new Twig_Node_Expression_GetAttr($expr, $attr, $args, Twig_Template::METHOD_CALL, 1); + $tests[] = array($node, sprintf('%s%s, "bar", array(0 => %s, 1 => "bar"), "method")', $this->getAttributeGetter(), $this->getVariableGetter('foo', 1), $this->getVariableGetter('foo'))); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/NameTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/NameTest.php new file mode 100644 index 0000000..70721a8 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/NameTest.php @@ -0,0 +1,43 @@ +assertEquals('foo', $node->getAttribute('name')); + } + + public function getTests() + { + $node = new Twig_Node_Expression_Name('foo', 1); + $context = new Twig_Node_Expression_Name('_context', 1); + + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true)); + $env1 = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => false)); + + if (PHP_VERSION_ID >= 70000) { + $output = '($context["foo"] ?? $this->getContext($context, "foo"))'; + } elseif (PHP_VERSION_ID >= 50400) { + $output = '(isset($context["foo"]) ? $context["foo"] : $this->getContext($context, "foo"))'; + } else { + $output = '$this->getContext($context, "foo")'; + } + + return array( + array($node, "// line 1\n".$output, $env), + array($node, $this->getVariableGetter('foo', 1), $env1), + array($context, "// line 1\n\$context"), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/NullCoalesceTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/NullCoalesceTest.php new file mode 100644 index 0000000..e179a9f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/NullCoalesceTest.php @@ -0,0 +1,31 @@ += 70000) { + $tests[] = array($node, "((// line 1\n\$context[\"foo\"]) ?? (2))"); + } elseif (PHP_VERSION_ID >= 50400) { + $tests[] = array($node, "(((// line 1\n(isset(\$context[\"foo\"]) || array_key_exists(\"foo\", \$context)) && !(null === (isset(\$context[\"foo\"]) ? \$context[\"foo\"] : null)))) ? ((isset(\$context[\"foo\"]) ? \$context[\"foo\"] : null)) : (2))"); + } else { + $tests[] = array($node, "(((// line 1\n(isset(\$context[\"foo\"]) || array_key_exists(\"foo\", \$context)) && !(null === \$this->getContext(\$context, \"foo\")))) ? (\$this->getContext(\$context, \"foo\")) : (2))"); + } + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/FilterInclude.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/FilterInclude.php new file mode 100644 index 0000000..b5394bc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/FilterInclude.php @@ -0,0 +1,6 @@ +addFilter(new Twig_SimpleFilter('anonymous', function () {})); + +return $env; diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/FunctionInclude.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/FunctionInclude.php new file mode 100644 index 0000000..e8f68c7 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/FunctionInclude.php @@ -0,0 +1,6 @@ +addFunction(new Twig_SimpleFunction('anonymous', function () {})); + +return $env; diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/TestInclude.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/TestInclude.php new file mode 100644 index 0000000..9f818bc --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/PHP53/TestInclude.php @@ -0,0 +1,6 @@ +addTest(new Twig_SimpleTest('anonymous', function () {})); + +return $env; diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/ParentTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ParentTest.php new file mode 100644 index 0000000..ab2bbe0 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/ParentTest.php @@ -0,0 +1,28 @@ +assertEquals('foo', $node->getAttribute('name')); + } + + public function getTests() + { + $tests = array(); + $tests[] = array(new Twig_Node_Expression_Parent('foo', 1), '$this->renderParentBlock("foo", $context, $blocks)'); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/TestTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/TestTest.php new file mode 100644 index 0000000..a5f96d2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/TestTest.php @@ -0,0 +1,82 @@ +assertEquals($expr, $node->getNode('node')); + $this->assertEquals($args, $node->getNode('arguments')); + $this->assertEquals($name, $node->getAttribute('name')); + } + + public function getTests() + { + $environment = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $environment->addTest(new Twig_SimpleTest('barbar', 'twig_tests_test_barbar', array('is_variadic' => true, 'need_context' => true))); + + $tests = array(); + + $expr = new Twig_Node_Expression_Constant('foo', 1); + $node = new Twig_Node_Expression_Test_Null($expr, 'null', new Twig_Node(array()), 1); + $tests[] = array($node, '(null === "foo")'); + + // test as an anonymous function + if (PHP_VERSION_ID >= 50300) { + $node = $this->createTest(new Twig_Node_Expression_Constant('foo', 1), 'anonymous', array(new Twig_Node_Expression_Constant('foo', 1))); + $tests[] = array($node, 'call_user_func_array($this->env->getTest(\'anonymous\')->getCallable(), array("foo", "foo"))'); + } + + // arbitrary named arguments + $string = new Twig_Node_Expression_Constant('abc', 1); + $node = $this->createTest($string, 'barbar'); + $tests[] = array($node, 'twig_tests_test_barbar("abc")', $environment); + + $node = $this->createTest($string, 'barbar', array('foo' => new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'twig_tests_test_barbar("abc", null, null, array("foo" => "bar"))', $environment); + + $node = $this->createTest($string, 'barbar', array('arg2' => new Twig_Node_Expression_Constant('bar', 1))); + $tests[] = array($node, 'twig_tests_test_barbar("abc", null, "bar")', $environment); + + $node = $this->createTest($string, 'barbar', array( + new Twig_Node_Expression_Constant('1', 1), + new Twig_Node_Expression_Constant('2', 1), + new Twig_Node_Expression_Constant('3', 1), + 'foo' => new Twig_Node_Expression_Constant('bar', 1), + )); + $tests[] = array($node, 'twig_tests_test_barbar("abc", "1", "2", array(0 => "3", "foo" => "bar"))', $environment); + + return $tests; + } + + protected function createTest($node, $name, array $arguments = array()) + { + return new Twig_Node_Expression_Test($node, $name, new Twig_Node($arguments), 1); + } + + protected function getEnvironment() + { + if (PHP_VERSION_ID >= 50300) { + return include 'PHP53/TestInclude.php'; + } + + return parent::getEnvironment(); + } +} + +function twig_tests_test_barbar($string, $arg1 = null, $arg2 = null, array $args = array()) +{ +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/NegTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/NegTest.php new file mode 100644 index 0000000..b633371 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/NegTest.php @@ -0,0 +1,32 @@ +assertEquals($expr, $node->getNode('node')); + } + + public function getTests() + { + $node = new Twig_Node_Expression_Constant(1, 1); + $node = new Twig_Node_Expression_Unary_Neg($node, 1); + + return array( + array($node, '-1'), + array(new Twig_Node_Expression_Unary_Neg($node, 1), '- -1'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/NotTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/NotTest.php new file mode 100644 index 0000000..d7c6f85 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/NotTest.php @@ -0,0 +1,31 @@ +assertEquals($expr, $node->getNode('node')); + } + + public function getTests() + { + $node = new Twig_Node_Expression_Constant(1, 1); + $node = new Twig_Node_Expression_Unary_Not($node, 1); + + return array( + array($node, '!1'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/PosTest.php b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/PosTest.php new file mode 100644 index 0000000..057250f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/Expression/Unary/PosTest.php @@ -0,0 +1,31 @@ +assertEquals($expr, $node->getNode('node')); + } + + public function getTests() + { + $node = new Twig_Node_Expression_Constant(1, 1); + $node = new Twig_Node_Expression_Unary_Pos($node, 1); + + return array( + array($node, '+1'), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/ForTest.php b/vendor/twig/twig/test/Twig/Tests/Node/ForTest.php new file mode 100644 index 0000000..2bf4c7b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/ForTest.php @@ -0,0 +1,191 @@ +setAttribute('with_loop', false); + + $this->assertEquals($keyTarget, $node->getNode('key_target')); + $this->assertEquals($valueTarget, $node->getNode('value_target')); + $this->assertEquals($seq, $node->getNode('seq')); + $this->assertTrue($node->getAttribute('ifexpr')); + $this->assertEquals('Twig_Node_If', get_class($node->getNode('body'))); + $this->assertEquals($body, $node->getNode('body')->getNode('tests')->getNode(1)->getNode(0)); + $this->assertFalse($node->hasNode('else')); + + $else = new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1); + $node = new Twig_Node_For($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); + $node->setAttribute('with_loop', false); + $this->assertEquals($else, $node->getNode('else')); + } + + public function getTests() + { + $tests = array(); + + $keyTarget = new Twig_Node_Expression_AssignName('key', 1); + $valueTarget = new Twig_Node_Expression_AssignName('item', 1); + $seq = new Twig_Node_Expression_Name('items', 1); + $ifexpr = null; + $body = new Twig_Node(array(new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1)), array(), 1); + $else = null; + $node = new Twig_Node_For($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); + $node->setAttribute('with_loop', false); + + $tests[] = array($node, <<getVariableGetter('items')}); +foreach (\$context['_seq'] as \$context["key"] => \$context["item"]) { + echo {$this->getVariableGetter('foo')}; +} +\$_parent = \$context['_parent']; +unset(\$context['_seq'], \$context['_iterated'], \$context['key'], \$context['item'], \$context['_parent'], \$context['loop']); +\$context = array_intersect_key(\$context, \$_parent) + \$_parent; +EOF + ); + + $keyTarget = new Twig_Node_Expression_AssignName('k', 1); + $valueTarget = new Twig_Node_Expression_AssignName('v', 1); + $seq = new Twig_Node_Expression_Name('values', 1); + $ifexpr = null; + $body = new Twig_Node(array(new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1)), array(), 1); + $else = null; + $node = new Twig_Node_For($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); + $node->setAttribute('with_loop', true); + + $tests[] = array($node, <<getVariableGetter('values')}); +\$context['loop'] = array( + 'parent' => \$context['_parent'], + 'index0' => 0, + 'index' => 1, + 'first' => true, +); +if (is_array(\$context['_seq']) || (is_object(\$context['_seq']) && \$context['_seq'] instanceof Countable)) { + \$length = count(\$context['_seq']); + \$context['loop']['revindex0'] = \$length - 1; + \$context['loop']['revindex'] = \$length; + \$context['loop']['length'] = \$length; + \$context['loop']['last'] = 1 === \$length; +} +foreach (\$context['_seq'] as \$context["k"] => \$context["v"]) { + echo {$this->getVariableGetter('foo')}; + ++\$context['loop']['index0']; + ++\$context['loop']['index']; + \$context['loop']['first'] = false; + if (isset(\$context['loop']['length'])) { + --\$context['loop']['revindex0']; + --\$context['loop']['revindex']; + \$context['loop']['last'] = 0 === \$context['loop']['revindex0']; + } +} +\$_parent = \$context['_parent']; +unset(\$context['_seq'], \$context['_iterated'], \$context['k'], \$context['v'], \$context['_parent'], \$context['loop']); +\$context = array_intersect_key(\$context, \$_parent) + \$_parent; +EOF + ); + + $keyTarget = new Twig_Node_Expression_AssignName('k', 1); + $valueTarget = new Twig_Node_Expression_AssignName('v', 1); + $seq = new Twig_Node_Expression_Name('values', 1); + $ifexpr = new Twig_Node_Expression_Constant(true, 1); + $body = new Twig_Node(array(new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1)), array(), 1); + $else = null; + $node = new Twig_Node_For($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); + $node->setAttribute('with_loop', true); + + $tests[] = array($node, <<getVariableGetter('values')}); +\$context['loop'] = array( + 'parent' => \$context['_parent'], + 'index0' => 0, + 'index' => 1, + 'first' => true, +); +foreach (\$context['_seq'] as \$context["k"] => \$context["v"]) { + if (true) { + echo {$this->getVariableGetter('foo')}; + ++\$context['loop']['index0']; + ++\$context['loop']['index']; + \$context['loop']['first'] = false; + } +} +\$_parent = \$context['_parent']; +unset(\$context['_seq'], \$context['_iterated'], \$context['k'], \$context['v'], \$context['_parent'], \$context['loop']); +\$context = array_intersect_key(\$context, \$_parent) + \$_parent; +EOF + ); + + $keyTarget = new Twig_Node_Expression_AssignName('k', 1); + $valueTarget = new Twig_Node_Expression_AssignName('v', 1); + $seq = new Twig_Node_Expression_Name('values', 1); + $ifexpr = null; + $body = new Twig_Node(array(new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1)), array(), 1); + $else = new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1); + $node = new Twig_Node_For($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); + $node->setAttribute('with_loop', true); + + $tests[] = array($node, <<getVariableGetter('values')}); +\$context['_iterated'] = false; +\$context['loop'] = array( + 'parent' => \$context['_parent'], + 'index0' => 0, + 'index' => 1, + 'first' => true, +); +if (is_array(\$context['_seq']) || (is_object(\$context['_seq']) && \$context['_seq'] instanceof Countable)) { + \$length = count(\$context['_seq']); + \$context['loop']['revindex0'] = \$length - 1; + \$context['loop']['revindex'] = \$length; + \$context['loop']['length'] = \$length; + \$context['loop']['last'] = 1 === \$length; +} +foreach (\$context['_seq'] as \$context["k"] => \$context["v"]) { + echo {$this->getVariableGetter('foo')}; + \$context['_iterated'] = true; + ++\$context['loop']['index0']; + ++\$context['loop']['index']; + \$context['loop']['first'] = false; + if (isset(\$context['loop']['length'])) { + --\$context['loop']['revindex0']; + --\$context['loop']['revindex']; + \$context['loop']['last'] = 0 === \$context['loop']['revindex0']; + } +} +if (!\$context['_iterated']) { + echo {$this->getVariableGetter('foo')}; +} +\$_parent = \$context['_parent']; +unset(\$context['_seq'], \$context['_iterated'], \$context['k'], \$context['v'], \$context['_parent'], \$context['loop']); +\$context = array_intersect_key(\$context, \$_parent) + \$_parent; +EOF + ); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/IfTest.php b/vendor/twig/twig/test/Twig/Tests/Node/IfTest.php new file mode 100644 index 0000000..4ab0e4c --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/IfTest.php @@ -0,0 +1,88 @@ +assertEquals($t, $node->getNode('tests')); + $this->assertFalse($node->hasNode('else')); + + $else = new Twig_Node_Print(new Twig_Node_Expression_Name('bar', 1), 1); + $node = new Twig_Node_If($t, $else, 1); + $this->assertEquals($else, $node->getNode('else')); + } + + public function getTests() + { + $tests = array(); + + $t = new Twig_Node(array( + new Twig_Node_Expression_Constant(true, 1), + new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1), + ), array(), 1); + $else = null; + $node = new Twig_Node_If($t, $else, 1); + + $tests[] = array($node, <<getVariableGetter('foo')}; +} +EOF + ); + + $t = new Twig_Node(array( + new Twig_Node_Expression_Constant(true, 1), + new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1), + new Twig_Node_Expression_Constant(false, 1), + new Twig_Node_Print(new Twig_Node_Expression_Name('bar', 1), 1), + ), array(), 1); + $else = null; + $node = new Twig_Node_If($t, $else, 1); + + $tests[] = array($node, <<getVariableGetter('foo')}; +} elseif (false) { + echo {$this->getVariableGetter('bar')}; +} +EOF + ); + + $t = new Twig_Node(array( + new Twig_Node_Expression_Constant(true, 1), + new Twig_Node_Print(new Twig_Node_Expression_Name('foo', 1), 1), + ), array(), 1); + $else = new Twig_Node_Print(new Twig_Node_Expression_Name('bar', 1), 1); + $node = new Twig_Node_If($t, $else, 1); + + $tests[] = array($node, <<getVariableGetter('foo')}; +} else { + echo {$this->getVariableGetter('bar')}; +} +EOF + ); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/ImportTest.php b/vendor/twig/twig/test/Twig/Tests/Node/ImportTest.php new file mode 100644 index 0000000..36525b2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/ImportTest.php @@ -0,0 +1,40 @@ +assertEquals($macro, $node->getNode('expr')); + $this->assertEquals($var, $node->getNode('var')); + } + + public function getTests() + { + $tests = array(); + + $macro = new Twig_Node_Expression_Constant('foo.twig', 1); + $var = new Twig_Node_Expression_AssignName('macro', 1); + $node = new Twig_Node_Import($macro, $var, 1); + + $tests[] = array($node, <<loadTemplate("foo.twig", null, 1); +EOF + ); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/IncludeTest.php b/vendor/twig/twig/test/Twig/Tests/Node/IncludeTest.php new file mode 100644 index 0000000..d801f33 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/IncludeTest.php @@ -0,0 +1,83 @@ +assertFalse($node->hasNode('variables')); + $this->assertEquals($expr, $node->getNode('expr')); + $this->assertFalse($node->getAttribute('only')); + + $vars = new Twig_Node_Expression_Array(array(new Twig_Node_Expression_Constant('foo', 1), new Twig_Node_Expression_Constant(true, 1)), 1); + $node = new Twig_Node_Include($expr, $vars, true, false, 1); + $this->assertEquals($vars, $node->getNode('variables')); + $this->assertTrue($node->getAttribute('only')); + } + + public function getTests() + { + $tests = array(); + + $expr = new Twig_Node_Expression_Constant('foo.twig', 1); + $node = new Twig_Node_Include($expr, null, false, false, 1); + $tests[] = array($node, <<loadTemplate("foo.twig", null, 1)->display(\$context); +EOF + ); + + $expr = new Twig_Node_Expression_Conditional( + new Twig_Node_Expression_Constant(true, 1), + new Twig_Node_Expression_Constant('foo', 1), + new Twig_Node_Expression_Constant('foo', 1), + 0 + ); + $node = new Twig_Node_Include($expr, null, false, false, 1); + $tests[] = array($node, <<loadTemplate(((true) ? ("foo") : ("foo")), null, 1)->display(\$context); +EOF + ); + + $expr = new Twig_Node_Expression_Constant('foo.twig', 1); + $vars = new Twig_Node_Expression_Array(array(new Twig_Node_Expression_Constant('foo', 1), new Twig_Node_Expression_Constant(true, 1)), 1); + $node = new Twig_Node_Include($expr, $vars, false, false, 1); + $tests[] = array($node, <<loadTemplate("foo.twig", null, 1)->display(array_merge(\$context, array("foo" => true))); +EOF + ); + + $node = new Twig_Node_Include($expr, $vars, true, false, 1); + $tests[] = array($node, <<loadTemplate("foo.twig", null, 1)->display(array("foo" => true)); +EOF + ); + + $node = new Twig_Node_Include($expr, $vars, true, true, 1); + $tests[] = array($node, <<loadTemplate("foo.twig", null, 1)->display(array("foo" => true)); +} catch (Twig_Error_Loader \$e) { + // ignore missing template +} +EOF + ); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/MacroTest.php b/vendor/twig/twig/test/Twig/Tests/Node/MacroTest.php new file mode 100644 index 0000000..c7edfa2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/MacroTest.php @@ -0,0 +1,74 @@ +assertEquals($body, $node->getNode('body')); + $this->assertEquals($arguments, $node->getNode('arguments')); + $this->assertEquals('foo', $node->getAttribute('name')); + } + + public function getTests() + { + $body = new Twig_Node_Text('foo', 1); + $arguments = new Twig_Node(array( + 'foo' => new Twig_Node_Expression_Constant(null, 1), + 'bar' => new Twig_Node_Expression_Constant('Foo', 1), + ), array(), 1); + $node = new Twig_Node_Macro('foo', $body, $arguments, 1); + + if (PHP_VERSION_ID >= 50600) { + $declaration = ', ...$__varargs__'; + $varargs = '$__varargs__'; + } else { + $declaration = ''; + $varargs = 'func_num_args() > 2 ? array_slice(func_get_args(), 2) : array()'; + } + + return array( + array($node, <<env->mergeGlobals(array( + "foo" => \$__foo__, + "bar" => \$__bar__, + "varargs" => $varargs, + )); + + \$blocks = array(); + + ob_start(); + try { + echo "foo"; + } catch (Exception \$e) { + ob_end_clean(); + + throw \$e; + } catch (Throwable \$e) { + ob_end_clean(); + + throw \$e; + } + + return ('' === \$tmp = ob_get_clean()) ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset()); +} +EOF + ), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/ModuleTest.php b/vendor/twig/twig/test/Twig/Tests/Node/ModuleTest.php new file mode 100644 index 0000000..54a8989 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/ModuleTest.php @@ -0,0 +1,223 @@ +assertEquals($body, $node->getNode('body')); + $this->assertEquals($blocks, $node->getNode('blocks')); + $this->assertEquals($macros, $node->getNode('macros')); + $this->assertEquals($parent, $node->getNode('parent')); + $this->assertEquals($source->getName(), $node->getTemplateName()); + } + + public function getTests() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + + $tests = array(); + + $body = new Twig_Node_Text('foo', 1); + $extends = null; + $blocks = new Twig_Node(); + $macros = new Twig_Node(); + $traits = new Twig_Node(); + $source = new Twig_Source('{{ foo }}', 'foo.twig'); + + $node = new Twig_Node_Module($body, $extends, $blocks, $macros, $traits, new Twig_Node(array()), $source); + $tests[] = array($node, <<parent = false; + + \$this->blocks = array( + ); + } + + protected function doDisplay(array \$context, array \$blocks = array()) + { + // line 1 + echo "foo"; + } + + public function getTemplateName() + { + return "foo.twig"; + } + + public function getDebugInfo() + { + return array ( 19 => 1,); + } + + /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ + public function getSource() + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); + + return \$this->getSourceContext()->getCode(); + } + + public function getSourceContext() + { + return new Twig_Source("", "foo.twig", ""); + } +} +EOF + , $twig, true); + + $import = new Twig_Node_Import(new Twig_Node_Expression_Constant('foo.twig', 1), new Twig_Node_Expression_AssignName('macro', 1), 2); + + $body = new Twig_Node(array($import)); + $extends = new Twig_Node_Expression_Constant('layout.twig', 1); + + $node = new Twig_Node_Module($body, $extends, $blocks, $macros, $traits, new Twig_Node(array()), $source); + $tests[] = array($node, <<parent = \$this->loadTemplate("layout.twig", "foo.twig", 1); + \$this->blocks = array( + ); + } + + protected function doGetParent(array \$context) + { + return "layout.twig"; + } + + protected function doDisplay(array \$context, array \$blocks = array()) + { + // line 2 + \$context["macro"] = \$this->loadTemplate("foo.twig", "foo.twig", 2); + // line 1 + \$this->parent->display(\$context, array_merge(\$this->blocks, \$blocks)); + } + + public function getTemplateName() + { + return "foo.twig"; + } + + public function isTraitable() + { + return false; + } + + public function getDebugInfo() + { + return array ( 26 => 1, 24 => 2, 11 => 1,); + } + + /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ + public function getSource() + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); + + return \$this->getSourceContext()->getCode(); + } + + public function getSourceContext() + { + return new Twig_Source("", "foo.twig", ""); + } +} +EOF + , $twig, true); + + $set = new Twig_Node_Set(false, new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 4))), new Twig_Node(array(new Twig_Node_Expression_Constant('foo', 4))), 4); + $body = new Twig_Node(array($set)); + $extends = new Twig_Node_Expression_Conditional( + new Twig_Node_Expression_Constant(true, 2), + new Twig_Node_Expression_Constant('foo', 2), + new Twig_Node_Expression_Constant('foo', 2), + 2 + ); + + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('debug' => true)); + $node = new Twig_Node_Module($body, $extends, $blocks, $macros, $traits, new Twig_Node(array()), $source); + $tests[] = array($node, <<loadTemplate(((true) ? ("foo") : ("foo")), "foo.twig", 2); + } + + protected function doDisplay(array \$context, array \$blocks = array()) + { + // line 4 + \$context["foo"] = "foo"; + // line 2 + \$this->getParent(\$context)->display(\$context, array_merge(\$this->blocks, \$blocks)); + } + + public function getTemplateName() + { + return "foo.twig"; + } + + public function isTraitable() + { + return false; + } + + public function getDebugInfo() + { + return array ( 17 => 2, 15 => 4, 9 => 2,); + } + + /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ + public function getSource() + { + @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); + + return \$this->getSourceContext()->getCode(); + } + + public function getSourceContext() + { + return new Twig_Source("{{ foo }}", "foo.twig", ""); + } +} +EOF + , $twig, true); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/PrintTest.php b/vendor/twig/twig/test/Twig/Tests/Node/PrintTest.php new file mode 100644 index 0000000..4e0990f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/PrintTest.php @@ -0,0 +1,29 @@ +assertEquals($expr, $node->getNode('expr')); + } + + public function getTests() + { + $tests = array(); + $tests[] = array(new Twig_Node_Print(new Twig_Node_Expression_Constant('foo', 1), 1), "// line 1\necho \"foo\";"); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/SandboxTest.php b/vendor/twig/twig/test/Twig/Tests/Node/SandboxTest.php new file mode 100644 index 0000000..56f4877 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/SandboxTest.php @@ -0,0 +1,44 @@ +assertEquals($body, $node->getNode('body')); + } + + public function getTests() + { + $tests = array(); + + $body = new Twig_Node_Text('foo', 1); + $node = new Twig_Node_Sandbox($body, 1); + + $tests[] = array($node, <<env->getExtension('Twig_Extension_Sandbox'); +if (!\$alreadySandboxed = \$sandbox->isSandboxed()) { + \$sandbox->enableSandbox(); +} +echo "foo"; +if (!\$alreadySandboxed) { + \$sandbox->disableSandbox(); +} +EOF + ); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/SandboxedPrintTest.php b/vendor/twig/twig/test/Twig/Tests/Node/SandboxedPrintTest.php new file mode 100644 index 0000000..8bc8a75 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/SandboxedPrintTest.php @@ -0,0 +1,33 @@ +assertEquals($expr, $node->getNode('expr')); + } + + public function getTests() + { + $tests = array(); + + $tests[] = array(new Twig_Node_SandboxedPrint(new Twig_Node_Expression_Constant('foo', 1), 1), <<env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed("foo"); +EOF + ); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/SetTest.php b/vendor/twig/twig/test/Twig/Tests/Node/SetTest.php new file mode 100644 index 0000000..62ad280 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/SetTest.php @@ -0,0 +1,69 @@ +assertEquals($names, $node->getNode('names')); + $this->assertEquals($values, $node->getNode('values')); + $this->assertFalse($node->getAttribute('capture')); + } + + public function getTests() + { + $tests = array(); + + $names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 1)), array(), 1); + $values = new Twig_Node(array(new Twig_Node_Expression_Constant('foo', 1)), array(), 1); + $node = new Twig_Node_Set(false, $names, $values, 1); + $tests[] = array($node, <<env->getCharset()); +EOF + ); + + $names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 1)), array(), 1); + $values = new Twig_Node_Text('foo', 1); + $node = new Twig_Node_Set(true, $names, $values, 1); + $tests[] = array($node, <<env->getCharset()); +EOF + ); + + $names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 1), new Twig_Node_Expression_AssignName('bar', 1)), array(), 1); + $values = new Twig_Node(array(new Twig_Node_Expression_Constant('foo', 1), new Twig_Node_Expression_Name('bar', 1)), array(), 1); + $node = new Twig_Node_Set(false, $names, $values, 1); + $tests[] = array($node, <<getVariableGetter('bar')}); +EOF + ); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/SpacelessTest.php b/vendor/twig/twig/test/Twig/Tests/Node/SpacelessTest.php new file mode 100644 index 0000000..222ca09 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/SpacelessTest.php @@ -0,0 +1,37 @@ +
    foo
    ', 1))); + $node = new Twig_Node_Spaceless($body, 1); + + $this->assertEquals($body, $node->getNode('body')); + } + + public function getTests() + { + $body = new Twig_Node(array(new Twig_Node_Text('
    foo
    ', 1))); + $node = new Twig_Node_Spaceless($body, 1); + + return array( + array($node, <<
    foo
    "; +echo trim(preg_replace('/>\s+<', ob_get_clean())); +EOF + ), + ); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Node/TextTest.php b/vendor/twig/twig/test/Twig/Tests/Node/TextTest.php new file mode 100644 index 0000000..ceaf67f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Node/TextTest.php @@ -0,0 +1,28 @@ +assertEquals('foo', $node->getAttribute('data')); + } + + public function getTests() + { + $tests = array(); + $tests[] = array(new Twig_Node_Text('foo', 1), "// line 1\necho \"foo\";"); + + return $tests; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/NodeVisitor/OptimizerTest.php b/vendor/twig/twig/test/Twig/Tests/NodeVisitor/OptimizerTest.php new file mode 100644 index 0000000..92c0eca --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/NodeVisitor/OptimizerTest.php @@ -0,0 +1,124 @@ +getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + + $stream = $env->parse($env->tokenize(new Twig_Source('{{ block("foo") }}', 'index'))); + + $node = $stream->getNode('body')->getNode(0); + + $this->assertEquals('Twig_Node_Expression_BlockReference', get_class($node)); + $this->assertTrue($node->getAttribute('output')); + } + + public function testRenderParentBlockOptimizer() + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + + $stream = $env->parse($env->tokenize(new Twig_Source('{% extends "foo" %}{% block content %}{{ parent() }}{% endblock %}', 'index'))); + + $node = $stream->getNode('blocks')->getNode('content')->getNode(0)->getNode('body'); + + $this->assertEquals('Twig_Node_Expression_Parent', get_class($node)); + $this->assertTrue($node->getAttribute('output')); + } + + public function testRenderVariableBlockOptimizer() + { + if (PHP_VERSION_ID >= 50400) { + $this->markTestSkipped('not needed on PHP >= 5.4'); + } + + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false, 'autoescape' => false)); + $stream = $env->parse($env->tokenize(new Twig_Source('{{ block(name|lower) }}', 'index'))); + + $node = $stream->getNode('body')->getNode(0)->getNode(1); + + $this->assertEquals('Twig_Node_Expression_BlockReference', get_class($node)); + $this->assertTrue($node->getAttribute('output')); + } + + /** + * @dataProvider getTestsForForOptimizer + */ + public function testForOptimizer($template, $expected) + { + $env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('cache' => false)); + + $stream = $env->parse($env->tokenize(new Twig_Source($template, 'index'))); + + foreach ($expected as $target => $withLoop) { + $this->assertTrue($this->checkForConfiguration($stream, $target, $withLoop), sprintf('variable %s is %soptimized', $target, $withLoop ? 'not ' : '')); + } + } + + public function getTestsForForOptimizer() + { + return array( + array('{% for i in foo %}{% endfor %}', array('i' => false)), + + array('{% for i in foo %}{{ loop.index }}{% endfor %}', array('i' => true)), + + array('{% for i in foo %}{% for j in foo %}{% endfor %}{% endfor %}', array('i' => false, 'j' => false)), + + array('{% for i in foo %}{% include "foo" %}{% endfor %}', array('i' => true)), + + array('{% for i in foo %}{% include "foo" only %}{% endfor %}', array('i' => false)), + + array('{% for i in foo %}{% include "foo" with { "foo": "bar" } only %}{% endfor %}', array('i' => false)), + + array('{% for i in foo %}{% include "foo" with { "foo": loop.index } only %}{% endfor %}', array('i' => true)), + + array('{% for i in foo %}{% for j in foo %}{{ loop.index }}{% endfor %}{% endfor %}', array('i' => false, 'j' => true)), + + array('{% for i in foo %}{% for j in foo %}{{ loop.parent.loop.index }}{% endfor %}{% endfor %}', array('i' => true, 'j' => true)), + + array('{% for i in foo %}{% set l = loop %}{% for j in foo %}{{ l.index }}{% endfor %}{% endfor %}', array('i' => true, 'j' => false)), + + array('{% for i in foo %}{% for j in foo %}{{ foo.parent.loop.index }}{% endfor %}{% endfor %}', array('i' => false, 'j' => false)), + + array('{% for i in foo %}{% for j in foo %}{{ loop["parent"].loop.index }}{% endfor %}{% endfor %}', array('i' => true, 'j' => true)), + + array('{% for i in foo %}{{ include("foo") }}{% endfor %}', array('i' => true)), + + array('{% for i in foo %}{{ include("foo", with_context = false) }}{% endfor %}', array('i' => false)), + + array('{% for i in foo %}{{ include("foo", with_context = true) }}{% endfor %}', array('i' => true)), + + array('{% for i in foo %}{{ include("foo", { "foo": "bar" }, with_context = false) }}{% endfor %}', array('i' => false)), + + array('{% for i in foo %}{{ include("foo", { "foo": loop.index }, with_context = false) }}{% endfor %}', array('i' => true)), + ); + } + + public function checkForConfiguration(Twig_NodeInterface $node = null, $target, $withLoop) + { + if (null === $node) { + return; + } + + foreach ($node as $n) { + if ($n instanceof Twig_Node_For) { + if ($target === $n->getNode('value_target')->getAttribute('name')) { + return $withLoop == $n->getAttribute('with_loop'); + } + } + + $ret = $this->checkForConfiguration($n, $target, $withLoop); + if (null !== $ret) { + return $ret; + } + } + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/ParserTest.php b/vendor/twig/twig/test/Twig/Tests/ParserTest.php new file mode 100644 index 0000000..342fb7b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/ParserTest.php @@ -0,0 +1,198 @@ +getParser(); + $parser->setMacro('parent', $this->getMockBuilder('Twig_Node_Macro')->disableOriginalConstructor()->getMock()); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "foo" tag. Did you mean "for" at line 1? + */ + public function testUnknownTag() + { + $stream = new Twig_TokenStream(array( + new Twig_Token(Twig_Token::BLOCK_START_TYPE, '', 1), + new Twig_Token(Twig_Token::NAME_TYPE, 'foo', 1), + new Twig_Token(Twig_Token::BLOCK_END_TYPE, '', 1), + new Twig_Token(Twig_Token::EOF_TYPE, '', 1), + )); + $parser = new Twig_Parser(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $parser->parse($stream); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unknown "foobar" tag at line 1. + */ + public function testUnknownTagWithoutSuggestions() + { + $stream = new Twig_TokenStream(array( + new Twig_Token(Twig_Token::BLOCK_START_TYPE, '', 1), + new Twig_Token(Twig_Token::NAME_TYPE, 'foobar', 1), + new Twig_Token(Twig_Token::BLOCK_END_TYPE, '', 1), + new Twig_Token(Twig_Token::EOF_TYPE, '', 1), + )); + $parser = new Twig_Parser(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $parser->parse($stream); + } + + /** + * @dataProvider getFilterBodyNodesData + */ + public function testFilterBodyNodes($input, $expected) + { + $parser = $this->getParser(); + + $this->assertEquals($expected, $parser->filterBodyNodes($input)); + } + + public function getFilterBodyNodesData() + { + return array( + array( + new Twig_Node(array(new Twig_Node_Text(' ', 1))), + new Twig_Node(array()), + ), + array( + $input = new Twig_Node(array(new Twig_Node_Set(false, new Twig_Node(), new Twig_Node(), 1))), + $input, + ), + array( + $input = new Twig_Node(array(new Twig_Node_Set(true, new Twig_Node(), new Twig_Node(array(new Twig_Node(array(new Twig_Node_Text('foo', 1))))), 1))), + $input, + ), + ); + } + + /** + * @dataProvider getFilterBodyNodesDataThrowsException + * @expectedException Twig_Error_Syntax + */ + public function testFilterBodyNodesThrowsException($input) + { + $parser = $this->getParser(); + + $parser->filterBodyNodes($input); + } + + public function getFilterBodyNodesDataThrowsException() + { + return array( + array(new Twig_Node_Text('foo', 1)), + array(new Twig_Node(array(new Twig_Node(array(new Twig_Node_Text('foo', 1)))))), + ); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage A template that extends another one cannot start with a byte order mark (BOM); it must be removed at line 1 + */ + public function testFilterBodyNodesWithBOM() + { + $parser = $this->getParser(); + $parser->filterBodyNodes(new Twig_Node_Text(chr(0xEF).chr(0xBB).chr(0xBF), 1)); + } + + public function testParseIsReentrant() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array( + 'autoescape' => false, + 'optimizations' => 0, + )); + $twig->addTokenParser(new TestTokenParser()); + + $parser = new Twig_Parser($twig); + + $parser->parse(new Twig_TokenStream(array( + new Twig_Token(Twig_Token::BLOCK_START_TYPE, '', 1), + new Twig_Token(Twig_Token::NAME_TYPE, 'test', 1), + new Twig_Token(Twig_Token::BLOCK_END_TYPE, '', 1), + new Twig_Token(Twig_Token::VAR_START_TYPE, '', 1), + new Twig_Token(Twig_Token::NAME_TYPE, 'foo', 1), + new Twig_Token(Twig_Token::VAR_END_TYPE, '', 1), + new Twig_Token(Twig_Token::EOF_TYPE, '', 1), + ))); + + $this->assertNull($parser->getParent()); + } + + public function testGetVarName() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array( + 'autoescape' => false, + 'optimizations' => 0, + )); + + $twig->parse($twig->tokenize(new Twig_Source(<<addToAssertionCount(1); + } + + protected function getParser() + { + $parser = new TestParser(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + $parser->setParent(new Twig_Node()); + $parser->stream = new Twig_TokenStream(array()); + + return $parser; + } +} + +class TestParser extends Twig_Parser +{ + public $stream; + + public function filterBodyNodes(Twig_NodeInterface $node) + { + return parent::filterBodyNodes($node); + } +} + +class TestTokenParser extends Twig_TokenParser +{ + public function parse(Twig_Token $token) + { + // simulate the parsing of another template right in the middle of the parsing of the current template + $this->parser->parse(new Twig_TokenStream(array( + new Twig_Token(Twig_Token::BLOCK_START_TYPE, '', 1), + new Twig_Token(Twig_Token::NAME_TYPE, 'extends', 1), + new Twig_Token(Twig_Token::STRING_TYPE, 'base', 1), + new Twig_Token(Twig_Token::BLOCK_END_TYPE, '', 1), + new Twig_Token(Twig_Token::EOF_TYPE, '', 1), + ))); + + $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE); + + return new Twig_Node(array()); + } + + public function getTag() + { + return 'test'; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/AbstractTest.php b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/AbstractTest.php new file mode 100644 index 0000000..a71b97b --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/AbstractTest.php @@ -0,0 +1,101 @@ +getMockBuilder('Twig_Profiler_Profile')->disableOriginalConstructor()->getMock(); + + $profile->expects($this->any())->method('isRoot')->will($this->returnValue(true)); + $profile->expects($this->any())->method('getName')->will($this->returnValue('main')); + $profile->expects($this->any())->method('getDuration')->will($this->returnValue(1)); + $profile->expects($this->any())->method('getMemoryUsage')->will($this->returnValue(0)); + $profile->expects($this->any())->method('getPeakMemoryUsage')->will($this->returnValue(0)); + + $subProfiles = array( + $this->getIndexProfile( + array( + $this->getEmbeddedBlockProfile(), + $this->getEmbeddedTemplateProfile( + array( + $this->getIncludedTemplateProfile(), + ) + ), + $this->getMacroProfile(), + $this->getEmbeddedTemplateProfile( + array( + $this->getIncludedTemplateProfile(), + ) + ), + ) + ), + ); + + $profile->expects($this->any())->method('getProfiles')->will($this->returnValue($subProfiles)); + $profile->expects($this->any())->method('getIterator')->will($this->returnValue(new ArrayIterator($subProfiles))); + + return $profile; + } + + private function getIndexProfile(array $subProfiles = array()) + { + return $this->generateProfile('main', 1, true, 'template', 'index.twig', $subProfiles); + } + + private function getEmbeddedBlockProfile(array $subProfiles = array()) + { + return $this->generateProfile('body', 0.0001, false, 'block', 'embedded.twig', $subProfiles); + } + + private function getEmbeddedTemplateProfile(array $subProfiles = array()) + { + return $this->generateProfile('main', 0.0001, true, 'template', 'embedded.twig', $subProfiles); + } + + private function getIncludedTemplateProfile(array $subProfiles = array()) + { + return $this->generateProfile('main', 0.0001, true, 'template', 'included.twig', $subProfiles); + } + + private function getMacroProfile(array $subProfiles = array()) + { + return $this->generateProfile('foo', 0.0001, false, 'macro', 'index.twig', $subProfiles); + } + + /** + * @param string $name + * @param float $duration + * @param bool $isTemplate + * @param string $type + * @param string $templateName + * @param array $subProfiles + * + * @return Twig_Profiler_Profile + */ + private function generateProfile($name, $duration, $isTemplate, $type, $templateName, array $subProfiles = array()) + { + $profile = $this->getMockBuilder('Twig_Profiler_Profile')->disableOriginalConstructor()->getMock(); + + $profile->expects($this->any())->method('isRoot')->will($this->returnValue(false)); + $profile->expects($this->any())->method('getName')->will($this->returnValue($name)); + $profile->expects($this->any())->method('getDuration')->will($this->returnValue($duration)); + $profile->expects($this->any())->method('getMemoryUsage')->will($this->returnValue(0)); + $profile->expects($this->any())->method('getPeakMemoryUsage')->will($this->returnValue(0)); + $profile->expects($this->any())->method('isTemplate')->will($this->returnValue($isTemplate)); + $profile->expects($this->any())->method('getType')->will($this->returnValue($type)); + $profile->expects($this->any())->method('getTemplate')->will($this->returnValue($templateName)); + $profile->expects($this->any())->method('getProfiles')->will($this->returnValue($subProfiles)); + $profile->expects($this->any())->method('getIterator')->will($this->returnValue(new ArrayIterator($subProfiles))); + + return $profile; + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/BlackfireTest.php b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/BlackfireTest.php new file mode 100644 index 0000000..1a1b9d2 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/BlackfireTest.php @@ -0,0 +1,32 @@ +assertStringMatchesFormat(<<index.twig//1 %d %d %d +index.twig==>embedded.twig::block(body)//1 %d %d 0 +index.twig==>embedded.twig//2 %d %d %d +embedded.twig==>included.twig//2 %d %d %d +index.twig==>index.twig::macro(foo)//1 %d %d %d +EOF + , $dumper->dump($this->getProfile())); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/HtmlTest.php b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/HtmlTest.php new file mode 100644 index 0000000..66a68c4 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/HtmlTest.php @@ -0,0 +1,30 @@ +assertStringMatchesFormat(<<main %d.%dms/%d% +└ index.twig %d.%dms/%d% + └ embedded.twig::block(body) + └ embedded.twig + │ └ included.twig + └ index.twig::macro(foo) + └ embedded.twig + └ included.twig + +EOF + , $dumper->dump($this->getProfile())); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/TextTest.php b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/TextTest.php new file mode 100644 index 0000000..e2ea165 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Profiler/Dumper/TextTest.php @@ -0,0 +1,30 @@ +assertStringMatchesFormat(<<dump($this->getProfile())); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Profiler/ProfileTest.php b/vendor/twig/twig/test/Twig/Tests/Profiler/ProfileTest.php new file mode 100644 index 0000000..08db96a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Profiler/ProfileTest.php @@ -0,0 +1,110 @@ +assertEquals('template', $profile->getTemplate()); + $this->assertEquals('type', $profile->getType()); + $this->assertEquals('name', $profile->getName()); + } + + public function testIsRoot() + { + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::ROOT); + $this->assertTrue($profile->isRoot()); + + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::TEMPLATE); + $this->assertFalse($profile->isRoot()); + } + + public function testIsTemplate() + { + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::TEMPLATE); + $this->assertTrue($profile->isTemplate()); + + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::ROOT); + $this->assertFalse($profile->isTemplate()); + } + + public function testIsBlock() + { + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::BLOCK); + $this->assertTrue($profile->isBlock()); + + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::ROOT); + $this->assertFalse($profile->isBlock()); + } + + public function testIsMacro() + { + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::MACRO); + $this->assertTrue($profile->isMacro()); + + $profile = new Twig_Profiler_Profile('template', Twig_Profiler_Profile::ROOT); + $this->assertFalse($profile->isMacro()); + } + + public function testGetAddProfile() + { + $profile = new Twig_Profiler_Profile(); + $profile->addProfile($a = new Twig_Profiler_Profile()); + $profile->addProfile($b = new Twig_Profiler_Profile()); + + $this->assertSame(array($a, $b), $profile->getProfiles()); + $this->assertSame(array($a, $b), iterator_to_array($profile)); + } + + public function testGetDuration() + { + $profile = new Twig_Profiler_Profile(); + usleep(1); + $profile->leave(); + + $this->assertTrue($profile->getDuration() > 0, sprintf('Expected duration > 0, got: %f', $profile->getDuration())); + } + + public function testSerialize() + { + $profile = new Twig_Profiler_Profile('template', 'type', 'name'); + $profile1 = new Twig_Profiler_Profile('template1', 'type1', 'name1'); + $profile->addProfile($profile1); + $profile->leave(); + $profile1->leave(); + + $profile2 = unserialize(serialize($profile)); + $profiles = $profile->getProfiles(); + $this->assertCount(1, $profiles); + $profile3 = $profiles[0]; + + $this->assertEquals($profile->getTemplate(), $profile2->getTemplate()); + $this->assertEquals($profile->getType(), $profile2->getType()); + $this->assertEquals($profile->getName(), $profile2->getName()); + $this->assertEquals($profile->getDuration(), $profile2->getDuration()); + + $this->assertEquals($profile1->getTemplate(), $profile3->getTemplate()); + $this->assertEquals($profile1->getType(), $profile3->getType()); + $this->assertEquals($profile1->getName(), $profile3->getName()); + } + + public function testReset() + { + $profile = new Twig_Profiler_Profile(); + usleep(1); + $profile->leave(); + $profile->reset(); + + $this->assertEquals(0, $profile->getDuration()); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/TemplateTest.php b/vendor/twig/twig/test/Twig/Tests/TemplateTest.php new file mode 100644 index 0000000..336fc1f --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/TemplateTest.php @@ -0,0 +1,762 @@ +getMockForAbstractClass('Twig_Template', array(), '', false); + $template->displayBlock('foo', array(), array('foo' => array(new stdClass(), 'foo'))); + } + + /** + * @dataProvider getAttributeExceptions + */ + public function testGetAttributeExceptions($template, $message) + { + $templates = array('index' => $template); + $env = new Twig_Environment(new Twig_Loader_Array($templates), array('strict_variables' => true)); + $template = $env->loadTemplate('index'); + + $context = array( + 'string' => 'foo', + 'null' => null, + 'empty_array' => array(), + 'array' => array('foo' => 'foo'), + 'array_access' => new Twig_TemplateArrayAccessObject(), + 'magic_exception' => new Twig_TemplateMagicPropertyObjectWithException(), + 'object' => new stdClass(), + ); + + try { + $template->render($context); + $this->fail('Accessing an invalid attribute should throw an exception.'); + } catch (Twig_Error_Runtime $e) { + $this->assertSame(sprintf($message, 'index'), $e->getMessage()); + } + } + + public function getAttributeExceptions() + { + return array( + array('{{ string["a"] }}', 'Impossible to access a key ("a") on a string variable ("foo") in "%s" at line 1.'), + array('{{ null["a"] }}', 'Impossible to access a key ("a") on a null variable in "%s" at line 1.'), + array('{{ empty_array["a"] }}', 'Key "a" does not exist as the array is empty in "%s" at line 1.'), + array('{{ array["a"] }}', 'Key "a" for array with keys "foo" does not exist in "%s" at line 1.'), + array('{{ array_access["a"] }}', 'Key "a" in object with ArrayAccess of class "Twig_TemplateArrayAccessObject" does not exist in "%s" at line 1.'), + array('{{ string.a }}', 'Impossible to access an attribute ("a") on a string variable ("foo") in "%s" at line 1.'), + array('{{ string.a() }}', 'Impossible to invoke a method ("a") on a string variable ("foo") in "%s" at line 1.'), + array('{{ null.a }}', 'Impossible to access an attribute ("a") on a null variable in "%s" at line 1.'), + array('{{ null.a() }}', 'Impossible to invoke a method ("a") on a null variable in "%s" at line 1.'), + array('{{ array.a() }}', 'Impossible to invoke a method ("a") on an array in "%s" at line 1.'), + array('{{ empty_array.a }}', 'Key "a" does not exist as the array is empty in "%s" at line 1.'), + array('{{ array.a }}', 'Key "a" for array with keys "foo" does not exist in "%s" at line 1.'), + array('{{ attribute(array, -10) }}', 'Key "-10" for array with keys "foo" does not exist in "%s" at line 1.'), + array('{{ array_access.a }}', 'Neither the property "a" nor one of the methods "a()", "geta()"/"isa()" or "__call()" exist and have public access in class "Twig_TemplateArrayAccessObject" in "%s" at line 1.'), + array('{% from _self import foo %}{% macro foo(obj) %}{{ obj.missing_method() }}{% endmacro %}{{ foo(array_access) }}', 'Neither the property "missing_method" nor one of the methods "missing_method()", "getmissing_method()"/"ismissing_method()" or "__call()" exist and have public access in class "Twig_TemplateArrayAccessObject" in "%s" at line 1.'), + array('{{ magic_exception.test }}', 'An exception has been thrown during the rendering of a template ("Hey! Don\'t try to isset me!") in "%s" at line 1.'), + array('{{ object["a"] }}', 'Impossible to access a key "a" on an object of class "stdClass" that does not implement ArrayAccess interface in "%s" at line 1.'), + ); + } + + /** + * @dataProvider getGetAttributeWithSandbox + */ + public function testGetAttributeWithSandbox($object, $item, $allowed) + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + $policy = new Twig_Sandbox_SecurityPolicy(array(), array(), array(/*method*/), array(/*prop*/), array()); + $twig->addExtension(new Twig_Extension_Sandbox($policy, !$allowed)); + $template = new Twig_TemplateTest($twig); + + try { + $template->getAttribute($object, $item, array(), 'any'); + + if (!$allowed) { + $this->fail(); + } else { + $this->addToAssertionCount(1); + } + } catch (Twig_Sandbox_SecurityError $e) { + if ($allowed) { + $this->fail(); + } else { + $this->addToAssertionCount(1); + } + + $this->assertContains('is not allowed', $e->getMessage()); + } + } + + public function getGetAttributeWithSandbox() + { + return array( + array(new Twig_TemplatePropertyObject(), 'defined', false), + array(new Twig_TemplatePropertyObject(), 'defined', true), + array(new Twig_TemplateMethodObject(), 'defined', false), + array(new Twig_TemplateMethodObject(), 'defined', true), + ); + } + + /** + * @group legacy + */ + public function testGetAttributeWithTemplateAsObject() + { + // to be removed in 2.0 + $twig = new Twig_Environment($this->getMockBuilder('Twig_TemplateTestLoaderInterface')->getMock()); + //$twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface', 'Twig_SourceContextLoaderInterface')->getMock()); + + $template = new Twig_TemplateTest($twig, 'index.twig'); + $template1 = new Twig_TemplateTest($twig, 'index1.twig'); + + $this->assertInstanceof('Twig_Markup', $template->getAttribute($template1, 'string')); + $this->assertEquals('some_string', $template->getAttribute($template1, 'string')); + + $this->assertInstanceof('Twig_Markup', $template->getAttribute($template1, 'true')); + $this->assertEquals('1', $template->getAttribute($template1, 'true')); + + $this->assertInstanceof('Twig_Markup', $template->getAttribute($template1, 'zero')); + $this->assertEquals('0', $template->getAttribute($template1, 'zero')); + + $this->assertNotInstanceof('Twig_Markup', $template->getAttribute($template1, 'empty')); + $this->assertSame('', $template->getAttribute($template1, 'empty')); + + $this->assertFalse($template->getAttribute($template1, 'env', array(), Twig_Template::ANY_CALL, true)); + $this->assertFalse($template->getAttribute($template1, 'environment', array(), Twig_Template::ANY_CALL, true)); + $this->assertFalse($template->getAttribute($template1, 'getEnvironment', array(), Twig_Template::METHOD_CALL, true)); + $this->assertFalse($template->getAttribute($template1, 'displayWithErrorHandling', array(), Twig_Template::METHOD_CALL, true)); + } + + /** + * @group legacy + * @expectedDeprecation Calling "string" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "string" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "true" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "true" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "zero" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "zero" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "empty" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "empty" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. + * @expectedDeprecation Calling "renderBlock" on template "index.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use block("name") instead). + * @expectedDeprecation Calling "displayBlock" on template "index.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use block("name") instead). + * @expectedDeprecation Calling "hasBlock" on template "index.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use "block("name") is defined" instead). + * @expectedDeprecation Calling "render" on template "index.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use include("index.twig") instead). + * @expectedDeprecation Calling "display" on template "index.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use include("index.twig") instead). + * @expectedDeprecation Calling "renderBlock" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use block("name", template) instead). + * @expectedDeprecation Calling "displayBlock" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use block("name", template) instead). + * @expectedDeprecation Calling "hasBlock" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use "block("name", template) is defined" instead). + * @expectedDeprecation Calling "render" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use include("index1.twig") instead). + * @expectedDeprecation Calling "display" on template "index1.twig" from template "index.twig" is deprecated since version 1.28 and won't be supported anymore in 2.0. Use include("index1.twig") instead). + */ + public function testGetAttributeWithTemplateAsObjectForDeprecations() + { + // to be removed in 2.0 + $twig = new Twig_Environment($this->getMockBuilder('Twig_TemplateTestLoaderInterface')->getMock()); + //$twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface', 'Twig_SourceContextLoaderInterface')->getMock()); + + $template = new Twig_TemplateTest($twig, 'index.twig'); + $template1 = new Twig_TemplateTest($twig, 'index1.twig'); + + $this->assertInstanceof('Twig_Markup', $template->getAttribute($template1, 'string')); + $this->assertEquals('some_string', $template->getAttribute($template1, 'string')); + + $this->assertInstanceof('Twig_Markup', $template->getAttribute($template1, 'true')); + $this->assertEquals('1', $template->getAttribute($template1, 'true')); + + $this->assertInstanceof('Twig_Markup', $template->getAttribute($template1, 'zero')); + $this->assertEquals('0', $template->getAttribute($template1, 'zero')); + + $this->assertNotInstanceof('Twig_Markup', $template->getAttribute($template1, 'empty')); + $this->assertSame('', $template->getAttribute($template1, 'empty')); + + $blocks = array('name' => array($template1, 'block_name')); + + // trigger some deprecation notice messages to check them with @expectedDeprecation + $template->getAttribute($template, 'renderBlock', array('name', array(), $blocks)); + $template->getAttribute($template, 'displayBlock', array('name', array(), $blocks)); + $template->getAttribute($template, 'hasBlock', array('name', array())); + $template->getAttribute($template, 'render', array(array())); + $template->getAttribute($template, 'display', array(array())); + + $template->getAttribute($template1, 'renderBlock', array('name', array(), $blocks)); + $template->getAttribute($template1, 'displayBlock', array('name', array(), $blocks)); + $template->getAttribute($template1, 'hasBlock', array('name', array())); + $template->getAttribute($template1, 'render', array(array())); + $template->getAttribute($template1, 'display', array(array())); + + $this->assertFalse($template->getAttribute($template1, 'env', array(), Twig_Template::ANY_CALL, true)); + $this->assertFalse($template->getAttribute($template1, 'environment', array(), Twig_Template::ANY_CALL, true)); + $this->assertFalse($template->getAttribute($template1, 'getEnvironment', array(), Twig_Template::METHOD_CALL, true)); + $this->assertFalse($template->getAttribute($template1, 'displayWithErrorHandling', array(), Twig_Template::METHOD_CALL, true)); + } + + /** + * @group legacy + * @expectedDeprecation Silent display of undefined block "unknown" in template "index.twig" is deprecated since version 1.29 and will throw an exception in 2.0. Use the "block('unknown') is defined" expression to test for block existence. + * @expectedDeprecation Silent display of undefined block "unknown" in template "index.twig" is deprecated since version 1.29 and will throw an exception in 2.0. Use the "block('unknown') is defined" expression to test for block existence. + */ + public function testRenderBlockWithUndefinedBlock() + { + $twig = new Twig_Environment($this->getMockBuilder('Twig_TemplateTestLoaderInterface')->getMock()); + + $template = new Twig_TemplateTest($twig, 'index.twig'); + $template->renderBlock('unknown', array()); + $template->displayBlock('unknown', array()); + } + + public function testGetAttributeOnArrayWithConfusableKey() + { + $template = new Twig_TemplateTest(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + + $array = array('Zero', 'One', -1 => 'MinusOne', '' => 'EmptyString', '1.5' => 'FloatButString', '01' => 'IntegerButStringWithLeadingZeros'); + + $this->assertSame('Zero', $array[false]); + $this->assertSame('One', $array[true]); + $this->assertSame('One', $array[1.5]); + $this->assertSame('One', $array['1']); + $this->assertSame('MinusOne', $array[-1.5]); + $this->assertSame('FloatButString', $array['1.5']); + $this->assertSame('IntegerButStringWithLeadingZeros', $array['01']); + $this->assertSame('EmptyString', $array[null]); + + $this->assertSame('Zero', $template->getAttribute($array, false), 'false is treated as 0 when accessing an array (equals PHP behavior)'); + $this->assertSame('One', $template->getAttribute($array, true), 'true is treated as 1 when accessing an array (equals PHP behavior)'); + $this->assertSame('One', $template->getAttribute($array, 1.5), 'float is casted to int when accessing an array (equals PHP behavior)'); + $this->assertSame('One', $template->getAttribute($array, '1'), '"1" is treated as integer 1 when accessing an array (equals PHP behavior)'); + $this->assertSame('MinusOne', $template->getAttribute($array, -1.5), 'negative float is casted to int when accessing an array (equals PHP behavior)'); + $this->assertSame('FloatButString', $template->getAttribute($array, '1.5'), '"1.5" is treated as-is when accessing an array (equals PHP behavior)'); + $this->assertSame('IntegerButStringWithLeadingZeros', $template->getAttribute($array, '01'), '"01" is treated as-is when accessing an array (equals PHP behavior)'); + $this->assertSame('EmptyString', $template->getAttribute($array, null), 'null is treated as "" when accessing an array (equals PHP behavior)'); + } + + /** + * @dataProvider getGetAttributeTests + */ + public function testGetAttribute($defined, $value, $object, $item, $arguments, $type) + { + $template = new Twig_TemplateTest(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + + $this->assertEquals($value, $template->getAttribute($object, $item, $arguments, $type)); + } + + /** + * @dataProvider getGetAttributeTests + */ + public function testGetAttributeStrict($defined, $value, $object, $item, $arguments, $type, $exceptionMessage = null) + { + $template = new Twig_TemplateTest(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true))); + + if ($defined) { + $this->assertEquals($value, $template->getAttribute($object, $item, $arguments, $type)); + } else { + if (method_exists($this, 'expectException')) { + $this->expectException('Twig_Error_Runtime'); + if (null !== $exceptionMessage) { + $this->expectExceptionMessage($exceptionMessage); + } + } else { + $this->setExpectedException('Twig_Error_Runtime', $exceptionMessage); + } + $this->assertEquals($value, $template->getAttribute($object, $item, $arguments, $type)); + } + } + + /** + * @dataProvider getGetAttributeTests + */ + public function testGetAttributeDefined($defined, $value, $object, $item, $arguments, $type) + { + $template = new Twig_TemplateTest(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + + $this->assertEquals($defined, $template->getAttribute($object, $item, $arguments, $type, true)); + } + + /** + * @dataProvider getGetAttributeTests + */ + public function testGetAttributeDefinedStrict($defined, $value, $object, $item, $arguments, $type) + { + $template = new Twig_TemplateTest(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true))); + + $this->assertEquals($defined, $template->getAttribute($object, $item, $arguments, $type, true)); + } + + public function testGetAttributeCallExceptions() + { + $template = new Twig_TemplateTest(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); + + $object = new Twig_TemplateMagicMethodExceptionObject(); + + $this->assertNull($template->getAttribute($object, 'foo')); + } + + public function getGetAttributeTests() + { + $array = array( + 'defined' => 'defined', + 'zero' => 0, + 'null' => null, + '1' => 1, + 'bar' => true, + 'baz' => 'baz', + '09' => '09', + '+4' => '+4', + ); + + $objectArray = new Twig_TemplateArrayAccessObject(); + $stdObject = (object) $array; + $magicPropertyObject = new Twig_TemplateMagicPropertyObject(); + $propertyObject = new Twig_TemplatePropertyObject(); + $propertyObject1 = new Twig_TemplatePropertyObjectAndIterator(); + $propertyObject2 = new Twig_TemplatePropertyObjectAndArrayAccess(); + $propertyObject3 = new Twig_TemplatePropertyObjectDefinedWithUndefinedValue(); + $methodObject = new Twig_TemplateMethodObject(); + $magicMethodObject = new Twig_TemplateMagicMethodObject(); + + $anyType = Twig_Template::ANY_CALL; + $methodType = Twig_Template::METHOD_CALL; + $arrayType = Twig_Template::ARRAY_CALL; + + $basicTests = array( + // array(defined, value, property to fetch) + array(true, 'defined', 'defined'), + array(false, null, 'undefined'), + array(false, null, 'protected'), + array(true, 0, 'zero'), + array(true, 1, 1), + array(true, 1, 1.0), + array(true, null, 'null'), + array(true, true, 'bar'), + array(true, 'baz', 'baz'), + array(true, '09', '09'), + array(true, '+4', '+4'), + ); + $testObjects = array( + // array(object, type of fetch) + array($array, $arrayType), + array($objectArray, $arrayType), + array($stdObject, $anyType), + array($magicPropertyObject, $anyType), + array($methodObject, $methodType), + array($methodObject, $anyType), + array($propertyObject, $anyType), + array($propertyObject1, $anyType), + array($propertyObject2, $anyType), + ); + + $tests = array(); + foreach ($testObjects as $testObject) { + foreach ($basicTests as $test) { + // properties cannot be numbers + if (($testObject[0] instanceof stdClass || $testObject[0] instanceof Twig_TemplatePropertyObject) && is_numeric($test[2])) { + continue; + } + + if ('+4' === $test[2] && $methodObject === $testObject[0]) { + continue; + } + + $tests[] = array($test[0], $test[1], $testObject[0], $test[2], array(), $testObject[1]); + } + } + + // additional properties tests + $tests = array_merge($tests, array( + array(true, null, $propertyObject3, 'foo', array(), $anyType), + )); + + // additional method tests + $tests = array_merge($tests, array( + array(true, 'defined', $methodObject, 'defined', array(), $methodType), + array(true, 'defined', $methodObject, 'DEFINED', array(), $methodType), + array(true, 'defined', $methodObject, 'getDefined', array(), $methodType), + array(true, 'defined', $methodObject, 'GETDEFINED', array(), $methodType), + array(true, 'static', $methodObject, 'static', array(), $methodType), + array(true, 'static', $methodObject, 'getStatic', array(), $methodType), + + array(true, '__call_undefined', $magicMethodObject, 'undefined', array(), $methodType), + array(true, '__call_UNDEFINED', $magicMethodObject, 'UNDEFINED', array(), $methodType), + )); + + // add the same tests for the any type + foreach ($tests as $test) { + if ($anyType !== $test[5]) { + $test[5] = $anyType; + $tests[] = $test; + } + } + + $methodAndPropObject = new Twig_TemplateMethodAndPropObject(); + + // additional method tests + $tests = array_merge($tests, array( + array(true, 'a', $methodAndPropObject, 'a', array(), $anyType), + array(true, 'a', $methodAndPropObject, 'a', array(), $methodType), + array(false, null, $methodAndPropObject, 'a', array(), $arrayType), + + array(true, 'b_prop', $methodAndPropObject, 'b', array(), $anyType), + array(true, 'b', $methodAndPropObject, 'B', array(), $anyType), + array(true, 'b', $methodAndPropObject, 'b', array(), $methodType), + array(true, 'b', $methodAndPropObject, 'B', array(), $methodType), + array(false, null, $methodAndPropObject, 'b', array(), $arrayType), + + array(false, null, $methodAndPropObject, 'c', array(), $anyType), + array(false, null, $methodAndPropObject, 'c', array(), $methodType), + array(false, null, $methodAndPropObject, 'c', array(), $arrayType), + )); + + // tests when input is not an array or object + $tests = array_merge($tests, array( + array(false, null, 42, 'a', array(), $anyType, 'Impossible to access an attribute ("a") on a integer variable ("42") in "index.twig".'), + array(false, null, 'string', 'a', array(), $anyType, 'Impossible to access an attribute ("a") on a string variable ("string") in "index.twig".'), + array(false, null, array(), 'a', array(), $anyType, 'Key "a" does not exist as the array is empty in "index.twig".'), + )); + + return $tests; + } + + /** + * @expectedException Twig_Error_Runtime + */ + public function testGetIsMethods() + { + $getIsObject = new Twig_TemplateGetIsMethods(); + $template = new Twig_TemplateTest(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true))); + // first time should not create a cache for "get" + $this->assertNull($template->getAttribute($getIsObject, 'get')); + // 0 should be in the method cache now, so this should fail + $this->assertNull($template->getAttribute($getIsObject, 0)); + } +} + +class Twig_TemplateTest extends Twig_Template +{ + private $name; + + public function __construct(Twig_Environment $env, $name = 'index.twig') + { + parent::__construct($env); + self::$cache = array(); + $this->name = $name; + } + + public function getZero() + { + return 0; + } + + public function getEmpty() + { + return ''; + } + + public function getString() + { + return 'some_string'; + } + + public function getTrue() + { + return true; + } + + public function getTemplateName() + { + return $this->name; + } + + public function getDebugInfo() + { + return array(); + } + + protected function doGetParent(array $context) + { + return false; + } + + protected function doDisplay(array $context, array $blocks = array()) + { + } + + public function getAttribute($object, $item, array $arguments = array(), $type = Twig_Template::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false) + { + if (function_exists('twig_template_get_attributes')) { + return twig_template_get_attributes($this, $object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck); + } else { + return parent::getAttribute($object, $item, $arguments, $type, $isDefinedTest, $ignoreStrictCheck); + } + } + + public function block_name($context, array $blocks = array()) + { + } +} + +class Twig_TemplateArrayAccessObject implements ArrayAccess +{ + protected $protected = 'protected'; + + public $attributes = array( + 'defined' => 'defined', + 'zero' => 0, + 'null' => null, + '1' => 1, + 'bar' => true, + 'baz' => 'baz', + '09' => '09', + '+4' => '+4', + ); + + public function offsetExists($name) + { + return array_key_exists($name, $this->attributes); + } + + public function offsetGet($name) + { + return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : null; + } + + public function offsetSet($name, $value) + { + } + + public function offsetUnset($name) + { + } +} + +class Twig_TemplateMagicPropertyObject +{ + public $defined = 'defined'; + + public $attributes = array( + 'zero' => 0, + 'null' => null, + '1' => 1, + 'bar' => true, + 'baz' => 'baz', + '09' => '09', + '+4' => '+4', + ); + + protected $protected = 'protected'; + + public function __isset($name) + { + return array_key_exists($name, $this->attributes); + } + + public function __get($name) + { + return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : null; + } +} + +class Twig_TemplateMagicPropertyObjectWithException +{ + public function __isset($key) + { + throw new Exception('Hey! Don\'t try to isset me!'); + } +} + +class Twig_TemplatePropertyObject +{ + public $defined = 'defined'; + public $zero = 0; + public $null = null; + public $bar = true; + public $baz = 'baz'; + + protected $protected = 'protected'; +} + +class Twig_TemplatePropertyObjectAndIterator extends Twig_TemplatePropertyObject implements IteratorAggregate +{ + public function getIterator() + { + return new ArrayIterator(array('foo', 'bar')); + } +} + +class Twig_TemplatePropertyObjectAndArrayAccess extends Twig_TemplatePropertyObject implements ArrayAccess +{ + private $data = array( + 'defined' => 'defined', + 'zero' => 0, + 'null' => null, + 'bar' => true, + 'baz' => 'baz', + ); + + public function offsetExists($offset) + { + return array_key_exists($offset, $this->data); + } + + public function offsetGet($offset) + { + return $this->offsetExists($offset) ? $this->data[$offset] : 'n/a'; + } + + public function offsetSet($offset, $value) + { + } + + public function offsetUnset($offset) + { + } +} + +class Twig_TemplatePropertyObjectDefinedWithUndefinedValue +{ + public $foo; + + public function __construct() + { + $this->foo = @$notExist; + } +} + +class Twig_TemplateMethodObject +{ + public function getDefined() + { + return 'defined'; + } + + public function get1() + { + return 1; + } + + public function get09() + { + return '09'; + } + + public function getZero() + { + return 0; + } + + public function getNull() + { + } + + public function isBar() + { + return true; + } + + public function isBaz() + { + return 'should never be returned'; + } + + public function getBaz() + { + return 'baz'; + } + + protected function getProtected() + { + return 'protected'; + } + + public static function getStatic() + { + return 'static'; + } +} + +class Twig_TemplateGetIsMethods +{ + public function get() + { + } + + public function is() + { + } +} + +class Twig_TemplateMethodAndPropObject +{ + private $a = 'a_prop'; + + public function getA() + { + return 'a'; + } + + public $b = 'b_prop'; + + public function getB() + { + return 'b'; + } + + private $c = 'c_prop'; + + private function getC() + { + return 'c'; + } +} + +class Twig_TemplateMagicMethodObject +{ + public function __call($method, $arguments) + { + return '__call_'.$method; + } +} + +class Twig_TemplateMagicMethodExceptionObject +{ + public function __call($method, $arguments) + { + throw new BadMethodCallException(sprintf('Unknown method "%s".', $method)); + } +} + +class CExtDisablingNodeVisitor implements Twig_NodeVisitorInterface +{ + public function enterNode(Twig_NodeInterface $node, Twig_Environment $env) + { + if ($node instanceof Twig_Node_Expression_GetAttr) { + $node->setAttribute('disable_c_ext', true); + } + + return $node; + } + + public function leaveNode(Twig_NodeInterface $node, Twig_Environment $env) + { + return $node; + } + + public function getPriority() + { + return 0; + } +} + +// to be removed in 2.0 +interface Twig_TemplateTestLoaderInterface extends Twig_LoaderInterface, Twig_SourceContextLoaderInterface +{ +} diff --git a/vendor/twig/twig/test/Twig/Tests/TemplateWrapperTest.php b/vendor/twig/twig/test/Twig/Tests/TemplateWrapperTest.php new file mode 100644 index 0000000..cc71052 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/TemplateWrapperTest.php @@ -0,0 +1,64 @@ + '{% block foo %}{% endblock %}', + 'index_with_use' => '{% use "imported" %}{% block foo %}{% endblock %}', + 'index_with_extends' => '{% extends "extended" %}{% block foo %}{% endblock %}', + 'imported' => '{% block imported %}{% endblock %}', + 'extended' => '{% block extended %}{% endblock %}', + ))); + + $wrapper = new Twig_TemplateWrapper($twig, $twig->loadTemplate('index')); + $this->assertTrue($wrapper->hasBlock('foo')); + $this->assertFalse($wrapper->hasBlock('bar')); + $this->assertEquals(array('foo'), $wrapper->getBlockNames()); + + $wrapper = new Twig_TemplateWrapper($twig, $twig->loadTemplate('index_with_use')); + $this->assertTrue($wrapper->hasBlock('foo')); + $this->assertTrue($wrapper->hasBlock('imported')); + $this->assertEquals(array('imported', 'foo'), $wrapper->getBlockNames()); + + $wrapper = new Twig_TemplateWrapper($twig, $twig->loadTemplate('index_with_extends')); + $this->assertTrue($wrapper->hasBlock('foo')); + $this->assertTrue($wrapper->hasBlock('extended')); + $this->assertEquals(array('foo', 'extended'), $wrapper->getBlockNames()); + } + + public function testRenderBlock() + { + $twig = new Twig_Environment(new Twig_Loader_Array(array( + 'index' => '{% block foo %}{{ foo }}{{ bar }}{% endblock %}', + ))); + $twig->addGlobal('bar', 'BAR'); + + $wrapper = new Twig_TemplateWrapper($twig, $twig->loadTemplate('index')); + $this->assertEquals('FOOBAR', $wrapper->renderBlock('foo', array('foo' => 'FOO'))); + } + + public function testDisplayBlock() + { + $twig = new Twig_Environment(new Twig_Loader_Array(array( + 'index' => '{% block foo %}{{ foo }}{{ bar }}{% endblock %}', + ))); + $twig->addGlobal('bar', 'BAR'); + + $wrapper = new Twig_TemplateWrapper($twig, $twig->loadTemplate('index')); + + ob_start(); + $wrapper->displayBlock('foo', array('foo' => 'FOO')); + + $this->assertEquals('FOOBAR', ob_get_clean()); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/TokenStreamTest.php b/vendor/twig/twig/test/Twig/Tests/TokenStreamTest.php new file mode 100644 index 0000000..f219c95 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/TokenStreamTest.php @@ -0,0 +1,82 @@ +assertEquals('foo', $stream->getFilename()); + $this->assertEquals('{{ foo }}', $stream->getSource()); + $this->assertEquals('foo', $stream->getSourceContext()->getName()); + $this->assertEquals('{{ foo }}', $stream->getSourceContext()->getCode()); + } + + public function testNext() + { + $stream = new Twig_TokenStream(self::$tokens); + $repr = array(); + while (!$stream->isEOF()) { + $token = $stream->next(); + + $repr[] = $token->getValue(); + } + $this->assertEquals('1, 2, 3, 4, 5, 6, 7', implode(', ', $repr), '->next() advances the pointer and returns the current token'); + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unexpected end of template + */ + public function testEndOfTemplateNext() + { + $stream = new Twig_TokenStream(array( + new Twig_Token(Twig_Token::BLOCK_START_TYPE, 1, 1), + )); + while (!$stream->isEOF()) { + $stream->next(); + } + } + + /** + * @expectedException Twig_Error_Syntax + * @expectedExceptionMessage Unexpected end of template + */ + public function testEndOfTemplateLook() + { + $stream = new Twig_TokenStream(array( + new Twig_Token(Twig_Token::BLOCK_START_TYPE, 1, 1), + )); + while (!$stream->isEOF()) { + $stream->look(); + $stream->next(); + } + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/Util/DeprecationCollectorTest.php b/vendor/twig/twig/test/Twig/Tests/Util/DeprecationCollectorTest.php new file mode 100644 index 0000000..887a90a --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/Util/DeprecationCollectorTest.php @@ -0,0 +1,42 @@ +getMockBuilder('Twig_LoaderInterface')->getMock()); + $twig->addFunction(new Twig_SimpleFunction('deprec', array($this, 'deprec'), array('deprecated' => true))); + + $collector = new Twig_Util_DeprecationCollector($twig); + $deprecations = $collector->collect(new Twig_Tests_Util_Iterator()); + + $this->assertEquals(array('Twig Function "deprec" is deprecated in deprec.twig at line 1.'), $deprecations); + } + + public function deprec() + { + } +} + +class Twig_Tests_Util_Iterator implements IteratorAggregate +{ + public function getIterator() + { + return new ArrayIterator(array( + 'ok.twig' => '{{ foo }}', + 'deprec.twig' => '{{ deprec("foo") }}', + )); + } +} diff --git a/vendor/twig/twig/test/Twig/Tests/escapingTest.php b/vendor/twig/twig/test/Twig/Tests/escapingTest.php new file mode 100644 index 0000000..12ebd13 --- /dev/null +++ b/vendor/twig/twig/test/Twig/Tests/escapingTest.php @@ -0,0 +1,325 @@ + ''', + '"' => '"', + '<' => '<', + '>' => '>', + '&' => '&', + ); + + protected $htmlAttrSpecialChars = array( + '\'' => ''', + /* Characters beyond ASCII value 255 to unicode escape */ + 'Ā' => 'Ā', + '😀' => '😀', + /* Immune chars excluded */ + ',' => ',', + '.' => '.', + '-' => '-', + '_' => '_', + /* Basic alnums excluded */ + 'a' => 'a', + 'A' => 'A', + 'z' => 'z', + 'Z' => 'Z', + '0' => '0', + '9' => '9', + /* Basic control characters and null */ + "\r" => ' ', + "\n" => ' ', + "\t" => ' ', + "\0" => '�', // should use Unicode replacement char + /* Encode chars as named entities where possible */ + '<' => '<', + '>' => '>', + '&' => '&', + '"' => '"', + /* Encode spaces for quoteless attribute protection */ + ' ' => ' ', + ); + + protected $jsSpecialChars = array( + /* HTML special chars - escape without exception to hex */ + '<' => '\\u003C', + '>' => '\\u003E', + '\'' => '\\u0027', + '"' => '\\u0022', + '&' => '\\u0026', + '/' => '\\/', + /* Characters beyond ASCII value 255 to unicode escape */ + 'Ā' => '\\u0100', + '😀' => '\\uD83D\\uDE00', + /* Immune chars excluded */ + ',' => ',', + '.' => '.', + '_' => '_', + /* Basic alnums excluded */ + 'a' => 'a', + 'A' => 'A', + 'z' => 'z', + 'Z' => 'Z', + '0' => '0', + '9' => '9', + /* Basic control characters and null */ + "\r" => '\r', + "\n" => '\n', + "\x08" => '\b', + "\t" => '\t', + "\x0C" => '\f', + "\0" => '\\u0000', + /* Encode spaces for quoteless attribute protection */ + ' ' => '\\u0020', + ); + + protected $urlSpecialChars = array( + /* HTML special chars - escape without exception to percent encoding */ + '<' => '%3C', + '>' => '%3E', + '\'' => '%27', + '"' => '%22', + '&' => '%26', + /* Characters beyond ASCII value 255 to hex sequence */ + 'Ā' => '%C4%80', + /* Punctuation and unreserved check */ + ',' => '%2C', + '.' => '.', + '_' => '_', + '-' => '-', + ':' => '%3A', + ';' => '%3B', + '!' => '%21', + /* Basic alnums excluded */ + 'a' => 'a', + 'A' => 'A', + 'z' => 'z', + 'Z' => 'Z', + '0' => '0', + '9' => '9', + /* Basic control characters and null */ + "\r" => '%0D', + "\n" => '%0A', + "\t" => '%09', + "\0" => '%00', + /* PHP quirks from the past */ + ' ' => '%20', + '~' => '~', + '+' => '%2B', + ); + + protected $cssSpecialChars = array( + /* HTML special chars - escape without exception to hex */ + '<' => '\\3C ', + '>' => '\\3E ', + '\'' => '\\27 ', + '"' => '\\22 ', + '&' => '\\26 ', + /* Characters beyond ASCII value 255 to unicode escape */ + 'Ā' => '\\100 ', + /* Immune chars excluded */ + ',' => '\\2C ', + '.' => '\\2E ', + '_' => '\\5F ', + /* Basic alnums excluded */ + 'a' => 'a', + 'A' => 'A', + 'z' => 'z', + 'Z' => 'Z', + '0' => '0', + '9' => '9', + /* Basic control characters and null */ + "\r" => '\\D ', + "\n" => '\\A ', + "\t" => '\\9 ', + "\0" => '\\0 ', + /* Encode spaces for quoteless attribute protection */ + ' ' => '\\20 ', + ); + + protected $env; + + protected function setUp() + { + $this->env = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); + } + + public function testHtmlEscapingConvertsSpecialChars() + { + foreach ($this->htmlSpecialChars as $key => $value) { + $this->assertEquals($value, twig_escape_filter($this->env, $key, 'html'), 'Failed to escape: '.$key); + } + } + + public function testHtmlAttributeEscapingConvertsSpecialChars() + { + foreach ($this->htmlAttrSpecialChars as $key => $value) { + $this->assertEquals($value, twig_escape_filter($this->env, $key, 'html_attr'), 'Failed to escape: '.$key); + } + } + + public function testJavascriptEscapingConvertsSpecialChars() + { + foreach ($this->jsSpecialChars as $key => $value) { + $this->assertEquals($value, twig_escape_filter($this->env, $key, 'js'), 'Failed to escape: '.$key); + } + } + + public function testJavascriptEscapingReturnsStringIfZeroLength() + { + $this->assertEquals('', twig_escape_filter($this->env, '', 'js')); + } + + public function testJavascriptEscapingReturnsStringIfContainsOnlyDigits() + { + $this->assertEquals('123', twig_escape_filter($this->env, '123', 'js')); + } + + public function testCssEscapingConvertsSpecialChars() + { + foreach ($this->cssSpecialChars as $key => $value) { + $this->assertEquals($value, twig_escape_filter($this->env, $key, 'css'), 'Failed to escape: '.$key); + } + } + + public function testCssEscapingReturnsStringIfZeroLength() + { + $this->assertEquals('', twig_escape_filter($this->env, '', 'css')); + } + + public function testCssEscapingReturnsStringIfContainsOnlyDigits() + { + $this->assertEquals('123', twig_escape_filter($this->env, '123', 'css')); + } + + public function testUrlEscapingConvertsSpecialChars() + { + foreach ($this->urlSpecialChars as $key => $value) { + $this->assertEquals($value, twig_escape_filter($this->env, $key, 'url'), 'Failed to escape: '.$key); + } + } + + /** + * Range tests to confirm escaped range of characters is within OWASP recommendation. + */ + + /** + * Only testing the first few 2 ranges on this prot. function as that's all these + * other range tests require. + */ + public function testUnicodeCodepointConversionToUtf8() + { + $expected = ' ~ޙ'; + $codepoints = array(0x20, 0x7e, 0x799); + $result = ''; + foreach ($codepoints as $value) { + $result .= $this->codepointToUtf8($value); + } + $this->assertEquals($expected, $result); + } + + /** + * Convert a Unicode Codepoint to a literal UTF-8 character. + * + * @param int $codepoint Unicode codepoint in hex notation + * + * @return string UTF-8 literal string + */ + protected function codepointToUtf8($codepoint) + { + if ($codepoint < 0x80) { + return chr($codepoint); + } + if ($codepoint < 0x800) { + return chr($codepoint >> 6 & 0x3f | 0xc0) + .chr($codepoint & 0x3f | 0x80); + } + if ($codepoint < 0x10000) { + return chr($codepoint >> 12 & 0x0f | 0xe0) + .chr($codepoint >> 6 & 0x3f | 0x80) + .chr($codepoint & 0x3f | 0x80); + } + if ($codepoint < 0x110000) { + return chr($codepoint >> 18 & 0x07 | 0xf0) + .chr($codepoint >> 12 & 0x3f | 0x80) + .chr($codepoint >> 6 & 0x3f | 0x80) + .chr($codepoint & 0x3f | 0x80); + } + throw new Exception('Codepoint requested outside of Unicode range.'); + } + + public function testJavascriptEscapingEscapesOwaspRecommendedRanges() + { + $immune = array(',', '.', '_'); // Exceptions to escaping ranges + for ($chr = 0; $chr < 0xFF; ++$chr) { + if ($chr >= 0x30 && $chr <= 0x39 + || $chr >= 0x41 && $chr <= 0x5A + || $chr >= 0x61 && $chr <= 0x7A) { + $literal = $this->codepointToUtf8($chr); + $this->assertEquals($literal, twig_escape_filter($this->env, $literal, 'js')); + } else { + $literal = $this->codepointToUtf8($chr); + if (in_array($literal, $immune)) { + $this->assertEquals($literal, twig_escape_filter($this->env, $literal, 'js')); + } else { + $this->assertNotEquals( + $literal, + twig_escape_filter($this->env, $literal, 'js'), + "$literal should be escaped!"); + } + } + } + } + + public function testHtmlAttributeEscapingEscapesOwaspRecommendedRanges() + { + $immune = array(',', '.', '-', '_'); // Exceptions to escaping ranges + for ($chr = 0; $chr < 0xFF; ++$chr) { + if ($chr >= 0x30 && $chr <= 0x39 + || $chr >= 0x41 && $chr <= 0x5A + || $chr >= 0x61 && $chr <= 0x7A) { + $literal = $this->codepointToUtf8($chr); + $this->assertEquals($literal, twig_escape_filter($this->env, $literal, 'html_attr')); + } else { + $literal = $this->codepointToUtf8($chr); + if (in_array($literal, $immune)) { + $this->assertEquals($literal, twig_escape_filter($this->env, $literal, 'html_attr')); + } else { + $this->assertNotEquals( + $literal, + twig_escape_filter($this->env, $literal, 'html_attr'), + "$literal should be escaped!"); + } + } + } + } + + public function testCssEscapingEscapesOwaspRecommendedRanges() + { + // CSS has no exceptions to escaping ranges + for ($chr = 0; $chr < 0xFF; ++$chr) { + if ($chr >= 0x30 && $chr <= 0x39 + || $chr >= 0x41 && $chr <= 0x5A + || $chr >= 0x61 && $chr <= 0x7A) { + $literal = $this->codepointToUtf8($chr); + $this->assertEquals($literal, twig_escape_filter($this->env, $literal, 'css')); + } else { + $literal = $this->codepointToUtf8($chr); + $this->assertNotEquals( + $literal, + twig_escape_filter($this->env, $literal, 'css'), + "$literal should be escaped!"); + } + } + } +}