pax_global_header00006660000000000000000000000064132465457450014531gustar00rootroot0000000000000052 comment=d2117ec118c1ff3d28ccddca8212d82787a4809f Twig-2.4.6/000077500000000000000000000000001324654574500124545ustar00rootroot00000000000000Twig-2.4.6/.editorconfig000066400000000000000000000003401324654574500151260ustar00rootroot00000000000000; 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 Twig-2.4.6/.gitignore000066400000000000000000000000441324654574500144420ustar00rootroot00000000000000/composer.lock /phpunit.xml /vendor Twig-2.4.6/.php_cs.dist000066400000000000000000000007371324654574500147020ustar00rootroot00000000000000setRules(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, )) ->setRiskyAllowed(true) ->setFinder(PhpCsFixer\Finder::create()->in(__DIR__)) ; Twig-2.4.6/.travis.yml000066400000000000000000000010671324654574500145710ustar00rootroot00000000000000language: php sudo: false cache: directories: - vendor - $HOME/.composer/cache/files matrix: include: - php: 7.0 - php: 7.1 - php: 7.2 - php: nightly fast_finish: true before_install: # turn off XDebug - phpenv config-rm xdebug.ini || return 0 install: - travis_retry composer install script: | if [[ $TRAVIS_PHP_VERSION = 7.* || $TRAVIS_PHP_VERSION = nightly ]]; then SYMFONY_PHPUNIT_VERSION=6.1 ./vendor/bin/simple-phpunit else ./vendor/bin/simple-phpunit fi Twig-2.4.6/CHANGELOG000066400000000000000000001363111324654574500136730ustar00rootroot00000000000000* 2.4.6 (2018-03-03) * fixed a regression in the way the profiler is registered in templates * 2.4.5 (2018-03-02) * optimized the performance of calling an extension method at runtime * optimized the performance of the dot operator for array and method calls * 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 * 2.4.4 (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 * added support for runtime loaders in IntegrationTestCase * fixed deprecation when using Twig_Profiler_Dumper_Html * removed @final from Twig_Profiler_Dumper_Text * 2.4.3 (2017-06-07) * fixed namespaces introduction * 2.4.2 (2017-06-05) * fixed namespaces introduction * 2.4.1 (2017-06-05) * fixed namespaces introduction * 2.4.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 * dropped HHVM support * added namespaced aliases for all (non-deprecated) classes and interfaces * marked Twig_Filter, Twig_Function, Twig_Test, Twig_Node_Module and Twig_Profiler_Profile as final via the @final annotation * 2.3.2 (2017-04-20) * fixed edge case in the method cache for Twig attributes * 2.3.1 (2017-04-18) * fixed the empty() test * 2.3.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 * added error message when calling `parent()` in a block that doesn't exist in the parent template * 2.2.0 (2017-02-26) * added a PSR-11 compatible runtime loader * added `side` argument to `trim` to allow left or right trimming only. * 2.1.0 (2017-01-11) * fixed twig_get_attribute() * added Twig_NodeCaptureInterface for nodes that capture all output * 2.0.0 (2017-01-05) * removed the C extension * moved Twig_Environment::getAttribute() to twig_get_attribute() * removed Twig_Environment::getLexer(), Twig_Environment::getParser(), Twig_Environment::getCompiler() * removed Twig_Compiler::getFilename() * added hasser support in Twig_Template::getAttribute() * sped up the json_encode filter * removed reserved macro names; all names can be used as macro * removed Twig_Template::getEnvironment() * changed _self variable to return the current template name * made the loader a required argument of Twig_Environment constructor * removed Twig_Environment::clearTemplateCache() * removed Twig_Autoloader (use Composer instead) * removed `true` as an equivalent to `html` for the auto-escaping strategy * removed pre-1.8 autoescape tag syntax * dropped support for PHP 5.x * removed the ability to register a global variable after the runtime or the extensions have been initialized * improved the performance of the filesystem loader * removed features that were deprecated in 1.x * 1.35.2 (2018-XX-XX) * 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 Twig-2.4.6/LICENSE000066400000000000000000000027311324654574500134640ustar00rootroot00000000000000Copyright (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. Twig-2.4.6/README.rst000066400000000000000000000007461324654574500141520ustar00rootroot00000000000000Twig, 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: http://twig.sensiolabs.org/documentation Twig-2.4.6/composer.json000066400000000000000000000026231324654574500152010ustar00rootroot00000000000000{ "name": "twig/twig", "type": "library", "description": "Twig, the flexible, fast, and secure template language for PHP", "keywords": ["templating"], "homepage": "http://twig.sensiolabs.org", "license": "BSD-3-Clause", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com", "homepage": "http://fabien.potencier.org", "role": "Lead Developer" }, { "name": "Twig Team", "homepage": "http://twig.sensiolabs.org/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": "^7.0", "symfony/polyfill-mbstring": "~1.0" }, "require-dev": { "symfony/phpunit-bridge": "~3.3@dev", "symfony/debug": "~2.7", "psr/container": "^1.0" }, "autoload": { "psr-0" : { "Twig_" : "lib/" }, "psr-4" : { "Twig\\" : "src/" } }, "autoload-dev": { "psr-0" : { "Twig_Tests_" : "test/" } }, "extra": { "branch-alias": { "dev-master": "2.4-dev" } } } Twig-2.4.6/doc/000077500000000000000000000000001324654574500132215ustar00rootroot00000000000000Twig-2.4.6/doc/advanced.rst000066400000000000000000000671041324654574500155300ustar00rootroot00000000000000Extending Twig ============== 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_Filter('rot13', function ($string) { return str_rot13($string); }); // or a simple PHP function $filter = new Twig_Filter('rot13', 'str_rot13'); // or a class static method $filter = new Twig_Filter('rot13', array('SomeClass', 'rot13Filter')); $filter = new Twig_Filter('rot13', 'SomeClass::rot13Filter'); // or a class method $filter = new Twig_Filter('rot13', array($this, 'rot13Filter')); // the one below needs a runtime implementation (see below for more information) $filter = new Twig_Filter('rot13', array('SomeClass', 'rot13Filter')); The first argument passed to the ``Twig_Filter`` 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_Filter`` class takes an array of options as its last argument:: $filter = new Twig_Filter('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_Filter('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_Filter('rot13', function ($context, $string) { // ... }, array('needs_context' => true)); $filter = new Twig_Filter('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_Filter('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_Filter('somefilter', 'somefilter', array('pre_escape' => 'html', 'is_safe' => array('html'))); Variadic Filters ~~~~~~~~~~~~~~~~ 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_Filter('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_Filter('*_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_Filter('*_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 ~~~~~~~~~~~~~~~~~~ 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_Filter('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_Function``:: $twig = new Twig_Environment($loader); $function = new Twig_Function('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_Test``:: $twig = new Twig_Environment($loader); $test = new Twig_Test('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_Test('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_Test( '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. If you want to pass a variable number of positional or named arguments to the test, set the ``is_variadic`` option to ``true``. Tests also support dynamic name feature as filters and functions. 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: http://github.com/twigphp/Twig-extensions. An extension is a class that implements the following interface:: interface Twig_ExtensionInterface { /** * 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_Filter[] */ public function getFilters(); /** * Returns a list of tests to add to the existing list. * * @return Twig_Test[] */ public function getTests(); /** * Returns a list of functions to add to the existing list. * * @return Twig_Function[] */ 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(); } 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. 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_Function('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_Filter('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_Test('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_Function('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). 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:: Twig comes with a PSR-11 compatible runtime loader (``Twig_ContainerRuntimeLoader``). 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_Function('rot13', array('Project_Twig_RuntimeExtension', 'rot13')), // or new Twig_Function('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_Filter('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_Filter('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`: http://www.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 Twig-2.4.6/doc/api.rst000066400000000000000000000456701324654574500145400ustar00rootroot00000000000000Twig 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/vendor/autoload.php'; $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'); 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')); 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* Sets the default auto-escaping strategy (``name``, ``html``, ``js``, ``css``, ``url``, ``html_attr``, or a PHP callback that takes the template "filename" and returns the escaping strategy to use -- the callback cannot be a function name to avoid collision with built-in escaping strategies); set it to ``false`` to disable auto-escaping. The ``name`` escaping strategy 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`` .......................... ``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`` loader 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 { /** * 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); /** * 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 timestamp $time 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); /** * 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); } The ``isFresh()`` method must return ``true`` if the current cached template is still fresh, given the last modification time, or ``false`` otherwise. The ``getSourceContext()`` method must return an instance of ``Twig_Source``. 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. * *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: .. 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 ~~~~~~~~~~~~~~~~~~ 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. Twig-2.4.6/doc/coding_standards.rst000066400000000000000000000045211324654574500172630ustar00rootroot00000000000000Coding 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 %} Twig-2.4.6/doc/deprecated.rst000066400000000000000000000007401324654574500160540ustar00rootroot00000000000000Deprecated Features =================== This document lists deprecated features in Twig 2.x. Deprecated features are kept for backward compatibility and removed in the next major release (a feature that was deprecated in Twig 2.x is removed in Twig 3.0). Final Classes ------------- The following classes are marked as ``@final`` in Twig 2 and will be final in 3.0: * ``Twig_Node_Module`` * ``Twig_Filter`` * ``Twig_Function`` * ``Twig_Test`` * ``Twig_Profiler_Profile`` Twig-2.4.6/doc/filters/000077500000000000000000000000001324654574500146715ustar00rootroot00000000000000Twig-2.4.6/doc/filters/abs.rst000066400000000000000000000003671324654574500161760ustar00rootroot00000000000000``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`: http://php.net/abs Twig-2.4.6/doc/filters/batch.rst000066400000000000000000000017651324654574500165150ustar00rootroot00000000000000``batch`` ========= 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
a b c
d e f
g No item No item
Arguments --------- * ``size``: The size of the batch; fractional numbers will be rounded up * ``fill``: Used to fill in missing items Twig-2.4.6/doc/filters/capitalize.rst000066400000000000000000000003511324654574500175470ustar00rootroot00000000000000``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' #} Twig-2.4.6/doc/filters/convert_encoding.rst000066400000000000000000000011721324654574500207520ustar00rootroot00000000000000``convert_encoding`` ==================== 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. Arguments --------- * ``to``: The output charset * ``from``: The input charset .. _`iconv`: http://php.net/iconv .. _`mbstring`: http://php.net/mbstring Twig-2.4.6/doc/filters/date.rst000066400000000000000000000050351324654574500163430ustar00rootroot00000000000000``date`` ======== 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'); 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'); Arguments --------- * ``format``: The date format * ``timezone``: The date timezone .. _`strtotime`: http://www.php.net/strtotime .. _`DateTime`: http://www.php.net/DateTime .. _`DateInterval`: http://www.php.net/DateInterval .. _`date`: http://www.php.net/date .. _`DateInterval::format`: http://www.php.net/DateInterval.format Twig-2.4.6/doc/filters/date_modify.rst000066400000000000000000000010431324654574500177050ustar00rootroot00000000000000``date_modify`` =============== 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`: http://www.php.net/strtotime .. _`DateTime`: http://www.php.net/DateTime Twig-2.4.6/doc/filters/default.rst000066400000000000000000000015321324654574500170500ustar00rootroot00000000000000``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 Twig-2.4.6/doc/filters/escape.rst000066400000000000000000000061361324654574500166710ustar00rootroot00000000000000``escape`` ========== 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'); 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`: http://php.net/htmlspecialchars Twig-2.4.6/doc/filters/first.rst000066400000000000000000000006731324654574500165600ustar00rootroot00000000000000``first`` ========= 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`: http://php.net/manual/en/class.traversable.php Twig-2.4.6/doc/filters/format.rst000066400000000000000000000006101324654574500167100ustar00rootroot00000000000000``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`: http://www.php.net/sprintf .. seealso:: :doc:`replace` Twig-2.4.6/doc/filters/index.rst000066400000000000000000000006221324654574500165320ustar00rootroot00000000000000Filters ======= .. 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 Twig-2.4.6/doc/filters/join.rst000066400000000000000000000006551324654574500163700ustar00rootroot00000000000000``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 Twig-2.4.6/doc/filters/json_encode.rst000066400000000000000000000007451324654574500177170ustar00rootroot00000000000000``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')) }}``) .. _`json_encode`: http://php.net/json_encode .. _`json_encode options`: http://www.php.net/manual/en/json.constants.php Twig-2.4.6/doc/filters/keys.rst000066400000000000000000000003331324654574500163750ustar00rootroot00000000000000``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 %} Twig-2.4.6/doc/filters/last.rst000066400000000000000000000006641324654574500163740ustar00rootroot00000000000000``last`` ======== 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`: http://php.net/manual/en/class.traversable.php Twig-2.4.6/doc/filters/length.rst000066400000000000000000000013221324654574500167020ustar00rootroot00000000000000``length`` ========== .. versionadded:: 2.3 Support for the ``__toString()`` magic method has been added in Twig 2.3. 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 %} Twig-2.4.6/doc/filters/lower.rst000066400000000000000000000002301324654574500165460ustar00rootroot00000000000000``lower`` ========= The ``lower`` filter converts a value to lowercase: .. code-block:: jinja {{ 'WELCOME'|lower }} {# outputs 'welcome' #} Twig-2.4.6/doc/filters/merge.rst000066400000000000000000000025241324654574500165250ustar00rootroot00000000000000``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`: http://php.net/array_merge Twig-2.4.6/doc/filters/nl2br.rst000066400000000000000000000005461324654574500164470ustar00rootroot00000000000000``nl2br`` ========= 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. Twig-2.4.6/doc/filters/number_format.rst000066400000000000000000000026621324654574500202710ustar00rootroot00000000000000``number_format`` ================= 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, '.', ','); 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`: http://php.net/number_format Twig-2.4.6/doc/filters/raw.rst000066400000000000000000000022741324654574500162210ustar00rootroot00000000000000``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. Twig-2.4.6/doc/filters/replace.rst000066400000000000000000000011411324654574500170330ustar00rootroot00000000000000``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` Twig-2.4.6/doc/filters/reverse.rst000066400000000000000000000017351324654574500171040ustar00rootroot00000000000000``reverse`` =========== 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`: http://php.net/Traversable Twig-2.4.6/doc/filters/round.rst000066400000000000000000000014201324654574500165470ustar00rootroot00000000000000``round`` ========= 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 Twig-2.4.6/doc/filters/slice.rst000066400000000000000000000041121324654574500165200ustar00rootroot00000000000000``slice`` =========== 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`: http://php.net/manual/en/class.traversable.php .. _`array_slice`: http://php.net/array_slice .. _`mb_substr` : http://php.net/mb-substr .. _`substr`: http://php.net/substr Twig-2.4.6/doc/filters/sort.rst000066400000000000000000000005301324654574500164100ustar00rootroot00000000000000``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`: http://php.net/asort Twig-2.4.6/doc/filters/split.rst000066400000000000000000000024711324654574500165620ustar00rootroot00000000000000``split`` ========= 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`: http://php.net/explode .. _`str_split`: http://php.net/str_split Twig-2.4.6/doc/filters/striptags.rst000066400000000000000000000011221324654574500174370ustar00rootroot00000000000000``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`: http://php.net/strip_tags Twig-2.4.6/doc/filters/title.rst000066400000000000000000000003771324654574500165530ustar00rootroot00000000000000``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' #} Twig-2.4.6/doc/filters/trim.rst000066400000000000000000000015511324654574500164000ustar00rootroot00000000000000``trim`` ======== 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`: http://php.net/trim .. _`ltrim`: http://php.net/ltrim .. _`rtrim`: http://php.net/rtrim Twig-2.4.6/doc/filters/upper.rst000066400000000000000000000002301324654574500165510ustar00rootroot00000000000000``upper`` ========= The ``upper`` filter converts a value to uppercase: .. code-block:: jinja {{ 'welcome'|upper }} {# outputs 'WELCOME' #} Twig-2.4.6/doc/filters/url_encode.rst000066400000000000000000000010171324654574500175410ustar00rootroot00000000000000``url_encode`` ============== 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 ``rawurlencode``. .. _`rawurlencode`: http://php.net/rawurlencode Twig-2.4.6/doc/functions/000077500000000000000000000000001324654574500152315ustar00rootroot00000000000000Twig-2.4.6/doc/functions/attribute.rst000066400000000000000000000011341324654574500177650ustar00rootroot00000000000000``attribute`` ============= 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. Twig-2.4.6/doc/functions/block.rst000066400000000000000000000014271324654574500170610ustar00rootroot00000000000000``block`` ========= 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>` Twig-2.4.6/doc/functions/constant.rst000066400000000000000000000007471324654574500176240ustar00rootroot00000000000000``constant`` ============ ``constant`` returns the constant value for a given string: .. code-block:: jinja {{ some_date|date(constant('DATE_W3C')) }} {{ constant('Namespace\\Classname::CONSTANT_NAME') }} 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 %} Twig-2.4.6/doc/functions/cycle.rst000066400000000000000000000010441324654574500170610ustar00rootroot00000000000000``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 Twig-2.4.6/doc/functions/date.rst000066400000000000000000000020441324654574500167000ustar00rootroot00000000000000``date`` ======== 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'); Arguments --------- * ``date``: The date * ``timezone``: The timezone .. _`date and time formats`: http://php.net/manual/en/datetime.formats.php Twig-2.4.6/doc/functions/dump.rst000066400000000000000000000030441324654574500167310ustar00rootroot00000000000000``dump`` ======== 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`: http://xdebug.org/docs/display .. _`var_dump`: http://php.net/var_dump Twig-2.4.6/doc/functions/include.rst000066400000000000000000000043711324654574500174130ustar00rootroot00000000000000``include`` =========== 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) }} $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 Twig-2.4.6/doc/functions/index.rst000066400000000000000000000003251324654574500170720ustar00rootroot00000000000000Functions ========= .. toctree:: :maxdepth: 1 attribute block constant cycle date dump include max min parent random range source template_from_string Twig-2.4.6/doc/functions/max.rst000066400000000000000000000005141324654574500165500ustar00rootroot00000000000000``max`` ======= ``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" #} Twig-2.4.6/doc/functions/min.rst000066400000000000000000000005131324654574500165450ustar00rootroot00000000000000``min`` ======= ``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" #} Twig-2.4.6/doc/functions/parent.rst000066400000000000000000000010631324654574500172540ustar00rootroot00000000000000``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>` Twig-2.4.6/doc/functions/random.rst000066400000000000000000000012771324654574500172520ustar00rootroot00000000000000``random`` ========== 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`: http://php.net/mt_rand Twig-2.4.6/doc/functions/range.rst000066400000000000000000000023051324654574500170570ustar00rootroot00000000000000``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`: http://php.net/range Twig-2.4.6/doc/functions/source.rst000066400000000000000000000012661324654574500172700ustar00rootroot00000000000000``source`` ========== 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 Twig-2.4.6/doc/functions/template_from_string.rst000066400000000000000000000015431324654574500222120ustar00rootroot00000000000000``template_from_string`` ======================== 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 Twig-2.4.6/doc/index.rst000066400000000000000000000003341324654574500150620ustar00rootroot00000000000000Twig ==== .. toctree:: :maxdepth: 2 intro installation templates api advanced internals recipes coding_standards tags/index filters/index functions/index tests/index Twig-2.4.6/doc/installation.rst000066400000000000000000000016131324654574500164550ustar00rootroot00000000000000Installation ============ 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:~2.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 .. _`download page`: https://github.com/twigphp/Twig/tags .. _`Composer`: https://getcomposer.org/download/ Twig-2.4.6/doc/internals.rst000066400000000000000000000105631324654574500157570ustar00rootroot00000000000000Twig 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``: 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)); 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); Twig-2.4.6/doc/intro.rst000066400000000000000000000047151324654574500151150ustar00rootroot00000000000000Introduction ============ 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 7.0.0** to run. Installation ------------ The recommended way to install Twig is via Composer: .. code-block:: bash composer require "twig/twig:^2.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')); Twig-2.4.6/doc/recipes.rst000066400000000000000000000420771324654574500154170ustar00rootroot00000000000000Recipes ======= .. _deprecation-notices: Displaying Deprecation Notices ------------------------------ 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: http://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_Function($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 } } .. 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), // ... )); 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_Node $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 { protected $dbh; public function __construct(PDO $dbh) { $this->dbh = $dbh; } 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); } 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 (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()``:: $template = $twig->createTemplate('hello {{ name }}'); echo $template->render(array('name' => 'Fabien')); 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: http://www.php.net/manual/en/function.is-callable.php Twig-2.4.6/doc/tags/000077500000000000000000000000001324654574500141575ustar00rootroot00000000000000Twig-2.4.6/doc/tags/autoescape.rst000066400000000000000000000032301324654574500170400ustar00rootroot00000000000000``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 %} 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. Twig-2.4.6/doc/tags/block.rst000066400000000000000000000007001324654574500160000ustar00rootroot00000000000000``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>` Twig-2.4.6/doc/tags/do.rst000066400000000000000000000002611324654574500153120ustar00rootroot00000000000000``do`` ====== The ``do`` tag works exactly like the regular variable expression (``{{ ... }}``) just that it doesn't print anything: .. code-block:: jinja {% do 1 + 2 %} Twig-2.4.6/doc/tags/embed.rst000066400000000000000000000155341324654574500157750ustar00rootroot00000000000000``embed`` ========= 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>` Twig-2.4.6/doc/tags/extends.rst000066400000000000000000000162771324654574500164000ustar00rootroot00000000000000``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 %} $layout = $twig->load('some_layout_template.twig'); $twig->display('template.twig', array('layout' => $layout)); 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>` Twig-2.4.6/doc/tags/filter.rst000066400000000000000000000007171324654574500162030ustar00rootroot00000000000000``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>" #} Twig-2.4.6/doc/tags/flush.rst000066400000000000000000000003321324654574500160300ustar00rootroot00000000000000``flush`` ========= The ``flush`` tag tells Twig to flush the output buffer: .. code-block:: jinja {% flush %} .. note:: Internally, Twig uses the PHP `flush`_ function. .. _`flush`: http://php.net/flush Twig-2.4.6/doc/tags/for.rst000066400000000000000000000107261324654574500155050ustar00rootroot00000000000000``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. 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 %}
    Twig-2.4.6/doc/tags/from.rst000066400000000000000000000004231324654574500156530ustar00rootroot00000000000000``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>` Twig-2.4.6/doc/tags/if.rst000066400000000000000000000036531324654574500153160ustar00rootroot00000000000000``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 kenny.sick %} Kenny is sick. {% elseif kenny.dead %} You killed Kenny! You bastard!!! {% else %} Kenny looks okay --- so far {% 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 whitespace-only string true empty array false null false non-empty array true object true ====================== ==================== Twig-2.4.6/doc/tags/import.rst000066400000000000000000000033361324654574500162300ustar00rootroot00000000000000``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>` Twig-2.4.6/doc/tags/include.rst000066400000000000000000000047351324654574500163450ustar00rootroot00000000000000``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 %} $template = $twig->load('some_template.twig'); $twig->display('template.twig', array('template' => $template)); 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 %} 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. Twig-2.4.6/doc/tags/index.rst000066400000000000000000000003561324654574500160240ustar00rootroot00000000000000Tags ==== .. toctree:: :maxdepth: 1 autoescape block do embed extends filter flush for from if import include macro sandbox set spaceless use verbatim with Twig-2.4.6/doc/tags/macro.rst000066400000000000000000000051541324654574500160170ustar00rootroot00000000000000``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') }}

    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>` Twig-2.4.6/doc/tags/sandbox.rst000066400000000000000000000013741324654574500163540ustar00rootroot00000000000000``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 %} Twig-2.4.6/doc/tags/set.rst000066400000000000000000000032221324654574500155030ustar00rootroot00000000000000``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 #} Twig-2.4.6/doc/tags/spaceless.rst000066400000000000000000000022241324654574500166730ustar00rootroot00000000000000``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. Twig-2.4.6/doc/tags/use.rst000066400000000000000000000062751324654574500155170ustar00rootroot00000000000000``use`` ======= .. 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 %} 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:: 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. Twig-2.4.6/doc/tags/verbatim.rst000066400000000000000000000005571324654574500165310ustar00rootroot00000000000000``verbatim`` ============ 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 %} Twig-2.4.6/doc/tags/with.rst000066400000000000000000000021071324654574500156640ustar00rootroot00000000000000``with`` ======== 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 %} Twig-2.4.6/doc/templates.rst000066400000000000000000000645001324654574500157560ustar00rootroot00000000000000Twig 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, and if ``foo`` is an object, check that ``hasBar`` 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 name; * ``_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 --------------- .. 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 filename 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 ------ 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 ~~~~~~~~ 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) #} { foo: 'foo', bar: 'bar' } {# keys as integer #} { 2: 'foo', 4: 'bar' } {# keys as expressions (the expression must be enclosed into parentheses) #} {% 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``. 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 support 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 ~~~~~~~~~~~~~~~ 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' }} {{ 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 ~~~~~~~~~~~~~~~~~~~~ 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 ------------------ 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`: http://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`: http://php.net/manual/en/pcre.pattern.php .. _`PHP-twig for atom`: https://github.com/reesef/php-twig .. _`TwigFiddle`: http://twigfiddle.com/ .. _`Twig pack`: https://marketplace.visualstudio.com/items?itemName=bajdzis.vscode-twig-pack Twig-2.4.6/doc/tests/000077500000000000000000000000001324654574500143635ustar00rootroot00000000000000Twig-2.4.6/doc/tests/constant.rst000066400000000000000000000010341324654574500167440ustar00rootroot00000000000000``constant`` ============ ``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 %} Twig-2.4.6/doc/tests/defined.rst000066400000000000000000000012661324654574500165200ustar00rootroot00000000000000``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 %} Twig-2.4.6/doc/tests/divisibleby.rst000066400000000000000000000003021324654574500174150ustar00rootroot00000000000000``divisible by`` ================ ``divisible by`` checks if a variable is divisible by a number: .. code-block:: jinja {% if loop.index is divisible by(3) %} ... {% endif %} Twig-2.4.6/doc/tests/empty.rst000066400000000000000000000011031324654574500162460ustar00rootroot00000000000000``empty`` ========= .. versionadded:: 2.3 Support for the ``__toString()`` magic method has been added in Twig 2.3. ``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 %} Twig-2.4.6/doc/tests/even.rst000066400000000000000000000002371324654574500160540ustar00rootroot00000000000000``even`` ======== ``even`` returns ``true`` if the given number is even: .. code-block:: jinja {{ var is even }} .. seealso:: :doc:`odd<../tests/odd>` Twig-2.4.6/doc/tests/index.rst000066400000000000000000000002211324654574500162170ustar00rootroot00000000000000Tests ===== .. toctree:: :maxdepth: 1 constant defined divisibleby empty even iterable null odd sameas Twig-2.4.6/doc/tests/iterable.rst000066400000000000000000000006131324654574500167040ustar00rootroot00000000000000``iterable`` ============ ``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 %} Twig-2.4.6/doc/tests/null.rst000066400000000000000000000002531324654574500160670ustar00rootroot00000000000000``null`` ======== ``null`` returns ``true`` if the variable is ``null``: .. code-block:: jinja {{ var is null }} .. note:: ``none`` is an alias for ``null``. Twig-2.4.6/doc/tests/odd.rst000066400000000000000000000002341324654574500156620ustar00rootroot00000000000000``odd`` ======= ``odd`` returns ``true`` if the given number is odd: .. code-block:: jinja {{ var is odd }} .. seealso:: :doc:`even<../tests/even>` Twig-2.4.6/doc/tests/sameas.rst000066400000000000000000000004241324654574500163660ustar00rootroot00000000000000``same as`` =========== ``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 %} Twig-2.4.6/lib/000077500000000000000000000000001324654574500132225ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/000077500000000000000000000000001324654574500141345ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/BaseNodeVisitor.php000066400000000000000000000024101324654574500177020ustar00rootroot00000000000000 */ abstract class Twig_BaseNodeVisitor implements Twig_NodeVisitorInterface { final public function enterNode(Twig_Node $node, Twig_Environment $env) { return $this->doEnterNode($node, $env); } final public function leaveNode(Twig_Node $node, Twig_Environment $env) { 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'); Twig-2.4.6/lib/Twig/Cache/000077500000000000000000000000001324654574500151375ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Cache/Filesystem.php000066400000000000000000000047421324654574500200030ustar00rootroot00000000000000 */ 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)) { 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); Twig-2.4.6/lib/Twig/Cache/Null.php000066400000000000000000000012431324654574500165620ustar00rootroot00000000000000 */ final 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); Twig-2.4.6/lib/Twig/CacheInterface.php000066400000000000000000000026631324654574500175000ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Compiler.php000066400000000000000000000130741324654574500164240ustar00rootroot00000000000000 */ class Twig_Compiler { private $lastLine; private $source; private $indentation; private $env; private $debugInfo = array(); private $sourceOffset; private $sourceLine; private $varNameSalt = 0; public function __construct(Twig_Environment $env) { $this->env = $env; } /** * 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_Node $node The node to compile * @param int $indentation The current indentation * * @return $this */ public function compile(Twig_Node $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; $node->compile($this); return $this; } public function subcompile(Twig_Node $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) { foreach ($strings as $string) { $this->source .= str_repeat(' ', $this->indentation * 4).$string; } 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_Node $node) { if ($node->getTemplateLine() != $this->lastLine) { $this->write(sprintf("// line %d\n", $node->getTemplateLine())); $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'); Twig-2.4.6/lib/Twig/ContainerRuntimeLoader.php000066400000000000000000000017041324654574500212640ustar00rootroot00000000000000 * @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); Twig-2.4.6/lib/Twig/Environment.php000066400000000000000000000664641324654574500171710ustar00rootroot00000000000000 */ class Twig_Environment { const VERSION = '2.4.6'; const VERSION_ID = 20406; const MAJOR_VERSION = 2; const MINOR_VERSION = 4; const RELEASE_VERSION = 5; const EXTRA_VERSION = ''; private $charset; private $loader; private $debug; private $autoReload; private $cache; private $lexer; private $parser; private $compiler; private $baseTemplateClass; private $globals = array(); private $resolvedGlobals; private $loadedTemplates; private $strictVariables; private $templateClassPrefix = '__TwigTemplate_'; private $originalCache; private $extensionSet; 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 * * 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, $options = array()) { $this->setLoader($loader); $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->setCharset($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->extensionSet = new Twig_ExtensionSet(); $this->addExtension(new Twig_Extension_Core()); $this->addExtension(new Twig_Extension_Escaper($options['autoescape'])); $this->addExtension(new Twig_Extension_Optimizer($options['optimizations'])); } /** * 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 ($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 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); } /** * 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_Template 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)) { $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)) { $source = $this->getLoader()->getSourceContext($name); $content = $this->compileSource($source); $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); } } } // to be removed in 3.0 $this->extensionSet->initRuntime($this); 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); } finally { unset($this->loading[$cls]); } 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); } finally { $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) { return $this->extensionSet->getLastModified() <= $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))); } public function setLexer(Twig_Lexer $lexer) { $this->lexer = $lexer; } /** * Tokenizes a source code. * * @return Twig_TokenStream * * @throws Twig_Error_Syntax When the code is syntactically wrong */ public function tokenize(Twig_Source $source) { if (null === $this->lexer) { $this->lexer = new Twig_Lexer($this); } return $this->lexer->tokenize($source); } public function setParser(Twig_Parser $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); } public function setCompiler(Twig_Compiler $compiler) { $this->compiler = $compiler; } /** * Compiles a node and returns the PHP code. * * @return string The compiled PHP source code */ public function compile(Twig_Node $node) { if (null === $this->compiler) { $this->compiler = new Twig_Compiler($this); } return $this->compiler->compile($node)->getSource(); } /** * Compiles a template source code. * * @return string The compiled PHP source code * * @throws Twig_Error_Syntax When there was an error during tokenizing, parsing or compiling */ public function compileSource(Twig_Source $source) { 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) { $this->loader = $loader; } /** * Gets the Loader instance. * * @return Twig_LoaderInterface */ public function getLoader() { return $this->loader; } /** * Sets the default template charset. * * @param string $charset The default charset */ public function setCharset($charset) { if ('UTF8' === $charset = strtoupper($charset)) { // iconv on Windows requires "UTF-8" instead of "UTF8" $charset = 'UTF-8'; } $this->charset = $charset; } /** * Gets the default template charset. * * @return string The default charset */ public function getCharset() { return $this->charset; } /** * 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) { return $this->extensionSet->hasExtension($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) { return $this->extensionSet->getExtension($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) { $this->extensionSet->addExtension($extension); $this->updateOptionsHash(); } /** * Registers an array of extensions. * * @param array $extensions An array of extensions */ public function setExtensions(array $extensions) { $this->extensionSet->setExtensions($extensions); $this->updateOptionsHash(); } /** * 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->extensionSet->getExtensions(); } public function addTokenParser(Twig_TokenParserInterface $parser) { $this->extensionSet->addTokenParser($parser); } /** * Gets the registered Token Parsers. * * @return Twig_TokenParserInterface[] * * @internal */ public function getTokenParsers() { return $this->extensionSet->getTokenParsers(); } /** * Gets registered tags. * * @return Twig_TokenParserInterface[] * * @internal */ public function getTags() { $tags = array(); foreach ($this->getTokenParsers() as $parser) { $tags[$parser->getTag()] = $parser; } return $tags; } public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { $this->extensionSet->addNodeVisitor($visitor); } /** * Gets the registered Node Visitors. * * @return Twig_NodeVisitorInterface[] * * @internal */ public function getNodeVisitors() { return $this->extensionSet->getNodeVisitors(); } public function addFilter(Twig_Filter $filter) { $this->extensionSet->addFilter($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) { return $this->extensionSet->getFilter($name); } public function registerUndefinedFilterCallback(callable $callable) { $this->extensionSet->registerUndefinedFilterCallback($callable); } /** * Gets the registered Filters. * * Be warned that this method cannot return filters defined with registerUndefinedFilterCallback. * * @return Twig_Filter[] * * @see registerUndefinedFilterCallback * * @internal */ public function getFilters() { return $this->extensionSet->getFilters(); } /** * Registers a Test. * * @param Twig_Test $test A Twig_Test instance */ public function addTest(Twig_Test $test) { $this->extensionSet->addTest($test); } /** * Gets the registered Tests. * * @return Twig_Test[] * * @internal */ public function getTests() { return $this->extensionSet->getTests(); } /** * 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) { return $this->extensionSet->getTest($name); } public function addFunction(Twig_Function $function) { $this->extensionSet->addFunction($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) { return $this->extensionSet->getFunction($name); } public function registerUndefinedFunctionCallback(callable $callable) { $this->extensionSet->registerUndefinedFunctionCallback($callable); } /** * Gets registered functions. * * Be warned that this method cannot return functions defined with registerUndefinedFunctionCallback. * * @return Twig_Function[] * * @see registerUndefinedFunctionCallback * * @internal */ public function getFunctions() { return $this->extensionSet->getFunctions(); } /** * 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->extensionSet->isInitialized() && !array_key_exists($name, $this->getGlobals())) { throw new LogicException(sprintf('Unable to add global "%s" as the runtime or the extensions have already been initialized.', $name)); } if (null !== $this->resolvedGlobals) { $this->resolvedGlobals[$name] = $value; } else { $this->globals[$name] = $value; } } /** * Gets the registered Globals. * * @return array An array of globals * * @internal */ public function getGlobals() { if ($this->extensionSet->isInitialized()) { if (null === $this->resolvedGlobals) { $this->resolvedGlobals = array_merge($this->extensionSet->getGlobals(), $this->globals); } return $this->resolvedGlobals; } return array_merge($this->extensionSet->getGlobals(), $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() { return $this->extensionSet->getUnaryOperators(); } /** * Gets the registered binary Operators. * * @return array An array of binary operators * * @internal */ public function getBinaryOperators() { return $this->extensionSet->getBinaryOperators(); } private function updateOptionsHash() { $this->optionsHash = implode(':', array( $this->extensionSet->getSignature(), PHP_MAJOR_VERSION, PHP_MINOR_VERSION, self::VERSION, (int) $this->debug, $this->baseTemplateClass, (int) $this->strictVariables, )); } } class_alias('Twig_Environment', 'Twig\Environment', false); Twig-2.4.6/lib/Twig/Error.php000066400000000000000000000177021324654574500157450ustar00rootroot00000000000000 */ class Twig_Error extends Exception { private $lineno; private $name; private $rawMessage; 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) { parent::__construct('', 0, $previous); 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(); } $this->lineno = $lineno; $this->name = $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 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->name ? new Twig_Source($this->sourceCode, $this->name, $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->name = $this->sourcePath = null; } else { $this->sourceCode = $source->getCode(); $this->name = $source->getName(); $this->sourcePath = $source->getPath(); } $this->updateRepr(); } public function guess() { $this->guessTemplateInfo(); $this->updateRepr(); } public function appendMessage($rawMessage) { $this->rawMessage .= $rawMessage; $this->updateRepr(); } private 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->name) { if (is_string($this->name) || (is_object($this->name) && method_exists($this->name, '__toString'))) { $name = sprintf('"%s"', $this->name); } else { $name = json_encode($this->name); } $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 .= '?'; } } private function guessTemplateInfo() { $template = null; $templateClass = null; $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS | DEBUG_BACKTRACE_PROVIDE_OBJECT); foreach ($backtrace as $trace) { if (isset($trace['object']) && $trace['object'] instanceof Twig_Template && 'Twig_Template' !== get_class($trace['object'])) { $currentClass = get_class($trace['object']); $isEmbedContainer = 0 === strpos($templateClass, $currentClass); if (null === $this->name || ($this->name == $trace['object']->getTemplateName() && !$isEmbedContainer)) { $template = $trace['object']; $templateClass = get_class($trace['object']); } } } // update template name if (null !== $template && null === $this->name) { $this->name = $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 = $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'); Twig-2.4.6/lib/Twig/Error/000077500000000000000000000000001324654574500152255ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Error/Loader.php000066400000000000000000000020601324654574500171420ustar00rootroot00000000000000 */ class Twig_Error_Loader extends Twig_Error { public function __construct($message, $lineno = -1, $source = null, Exception $previous = null) { Exception::__construct('', 0, $previous); $this->appendMessage($message); $this->setTemplateLine(false); } } class_alias('Twig_Error_Loader', 'Twig\Error\LoaderError', false); Twig-2.4.6/lib/Twig/Error/Runtime.php000066400000000000000000000007071324654574500173650ustar00rootroot00000000000000 */ class Twig_Error_Runtime extends Twig_Error { } class_alias('Twig_Error_Runtime', 'Twig\Error\RuntimeError', false); Twig-2.4.6/lib/Twig/Error/Syntax.php000066400000000000000000000023141324654574500172240ustar00rootroot00000000000000 */ 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) { $alternatives = array(); foreach ($items as $item) { $lev = levenshtein($name, $item); if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) { $alternatives[$item] = $lev; } } if (!$alternatives) { return; } asort($alternatives); $this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', array_keys($alternatives)))); } } class_alias('Twig_Error_Syntax', 'Twig\Error\SyntaxError', false); Twig-2.4.6/lib/Twig/ExistsLoaderInterface.php000066400000000000000000000006371324654574500211020ustar00rootroot00000000000000 * * @internal */ class Twig_ExpressionParser { const OPERATOR_LEFT = 1; const OPERATOR_RIGHT = 2; private $parser; private $env; private $unaryOperators; private $binaryOperators; public function __construct(Twig_Parser $parser, Twig_Environment $env) { $this->parser = $parser; $this->env = $env; $this->unaryOperators = $env->getUnaryOperators(); $this->binaryOperators = $env->getBinaryOperators(); } 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 = $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; } private 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(); } private 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; } private function isUnary(Twig_Token $token) { return $token->test(Twig_Token::OPERATOR_TYPE) && isset($this->unaryOperators[$token->getValue()]); } private 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'); $node = new Twig_Node_Expression_MethodCall($node, 'macro_'.$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_Node $node) { return new Twig_Node_Expression_Unary_Not($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine()); } private function parseTestExpression(Twig_Node $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->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->getName(), $stream->getCurrent()->getLine()); @trigger_error($message, E_USER_DEPRECATED); } return $test->getNodeClass(); } private 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->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->getName(), $line); @trigger_error($message, E_USER_DEPRECATED); } return $function->getNodeClass(); } private 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->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->getName(), $line); @trigger_error($message, E_USER_DEPRECATED); } return $filter->getNodeClass(); } // checks that the node only contains "constant" elements private function checkConstantExpression(Twig_Node $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); Twig-2.4.6/lib/Twig/Extension.php000066400000000000000000000014531324654574500166240ustar00rootroot00000000000000escapers[$strategy] = $callable; } /** * Gets all defined escapers. * * @return callable[] 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(), ); } public function getFilters() { return array( // formatting filters new Twig_Filter('date', 'twig_date_format_filter', array('needs_environment' => true)), new Twig_Filter('date_modify', 'twig_date_modify_filter', array('needs_environment' => true)), new Twig_Filter('format', 'sprintf'), new Twig_Filter('replace', 'twig_replace_filter'), new Twig_Filter('number_format', 'twig_number_format_filter', array('needs_environment' => true)), new Twig_Filter('abs', 'abs'), new Twig_Filter('round', 'twig_round'), // encoding new Twig_Filter('url_encode', 'twig_urlencode_filter'), new Twig_Filter('json_encode', 'json_encode'), new Twig_Filter('convert_encoding', 'twig_convert_encoding'), // string filters new Twig_Filter('title', 'twig_title_string_filter', array('needs_environment' => true)), new Twig_Filter('capitalize', 'twig_capitalize_string_filter', array('needs_environment' => true)), new Twig_Filter('upper', 'twig_upper_filter', array('needs_environment' => true)), new Twig_Filter('lower', 'twig_lower_filter', array('needs_environment' => true)), new Twig_Filter('striptags', 'strip_tags'), new Twig_Filter('trim', 'twig_trim_filter'), new Twig_Filter('nl2br', 'nl2br', array('pre_escape' => 'html', 'is_safe' => array('html'))), // array helpers new Twig_Filter('join', 'twig_join_filter'), new Twig_Filter('split', 'twig_split_filter', array('needs_environment' => true)), new Twig_Filter('sort', 'twig_sort_filter'), new Twig_Filter('merge', 'twig_array_merge'), new Twig_Filter('batch', 'twig_array_batch'), // string/array filters new Twig_Filter('reverse', 'twig_reverse_filter', array('needs_environment' => true)), new Twig_Filter('length', 'twig_length_filter', array('needs_environment' => true)), new Twig_Filter('slice', 'twig_slice', array('needs_environment' => true)), new Twig_Filter('first', 'twig_first', array('needs_environment' => true)), new Twig_Filter('last', 'twig_last', array('needs_environment' => true)), // iteration and runtime new Twig_Filter('default', '_twig_default_filter', array('node_class' => 'Twig_Node_Expression_Filter_Default')), new Twig_Filter('keys', 'twig_get_array_keys_filter'), // escaping new Twig_Filter('escape', 'twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')), new Twig_Filter('e', 'twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')), ); } public function getFunctions() { return array( new Twig_Function('max', 'max'), new Twig_Function('min', 'min'), new Twig_Function('range', 'range'), new Twig_Function('constant', 'twig_constant'), new Twig_Function('cycle', 'twig_cycle'), new Twig_Function('random', 'twig_random', array('needs_environment' => true)), new Twig_Function('date', 'twig_date_converter', array('needs_environment' => true)), new Twig_Function('include', 'twig_include', array('needs_environment' => true, 'needs_context' => true, 'is_safe' => array('all'))), new Twig_Function('source', 'twig_source', array('needs_environment' => true, 'is_safe' => array('all'))), ); } public function getTests() { return array( new Twig_Test('even', null, array('node_class' => 'Twig_Node_Expression_Test_Even')), new Twig_Test('odd', null, array('node_class' => 'Twig_Node_Expression_Test_Odd')), new Twig_Test('defined', null, array('node_class' => 'Twig_Node_Expression_Test_Defined')), new Twig_Test('same as', null, array('node_class' => 'Twig_Node_Expression_Test_Sameas')), new Twig_Test('none', null, array('node_class' => 'Twig_Node_Expression_Test_Null')), new Twig_Test('null', null, array('node_class' => 'Twig_Node_Expression_Test_Null')), new Twig_Test('divisible by', null, array('node_class' => 'Twig_Node_Expression_Test_Divisibleby')), new Twig_Test('constant', null, array('node_class' => 'Twig_Node_Expression_Test_Constant')), new Twig_Test('empty', 'twig_test_empty'), new Twig_Test('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), ), ); } } /** * 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 ''; } $charset = $env->getCharset(); if ('UTF-8' !== $charset) { $values = iconv($charset, 'UTF-8', $values); } // 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] = iconv('UTF-8', $charset, $value); } } } 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 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 DateTimeInterface|string $date A date * @param string $modifier A modifier string * * @return DateTimeInterface A new date object */ function twig_date_modify_filter(Twig_Environment $env, $date, $modifier) { $date = twig_date_converter($env, $date, false); return $date->modify($modifier); } /** * Converts an input to a DateTime instance. * *
     *    {% if date(user.created_at) < date('+2days') %}
     *      {# do something #}
     *    {% endif %}
     * 
    * * @param Twig_Environment $env * @param DateTimeInterface|string|null $date A date or null to use the current time * @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 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 * * @return string */ function twig_replace_filter($str, $from) { if ($from instanceof Traversable) { $from = iterator_to_array($from); } 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)) { return http_build_query($url, '', '&', PHP_QUERY_RFC3986); } return rawurlencode($url); } /** * 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; return (string) mb_substr($item, $start, $length, $env->getCharset()); } /** * 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 ($limit <= 1) { return preg_split('/(?getCharset()); if ($length < $limit) { return array($value); } $r = array(); for ($i = 0; $i < $length; $i += $limit) { $r[] = mb_substr($value, $i, $limit, $env->getCharset()); } return $r; } // The '_default' filter is used internally to avoid using the ternary operator // which costs a lot for big contexts (before PHP 5.4). So, on average, // a function call is cheaper. /** * @internal */ function _twig_default_filter($value, $default = '') { if (twig_test_empty($value)) { return $default; } return $value; } /** * Returns the keys for the given array. * * It is useful when you want to iterate over the keys of an array: * *
     *  {% 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); } $string = (string) $item; $charset = $env->getCharset(); if ('UTF-8' !== $charset) { $item = iconv($charset, 'UTF-8', $string); } preg_match_all('/./us', $item, $matches); $string = implode('', array_reverse($matches[0])); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; } /** * 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 (null === $charset) { $charset = $env->getCharset(); } switch ($strategy) { case 'html': // see http://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 = iconv($charset, 'UTF-8', $string); $string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); return iconv('UTF-8', $charset, $string); case 'js': // escape all non-alphanumeric characters // into their \xHH or \uHHHH representations if ('UTF-8' !== $charset) { $string = iconv($charset, 'UTF-8', $string); } if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $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', function ($matches) { $char = $matches[0]; // \xHH if (!isset($char[1])) { return '\\x'.strtoupper(substr('00'.bin2hex($char), -2)); } // \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)); }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'css': if ('UTF-8' !== $charset) { $string = iconv($charset, 'UTF-8', $string); } if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $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', function ($matches) { $char = $matches[0]; // \xHH if (!isset($char[1])) { $hex = ltrim(strtoupper(bin2hex($char)), '0'); if (0 === strlen($hex)) { $hex = '0'; } return '\\'.$hex.' '; } // \uHHHH $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8'); return '\\'.ltrim(strtoupper(bin2hex($char)), '0').' '; }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'html_attr': if ('UTF-8' !== $charset) { $string = iconv($charset, 'UTF-8', $string); } if (0 == strlen($string) ? false : 1 !== preg_match('/^./su', $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', function ($matches) { /** * This function is adapted from code coming from Zend Framework. * * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /* * 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 => 'quot', /* quotation mark */ 38 => 'amp', /* ampersand */ 60 => 'lt', /* less-than sign */ 62 => 'gt', /* greater-than sign */ ); $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)) { $hex = strtoupper(substr('00'.bin2hex($chr), -2)); } else { $chr = twig_convert_encoding($chr, 'UTF-16BE', 'UTF-8'); $hex = strtoupper(substr('0000'.bin2hex($chr), -4)); } $int = hexdec($hex); if (array_key_exists($int, $entityMap)) { return sprintf('&%s;', $entityMap[$int]); } /* * Per OWASP recommendations, we'll use hex entities for any other * characters where a named entity does not exist. */ return sprintf('&#x%s;', $hex); }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'url': return rawurlencode($string); default: static $escapers; if (null === $escapers) { $escapers = $env->getExtension('Twig_Extension_Core')->getEscapers(); } if (isset($escapers[$strategy])) { return $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'); } function twig_convert_encoding($string, $to, $from) { return iconv($from, $to, $string); } /** * Returns the length of a variable. * * @param Twig_Environment $env A Twig_Environment instance * @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 (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) { return mb_strtoupper($string, $env->getCharset()); } /** * 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) { return mb_strtolower($string, $env->getCharset()); } /** * 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) { $charset = $env->getCharset(); return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).mb_strtolower(mb_substr($string, 1, null, $charset), $charset); } /** * @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 = null; 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; } 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 { 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; } /** * 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 */ function twig_get_attribute(Twig_Environment $env, Twig_Source $source, $object, $item, array $arguments = array(), $type = /* Twig_Template::ANY_CALL */ 'any', $isDefinedTest = false, $ignoreStrictCheck = false, $sandboxed = false) { // array if (/* Twig_Template::METHOD_CALL */ 'method' !== $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 (/* Twig_Template::ARRAY_CALL */ 'array' === $type || !is_object($object)) { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$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 (/* Twig_Template::ARRAY_CALL */ 'array' === $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, $source); } } if (!is_object($object)) { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$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, $source); } if ($object instanceof Twig_Template) { throw new Twig_Error_Runtime('Accessing Twig_Template attributes is forbidden.'); } // object property if (/* Twig_Template::METHOD_CALL */ 'method' !== $type) { if (isset($object->$item) || array_key_exists((string) $item, $object)) { if ($isDefinedTest) { return true; } if ($sandboxed) { $env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item); } return $object->$item; } } static $cache = array(); $class = get_class($object); // object method // precedence: getXxx() > isXxx() > hasXxx() if (!isset($cache[$class])) { $methods = get_class_methods($object); sort($methods); $lcMethods = array_map('strtolower', $methods); $classCache = array(); foreach ($methods as $i => $method) { $classCache[$method] = $method; $classCache[$lcName = $lcMethods[$i]] = $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); } elseif ('h' === $lcName[0] && 0 === strpos($lcName, 'has')) { $name = substr($method, 3); $lcName = substr($lcName, 3); if (in_array('is'.$lcName, $lcMethods)) { continue; } } else { continue; } // skip get() and is() methods (in which case, $name is empty) if ($name) { if (!isset($classCache[$name])) { $classCache[$name] = $method; } if (!isset($classCache[$lcName])) { $classCache[$lcName] = $method; } } } $cache[$class] = $classCache; } $call = false; if (isset($cache[$class][$item])) { $method = $cache[$class][$item]; } elseif (isset($cache[$class][$lcItem = strtolower($item)])) { $method = $cache[$class][$lcItem]; } elseif (isset($cache[$class]['__call'])) { $method = $item; $call = true; } else { if ($isDefinedTest) { return false; } if ($ignoreStrictCheck || !$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()"/"has%1$s()" or "__call()" exist and have public access in class "%2$s".', $item, $class), -1, $source); } if ($isDefinedTest) { return true; } if ($sandboxed) { $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 { $ret = $object->$method(...$arguments); } catch (BadMethodCallException $e) { if ($call && ($ignoreStrictCheck || !$env->isStrictVariables())) { return; } throw $e; } return $ret; } class_alias('Twig_Extension_Core', 'Twig\Extension\CoreExtension', false); Twig-2.4.6/lib/Twig/Extension/Debug.php000066400000000000000000000032051324654574500176470ustar00rootroot00000000000000 $isDumpOutputHtmlSafe ? array('html') : array(), 'needs_context' => true, 'needs_environment' => true)), ); } } function twig_var_dump(Twig_Environment $env, $context, ...$vars) { if (!$env->isDebug()) { return; } ob_start(); if (!$vars) { $vars = array(); foreach ($context as $key => $value) { if (!$value instanceof Twig_Template) { $vars[$key] = $value; } } var_dump($vars); } else { var_dump(...$vars); } return ob_get_clean(); } class_alias('Twig_Extension_Debug', 'Twig\Extension\DebugExtension', false); Twig-2.4.6/lib/Twig/Extension/Escaper.php000066400000000000000000000044641324654574500202130ustar00rootroot00000000000000setDefaultStrategy($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_Filter('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) { 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; } } /** * 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); Twig-2.4.6/lib/Twig/Extension/GlobalsInterface.php000066400000000000000000000014151324654574500220260ustar00rootroot00000000000000 */ interface Twig_Extension_GlobalsInterface { /** * Returns a list of global variables to add to the existing list. * * @return array An array of global variables */ public function getGlobals(); } class_alias('Twig_Extension_GlobalsInterface', 'Twig\Extension\GlobalsInterface', false); Twig-2.4.6/lib/Twig/Extension/InitRuntimeInterface.php000066400000000000000000000016361324654574500227170ustar00rootroot00000000000000 */ interface Twig_Extension_InitRuntimeInterface { /** * Initializes the runtime environment. * * This is where you can load some file that contains filter functions for instance. * * @param Twig_Environment $environment The current Twig_Environment instance */ public function initRuntime(Twig_Environment $environment); } class_alias('Twig_Extension_InitRuntimeInterface', 'Twig\Extension\InitRuntimeInterface', false); Twig-2.4.6/lib/Twig/Extension/Optimizer.php000066400000000000000000000011351324654574500206030ustar00rootroot00000000000000optimizers = $optimizers; } public function getNodeVisitors() { return array(new Twig_NodeVisitor_Optimizer($this->optimizers)); } } class_alias('Twig_Extension_Optimizer', 'Twig\Extension\OptimizerExtension', false); Twig-2.4.6/lib/Twig/Extension/Profiler.php000066400000000000000000000020411324654574500204000ustar00rootroot00000000000000actives[] = $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))); } } class_alias('Twig_Extension_Profiler', 'Twig\Extension\ProfilerExtension', false); class_exists('Twig_Profiler_Profile'); Twig-2.4.6/lib/Twig/Extension/Sandbox.php000066400000000000000000000041711324654574500202220ustar00rootroot00000000000000policy = $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; } } class_alias('Twig_Extension_Sandbox', 'Twig\Extension\SandboxExtension', false); Twig-2.4.6/lib/Twig/Extension/Staging.php000066400000000000000000000044501324654574500202200ustar00rootroot00000000000000 * * @internal */ final class Twig_Extension_Staging extends Twig_Extension { private $functions = array(); private $filters = array(); private $visitors = array(); private $tokenParsers = array(); private $tests = array(); public function addFunction(Twig_Function $function) { if (isset($this->functions[$function->getName()])) { throw new LogicException(sprintf('Function "%s" is already registered.', $function->getName())); } $this->functions[$function->getName()] = $function; } public function getFunctions() { return $this->functions; } public function addFilter(Twig_Filter $filter) { if (isset($this->filters[$filter->getName()])) { throw new LogicException(sprintf('Filter "%s" is already registered.', $filter->getName())); } $this->filters[$filter->getName()] = $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()])) { throw new LogicException(sprintf('Tag "%s" is already registered.', $parser->getTag())); } $this->tokenParsers[$parser->getTag()] = $parser; } public function getTokenParsers() { return $this->tokenParsers; } public function addTest(Twig_Test $test) { if (isset($this->tests[$test->getName()])) { throw new LogicException(sprintf('Test "%s" is already registered.', $test->getTag())); } $this->tests[$test->getName()] = $test; } public function getTests() { return $this->tests; } } class_alias('Twig_Extension_Staging', 'Twig\Extension\StagingExtension', false); Twig-2.4.6/lib/Twig/Extension/StringLoader.php000066400000000000000000000017541324654574500212250ustar00rootroot00000000000000 true)), ); } } /** * 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); Twig-2.4.6/lib/Twig/ExtensionInterface.php000066400000000000000000000027131324654574500204450ustar00rootroot00000000000000 */ interface Twig_ExtensionInterface { /** * 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_Filter[] */ public function getFilters(); /** * Returns a list of tests to add to the existing list. * * @return Twig_Test[] */ public function getTests(); /** * Returns a list of functions to add to the existing list. * * @return Twig_Function[] */ 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(); } class_alias('Twig_ExtensionInterface', 'Twig\Extension\ExtensionInterface', false); class_exists('Twig_Environment'); Twig-2.4.6/lib/Twig/ExtensionSet.php000066400000000000000000000320001324654574500172700ustar00rootroot00000000000000 * * @internal */ final class Twig_ExtensionSet { private $extensions; private $initialized = false; private $runtimeInitialized = false; private $staging; private $parsers; private $visitors; private $filters; private $tests; private $functions; private $unaryOperators; private $binaryOperators; private $globals; private $functionCallbacks = array(); private $filterCallbacks = array(); private $lastModified = 0; public function __construct() { $this->staging = new Twig_Extension_Staging(); } /** * Initializes the runtime environment. */ public function initRuntime(Twig_Environment $env) { if ($this->runtimeInitialized) { return; } $this->runtimeInitialized = true; foreach ($this->extensions as $extension) { if ($extension instanceof Twig_Extension_InitRuntimeInterface) { $extension->initRuntime($env); } } } /** * 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->extensions[$class]) && class_exists($class, false)) { // For BC/FC with namespaced aliases $class = (new ReflectionClass($class))->name; } return isset($this->extensions[$class]); } /** * Gets an extension by class name. * * @param string $class The extension class name * * @return Twig_ExtensionInterface A Twig_ExtensionInterface instance */ public function getExtension($class) { $class = ltrim($class, '\\'); if (!isset($this->extensions[$class]) && class_exists($class, false)) { // For BC/FC with namespaced aliases $class = (new ReflectionClass($class))->name; } if (!isset($this->extensions[$class])) { throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class)); } return $this->extensions[$class]; } /** * 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 array An array of extensions */ public function getExtensions() { return $this->extensions; } public function getSignature() { return json_encode(array_keys($this->extensions)); } public function isInitialized() { return $this->initialized || $this->runtimeInitialized; } public function getLastModified() { if (0 !== $this->lastModified) { return $this->lastModified; } foreach ($this->extensions as $extension) { $r = new ReflectionObject($extension); if (file_exists($r->getFileName()) && ($extensionTime = filemtime($r->getFileName())) > $this->lastModified) { $this->lastModified = $extensionTime; } } return $this->lastModified; } /** * Registers an extension. * * @param Twig_ExtensionInterface $extension A Twig_ExtensionInterface instance */ public function addExtension(Twig_ExtensionInterface $extension) { $class = get_class($extension); if ($this->initialized) { throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $class)); } if (isset($this->extensions[$class])) { throw new LogicException(sprintf('Unable to register extension "%s" as it is already registered.', $class)); } $this->extensions[$class] = $extension; } public function addFunction(Twig_Function $function) { if ($this->initialized) { throw new LogicException(sprintf('Unable to add function "%s" as extensions have already been initialized.', $function->getName())); } $this->staging->addFunction($function); } public function getFunctions() { if (!$this->initialized) { $this->initExtensions(); } return $this->functions; } /** * Get a function by name. * * @param string $name function name * * @return Twig_Function|false A Twig_Function instance or false if the function does not exist */ public function getFunction($name) { if (!$this->initialized) { $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 && preg_match('#^'.$pattern.'$#', $name, $matches)) { array_shift($matches); $function->setArguments($matches); return $function; } } foreach ($this->functionCallbacks as $callback) { if (false !== $function = $callback($name)) { return $function; } } return false; } public function registerUndefinedFunctionCallback(callable $callable) { $this->functionCallbacks[] = $callable; } public function addFilter(Twig_Filter $filter) { if ($this->initialized) { throw new LogicException(sprintf('Unable to add filter "%s" as extensions have already been initialized.', $filter->getName())); } $this->staging->addFilter($filter); } public function getFilters() { if (!$this->initialized) { $this->initExtensions(); } return $this->filters; } /** * 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 */ public function getFilter($name) { if (!$this->initialized) { $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 && preg_match('#^'.$pattern.'$#', $name, $matches)) { array_shift($matches); $filter->setArguments($matches); return $filter; } } foreach ($this->filterCallbacks as $callback) { if (false !== $filter = $callback($name)) { return $filter; } } return false; } public function registerUndefinedFilterCallback(callable $callable) { $this->filterCallbacks[] = $callable; } public function addNodeVisitor(Twig_NodeVisitorInterface $visitor) { if ($this->initialized) { throw new LogicException('Unable to add a node visitor as extensions have already been initialized.'); } $this->staging->addNodeVisitor($visitor); } public function getNodeVisitors() { if (!$this->initialized) { $this->initExtensions(); } return $this->visitors; } public function addTokenParser(Twig_TokenParserInterface $parser) { if ($this->initialized) { throw new LogicException('Unable to add a token parser as extensions have already been initialized.'); } $this->staging->addTokenParser($parser); } public function getTokenParsers() { if (!$this->initialized) { $this->initExtensions(); } return $this->parsers; } public function getGlobals() { if (null !== $this->globals) { return $this->globals; } $globals = array(); foreach ($this->extensions as $extension) { if (!$extension instanceof Twig_Extension_GlobalsInterface) { continue; } $extGlobals = $extension->getGlobals(); if (!is_array($extGlobals)) { throw new UnexpectedValueException(sprintf('"%s::getGlobals()" must return an array of globals.', get_class($extension))); } $globals = array_merge($globals, $extGlobals); } if ($this->initialized) { $this->globals = $globals; } return $globals; } public function addTest(Twig_Test $test) { if ($this->initialized) { throw new LogicException(sprintf('Unable to add test "%s" as extensions have already been initialized.', $test->getName())); } $this->staging->addTest($test); } public function getTests() { if (!$this->initialized) { $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 */ public function getTest($name) { if (!$this->initialized) { $this->initExtensions(); } if (isset($this->tests[$name])) { return $this->tests[$name]; } return false; } /** * Gets the registered unary Operators. * * @return array An array of unary operators */ public function getUnaryOperators() { if (!$this->initialized) { $this->initExtensions(); } return $this->unaryOperators; } /** * Gets the registered binary Operators. * * @return array An array of binary operators */ public function getBinaryOperators() { if (!$this->initialized) { $this->initExtensions(); } return $this->binaryOperators; } private function initExtensions() { $this->parsers = array(); $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->initialized = true; } private function initExtension(Twig_ExtensionInterface $extension) { // filters foreach ($extension->getFilters() as $filter) { $this->filters[$filter->getName()] = $filter; } // functions foreach ($extension->getFunctions() as $function) { $this->functions[$function->getName()] = $function; } // tests foreach ($extension->getTests() as $test) { $this->tests[$test->getName()] = $test; } // token parsers foreach ($extension->getTokenParsers() as $parser) { if (!$parser instanceof Twig_TokenParserInterface) { throw new LogicException('getTokenParsers() must return an array of Twig_TokenParserInterface.'); } $this->parsers[] = $parser; } // 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]); } } } class_alias('Twig_ExtensionSet', 'Twig\ExtensionSet', false); Twig-2.4.6/lib/Twig/FactoryRuntimeLoader.php000066400000000000000000000015721324654574500207540ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/FileExtensionEscapingStrategy.php000066400000000000000000000027601324654574500226230ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Filter.php000066400000000000000000000065441324654574500161030ustar00rootroot00000000000000 * * @see http://twig.sensiolabs.org/doc/templates.html#filters */ class Twig_Filter { private $name; private $callable; private $options; private $arguments = array(); /** * Creates a template filter. * * @param string $name Name of this filter * @param callable|null $callable A callable implementing the filter. If null, you need to overwrite the "node_class" option to customize compilation. * @param array $options Options array */ public function __construct(string $name, $callable = null, array $options = array()) { if (__CLASS__ !== get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since version 2.4.0 and the class will be final in 3.0.', E_USER_DEPRECATED); } $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; } /** * Returns the callable to execute for this filter. * * @return callable|null */ 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 $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']; } } // For Twig 1.x compatibility class_alias('Twig_Filter', 'Twig_SimpleFilter', false); class_alias('Twig_Filter', 'Twig\TwigFilter', false); Twig-2.4.6/lib/Twig/Function.php000066400000000000000000000061651324654574500164420ustar00rootroot00000000000000 * * @see http://twig.sensiolabs.org/doc/templates.html#functions */ class Twig_Function { private $name; private $callable; private $options; private $arguments = array(); /** * Creates a template function. * * @param string $name Name of this function * @param callable|null $callable A callable implementing the function. If null, you need to overwrite the "node_class" option to customize compilation. * @param array $options Options array */ public function __construct(string $name, $callable = null, array $options = array()) { if (__CLASS__ !== get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since version 2.4.0 and the class will be final in 3.0.', E_USER_DEPRECATED); } $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; } /** * Returns the callable to execute for this function. * * @return callable|null */ 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 $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']; } } // For Twig 1.x compatibility class_alias('Twig_Function', 'Twig_SimpleFunction', false); class_alias('Twig_Function', 'Twig\TwigFunction', false); Twig-2.4.6/lib/Twig/Lexer.php000066400000000000000000000363251324654574500157350ustar00rootroot00000000000000 */ class Twig_Lexer { private $tokens; private $code; private $cursor; private $lineno; private $end; private $state; private $states; private $brackets; private $env; private $source; private $options; private $regexes; private $position; private $positions; private $currentVarBlockLine; 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*(?:endverbatim)\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*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(Twig_Source $source) { $this->source = $source; $this->code = str_replace(array("\r\n", "\r"), "\n", $source->getCode()); $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); } return new Twig_TokenStream($this->tokens, $this->source); } private 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(); // {% 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; } } private 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(); } } private 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(); } } private 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); } } private function lexRawData() { if (!preg_match($this->regexes['lex_raw_data'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { throw new Twig_Error_Syntax('Unexpected end of file: Unclosed "verbatim" block.', $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); } private 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]); } private 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; } } private 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(); } } private 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); } private function moveCursor($text) { $this->cursor += strlen($text); $this->lineno += substr_count($text, "\n"); } private 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'; } private function pushState($state) { $this->states[] = $this->state; $this->state = $state; } private function popState() { if (0 === count($this->states)) { throw new LogicException('Cannot pop state without a previous state.'); } $this->state = array_pop($this->states); } } class_alias('Twig_Lexer', 'Twig\Lexer', false); Twig-2.4.6/lib/Twig/Loader/000077500000000000000000000000001324654574500153425ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Loader/Array.php000066400000000000000000000043561324654574500171410ustar00rootroot00000000000000 */ final class Twig_Loader_Array implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface { private $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[$name] = $template; } 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[$name]); } public function getCacheKey($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) { 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); Twig-2.4.6/lib/Twig/Loader/Chain.php000066400000000000000000000057271324654574500171100ustar00rootroot00000000000000 */ final class Twig_Loader_Chain implements Twig_LoaderInterface, Twig_ExistsLoaderInterface, Twig_SourceContextLoaderInterface { private $hasSourceCache = array(); private $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 getSourceContext($name) { $exceptions = array(); foreach ($this->loaders as $loader) { if (!$loader->exists($name)) { continue; } try { return $loader->getSourceContext($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) { if (isset($this->hasSourceCache[$name])) { return $this->hasSourceCache[$name]; } foreach ($this->loaders as $loader) { if ($loader->exists($name)) { return $this->hasSourceCache[$name] = true; } } return $this->hasSourceCache[$name] = false; } public function getCacheKey($name) { $exceptions = array(); foreach ($this->loaders as $loader) { if (!$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->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); Twig-2.4.6/lib/Twig/Loader/Filesystem.php000066400000000000000000000200671324654574500202040ustar00rootroot00000000000000 */ 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 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; } return false !== $this->findTemplate($name, false); } public function isFresh($name, $time) { return filemtime($this->findTemplate($name)) <= $time; } /** * Checks if the template can be found. * * @param string $name The template name * @param bool $throw Whether to throw an exception when an error occurs * * @return string|false The template name or false */ protected function findTemplate($name, $throw = 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]); } $this->validateName($name); list($namespace, $shortname) = $this->parseName($name); 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]); } private function normalizeName($name) { return preg_replace('#/{2,}#', '/', str_replace('\\', '/', $name)); } private 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); } private 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]) && ':' === $file[1] && strspn($file, '/\\', 2, 1) ) || null !== parse_url($file, PHP_URL_SCHEME) ; } } class_alias('Twig_Loader_Filesystem', 'Twig\Loader\FilesystemLoader', false); Twig-2.4.6/lib/Twig/LoaderInterface.php000066400000000000000000000032701324654574500176760ustar00rootroot00000000000000 */ interface Twig_LoaderInterface { /** * 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); /** * 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); /** * 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_LoaderInterface', 'Twig\Loader\LoaderInterface', false); Twig-2.4.6/lib/Twig/Markup.php000066400000000000000000000015161324654574500161070ustar00rootroot00000000000000 */ class Twig_Markup implements Countable, JsonSerializable { private $content; private $charset; public function __construct($content, $charset) { $this->content = (string) $content; $this->charset = $charset; } public function __toString() { return $this->content; } public function count() { return mb_strlen($this->content, $this->charset); } public function jsonSerialize() { return $this->content; } } class_alias('Twig_Markup', 'Twig\Markup', false); Twig-2.4.6/lib/Twig/Node.php000066400000000000000000000110251324654574500155310ustar00rootroot00000000000000 */ class Twig_Node implements Countable, IteratorAggregate { 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 self) { throw new InvalidArgumentException(sprintf('Using "%s" for the value of node "%s" of "%s" is not supported. You must pass a Twig_Node instance.', is_object($node) ? get_class($node) : null === $node ? 'null' : gettype($node), $name, get_class($this))); } } $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); } public function compile(Twig_Compiler $compiler) { foreach ($this->nodes as $node) { $node->compile($compiler); } } public function getTemplateLine() { 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 isset($this->nodes[$name]); } /** * @return Twig_Node */ public function getNode($name) { if (!isset($this->nodes[$name])) { throw new LogicException(sprintf('Node "%s" does not exist for Node "%s".', $name, get_class($this))); } return $this->nodes[$name]; } public function setNode($name, self $node) { $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) { $node->setTemplateName($name); } } public function getTemplateName() { return $this->name; } } class_alias('Twig_Node', 'Twig\Node\Node', false); class_exists('Twig_Compiler'); Twig-2.4.6/lib/Twig/Node/000077500000000000000000000000001324654574500150215ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Node/AutoEscape.php000066400000000000000000000016041324654574500175640ustar00rootroot00000000000000 */ class Twig_Node_AutoEscape extends Twig_Node { public function __construct($value, Twig_Node $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); Twig-2.4.6/lib/Twig/Node/Block.php000066400000000000000000000017671324654574500165770ustar00rootroot00000000000000 */ class Twig_Node_Block extends Twig_Node { public function __construct($name, Twig_Node $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); Twig-2.4.6/lib/Twig/Node/BlockReference.php000066400000000000000000000015551324654574500204110ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/Body.php000066400000000000000000000006111324654574500164250ustar00rootroot00000000000000 */ class Twig_Node_Body extends Twig_Node { } class_alias('Twig_Node_Body', 'Twig\Node\BodyNode', false); Twig-2.4.6/lib/Twig/Node/CheckSecurity.php000066400000000000000000000060041324654574500202770ustar00rootroot00000000000000 */ class Twig_Node_CheckSecurity extends Twig_Node { private $usedFilters; private $usedTags; private $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->extensions['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->source);\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); Twig-2.4.6/lib/Twig/Node/Do.php000066400000000000000000000014161324654574500160760ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/Embed.php000066400000000000000000000025131324654574500165470ustar00rootroot00000000000000 */ 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); $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); Twig-2.4.6/lib/Twig/Node/Expression.php000066400000000000000000000007551324654574500177000ustar00rootroot00000000000000 */ abstract class Twig_Node_Expression extends Twig_Node { } class_alias('Twig_Node_Expression', 'Twig\Node\Expression\AbstractExpression', false); Twig-2.4.6/lib/Twig/Node/Expression/000077500000000000000000000000001324654574500171605ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Node/Expression/Array.php000066400000000000000000000044361324654574500207560ustar00rootroot00000000000000index = -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); Twig-2.4.6/lib/Twig/Node/Expression/AssignName.php000066400000000000000000000011261324654574500217160ustar00rootroot00000000000000raw('$context[') ->string($this->getAttribute('name')) ->raw(']') ; } } class_alias('Twig_Node_Expression_AssignName', 'Twig\Node\Expression\AssignNameExpression', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary.php000066400000000000000000000017351324654574500211230ustar00rootroot00000000000000 $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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/000077500000000000000000000000001324654574500204045ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Node/Expression/Binary/Add.php000066400000000000000000000007641324654574500216140ustar00rootroot00000000000000raw('+'); } } class_alias('Twig_Node_Expression_Binary_Add', 'Twig\Node\Expression\Binary\AddBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/And.php000066400000000000000000000007651324654574500216270ustar00rootroot00000000000000raw('&&'); } } class_alias('Twig_Node_Expression_Binary_And', 'Twig\Node\Expression\Binary\AndBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/BitwiseAnd.php000066400000000000000000000010111324654574500231370ustar00rootroot00000000000000raw('&'); } } class_alias('Twig_Node_Expression_Binary_BitwiseAnd', 'Twig\Node\Expression\Binary\BitwiseAndBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/BitwiseOr.php000066400000000000000000000010061324654574500230210ustar00rootroot00000000000000raw('|'); } } class_alias('Twig_Node_Expression_Binary_BitwiseOr', 'Twig\Node\Expression\Binary\BitwiseOrBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/BitwiseXor.php000066400000000000000000000010111324654574500232050ustar00rootroot00000000000000raw('^'); } } class_alias('Twig_Node_Expression_Binary_BitwiseXor', 'Twig\Node\Expression\Binary\BitwiseXorBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Concat.php000066400000000000000000000007751324654574500223350ustar00rootroot00000000000000raw('.'); } } class_alias('Twig_Node_Expression_Binary_Concat', 'Twig\Node\Expression\Binary\ConcatBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Div.php000066400000000000000000000007641324654574500216460ustar00rootroot00000000000000raw('/'); } } class_alias('Twig_Node_Expression_Binary_Div', 'Twig\Node\Expression\Binary\DivBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/EndsWith.php000066400000000000000000000017421324654574500226460ustar00rootroot00000000000000getVarName(); $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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Equal.php000066400000000000000000000007451324654574500221720ustar00rootroot00000000000000raw('=='); } } class_alias('Twig_Node_Expression_Binary_Equal', 'Twig\Node\Expression\Binary\EqualBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/FloorDiv.php000066400000000000000000000012301324654574500226350ustar00rootroot00000000000000raw('(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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Greater.php000066400000000000000000000007521324654574500225120ustar00rootroot00000000000000raw('>'); } } class_alias('Twig_Node_Expression_Binary_Greater', 'Twig\Node\Expression\Binary\GreaterBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/GreaterEqual.php000066400000000000000000000007721324654574500235040ustar00rootroot00000000000000raw('>='); } } class_alias('Twig_Node_Expression_Binary_GreaterEqual', 'Twig\Node\Expression\Binary\GreaterEqualBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/In.php000066400000000000000000000013611324654574500214640ustar00rootroot00000000000000raw('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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Less.php000066400000000000000000000007411324654574500220250ustar00rootroot00000000000000raw('<'); } } class_alias('Twig_Node_Expression_Binary_Less', 'Twig\Node\Expression\Binary\LessBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/LessEqual.php000066400000000000000000000007611324654574500230170ustar00rootroot00000000000000raw('<='); } } class_alias('Twig_Node_Expression_Binary_LessEqual', 'Twig\Node\Expression\Binary\LessEqualBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Matches.php000066400000000000000000000013721324654574500225040ustar00rootroot00000000000000raw('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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Mod.php000066400000000000000000000007641324654574500216430ustar00rootroot00000000000000raw('%'); } } class_alias('Twig_Node_Expression_Binary_Mod', 'Twig\Node\Expression\Binary\ModBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Mul.php000066400000000000000000000007641324654574500216610ustar00rootroot00000000000000raw('*'); } } class_alias('Twig_Node_Expression_Binary_Mul', 'Twig\Node\Expression\Binary\MulBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/NotEqual.php000066400000000000000000000007561324654574500226550ustar00rootroot00000000000000raw('!='); } } class_alias('Twig_Node_Expression_Binary_NotEqual', 'Twig\Node\Expression\Binary\NotEqualBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/NotIn.php000066400000000000000000000013771324654574500221540ustar00rootroot00000000000000raw('!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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Or.php000066400000000000000000000007621324654574500215020ustar00rootroot00000000000000raw('||'); } } class_alias('Twig_Node_Expression_Binary_Or', 'Twig\Node\Expression\Binary\OrBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Power.php000066400000000000000000000007451324654574500222170ustar00rootroot00000000000000raw('**'); } } class_alias('Twig_Node_Expression_Binary_Power', 'Twig\Node\Expression\Binary\PowerBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Range.php000066400000000000000000000013611324654574500221520ustar00rootroot00000000000000raw('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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/StartsWith.php000066400000000000000000000017331324654574500232350ustar00rootroot00000000000000getVarName(); $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); Twig-2.4.6/lib/Twig/Node/Expression/Binary/Sub.php000066400000000000000000000007641324654574500216550ustar00rootroot00000000000000raw('-'); } } class_alias('Twig_Node_Expression_Binary_Sub', 'Twig\Node\Expression\Binary\SubBinary', false); Twig-2.4.6/lib/Twig/Node/Expression/BlockReference.php000066400000000000000000000045001324654574500225410ustar00rootroot00000000000000 */ class Twig_Node_Expression_BlockReference extends Twig_Node_Expression { public function __construct(Twig_Node $name, Twig_Node $template = null, $lineno, $tag = 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); Twig-2.4.6/lib/Twig/Node/Expression/Call.php000066400000000000000000000260671324654574500205570ustar00rootroot00000000000000getAttribute('callable'); $closingParenthesis = false; 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) { // For BC/FC with namespaced aliases $class = (new ReflectionClass(get_class($callable[0])))->name; if (!$compiler->getEnvironment()->hasExtension($class)) { throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class)); } $compiler->raw(sprintf('$this->extensions[\'%s\']->%s', ltrim($class, '\\'), $callable[1])); } else { $closingParenthesis = true; $compiler->raw(sprintf('call_user_func_array($this->env->get%s(\'%s\')->getCallable(), array', ucfirst($this->getAttribute('type')), $this->getAttribute('name'))); } } $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->getAttribute('callable'); $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 = null, $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)); } $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)); } 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)) ); } $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)); } } 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() : -1); } 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); Twig-2.4.6/lib/Twig/Node/Expression/Conditional.php000066400000000000000000000017431324654574500221410ustar00rootroot00000000000000 $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); Twig-2.4.6/lib/Twig/Node/Expression/Constant.php000066400000000000000000000012041324654574500214570ustar00rootroot00000000000000 $value), $lineno); } public function compile(Twig_Compiler $compiler) { $compiler->repr($this->getAttribute('value')); } } class_alias('Twig_Node_Expression_Constant', 'Twig\Node\Expression\ConstantExpression', false); Twig-2.4.6/lib/Twig/Node/Expression/Filter.php000066400000000000000000000025021324654574500211150ustar00rootroot00000000000000 $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('needs_environment', $filter->needsEnvironment()); $this->setAttribute('needs_context', $filter->needsContext()); $this->setAttribute('arguments', $filter->getArguments()); $this->setAttribute('callable', $filter->getCallable()); $this->setAttribute('is_variadic', $filter->isVariadic()); $this->compileCallable($compiler); } } class_alias('Twig_Node_Expression_Filter', 'Twig\Node\Expression\FilterExpression', false); Twig-2.4.6/lib/Twig/Node/Expression/Filter/000077500000000000000000000000001324654574500204055ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Node/Expression/Filter/Default.php000066400000000000000000000032511324654574500225030ustar00rootroot00000000000000 * {{ 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_Node $node, Twig_Node_Expression_Constant $filterName, Twig_Node $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); Twig-2.4.6/lib/Twig/Node/Expression/Function.php000066400000000000000000000026221324654574500214600ustar00rootroot00000000000000 $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('needs_environment', $function->needsEnvironment()); $this->setAttribute('needs_context', $function->needsContext()); $this->setAttribute('arguments', $function->getArguments()); $callable = $function->getCallable(); if ('constant' === $name && $this->getAttribute('is_defined_test')) { $callable = 'twig_constant_is_defined'; } $this->setAttribute('callable', $callable); $this->setAttribute('is_variadic', $function->isVariadic()); $this->compileCallable($compiler); } } class_alias('Twig_Node_Expression_Function', 'Twig\Node\Expression\FunctionExpression', false); Twig-2.4.6/lib/Twig/Node/Expression/GetAttr.php000066400000000000000000000064061324654574500212510ustar00rootroot00000000000000 $node, 'attribute' => $attribute); if (null !== $arguments) { $nodes['arguments'] = $arguments; } parent::__construct($nodes, array('type' => $type, 'is_defined_test' => false, 'ignore_strict_check' => false), $lineno); } public function compile(Twig_Compiler $compiler) { $env = $compiler->getEnvironment(); // optimize array calls if ( (!$env->isStrictVariables() || $this->getAttribute('ignore_strict_check')) && !$this->getAttribute('is_defined_test') && Twig_Template::ARRAY_CALL === $this->getAttribute('type') ) { $var = '$'.$compiler->getVarName(); $compiler ->raw('(('.$var.' = ') ->subcompile($this->getNode('node')) ->raw(') && is_array(') ->raw($var) ->raw(') || ') ->raw($var) ->raw(' instanceof ArrayAccess ? (') ->raw($var) ->raw('[') ->subcompile($this->getNode('attribute')) ->raw('] ?? null) : null)') ; return; } $compiler->raw('twig_get_attribute($this->env, $this->source, '); 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) $needFifth = $env->hasExtension('Twig_Extension_Sandbox'); $needFourth = $needFifth || $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')); } if ($needFifth) { $compiler->raw(', ')->repr($env->hasExtension('Twig_Extension_Sandbox')); } $compiler->raw(')'); } } class_alias('Twig_Node_Expression_GetAttr', 'Twig\Node\Expression\GetAttrExpression', false); Twig-2.4.6/lib/Twig/Node/Expression/MethodCall.php000066400000000000000000000024231324654574500217060ustar00rootroot00000000000000 $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); Twig-2.4.6/lib/Twig/Node/Expression/Name.php000066400000000000000000000051151324654574500205530ustar00rootroot00000000000000 '$this->getTemplateName()', '_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('array_key_exists(')->repr($name)->raw(', $context)'); } } elseif ($this->isSpecial()) { $compiler->raw($this->specialVars[$name]); } elseif ($this->getAttribute('always_defined')) { $compiler ->raw('$context[') ->string($name) ->raw(']') ; } else { if ($this->getAttribute('ignore_strict_check') || !$compiler->getEnvironment()->isStrictVariables()) { $compiler ->raw('($context[') ->string($name) ->raw('] ?? null)') ; } else { $compiler ->raw('(isset($context[') ->string($name) ->raw(']) || array_key_exists(') ->string($name) ->raw(', $context) ? $context[') ->string($name) ->raw('] : (function () { throw new Twig_Error_Runtime(\'Variable ') ->string($name) ->raw(' does not exist.\', ') ->repr($this->lineno) ->raw(', $this->source); })()') ->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); Twig-2.4.6/lib/Twig/Node/Expression/NullCoalesce.php000066400000000000000000000035521324654574500222470ustar00rootroot00000000000000getTemplateLine()), 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 ($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); Twig-2.4.6/lib/Twig/Node/Expression/Parent.php000066400000000000000000000022601324654574500211220ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/Expression/TempName.php000066400000000000000000000012561324654574500214030ustar00rootroot00000000000000 $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); Twig-2.4.6/lib/Twig/Node/Expression/Test.php000066400000000000000000000021171324654574500206110ustar00rootroot00000000000000 $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('callable', $test->getCallable()); $this->setAttribute('is_variadic', $test->isVariadic()); $this->compileCallable($compiler); } } class_alias('Twig_Node_Expression_Test', 'Twig\Node\Expression\TestExpression', false); Twig-2.4.6/lib/Twig/Node/Expression/Test/000077500000000000000000000000001324654574500200775ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Node/Expression/Test/Constant.php000066400000000000000000000023121324654574500223770ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/Node/Expression/Test/Defined.php000066400000000000000000000042231324654574500221470ustar00rootroot00000000000000 * {# 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_Node $node, $name, Twig_Node $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); } private 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); Twig-2.4.6/lib/Twig/Node/Expression/Test/Divisibleby.php000066400000000000000000000015221324654574500230550ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/Node/Expression/Test/Even.php000066400000000000000000000013241324654574500215050ustar00rootroot00000000000000 * {{ 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); Twig-2.4.6/lib/Twig/Node/Expression/Test/Null.php000066400000000000000000000013021324654574500215160ustar00rootroot00000000000000 * {{ 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); Twig-2.4.6/lib/Twig/Node/Expression/Test/Odd.php000066400000000000000000000013171324654574500213200ustar00rootroot00000000000000 * {{ 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); Twig-2.4.6/lib/Twig/Node/Expression/Test/Sameas.php000066400000000000000000000014161324654574500220230ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/Expression/Unary.php000066400000000000000000000014211324654574500207650ustar00rootroot00000000000000 $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); Twig-2.4.6/lib/Twig/Node/Expression/Unary/000077500000000000000000000000001324654574500202565ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Node/Expression/Unary/Neg.php000066400000000000000000000007501324654574500215020ustar00rootroot00000000000000raw('-'); } } class_alias('Twig_Node_Expression_Unary_Neg', 'Twig\Node\Expression\Unary\NegUnary', false); Twig-2.4.6/lib/Twig/Node/Expression/Unary/Not.php000066400000000000000000000007501324654574500215310ustar00rootroot00000000000000raw('!'); } } class_alias('Twig_Node_Expression_Unary_Not', 'Twig\Node\Expression\Unary\NotUnary', false); Twig-2.4.6/lib/Twig/Node/Expression/Unary/Pos.php000066400000000000000000000007501324654574500215320ustar00rootroot00000000000000raw('+'); } } class_alias('Twig_Node_Expression_Unary_Pos', 'Twig\Node\Expression\Unary\PosUnary', false); Twig-2.4.6/lib/Twig/Node/Flush.php000066400000000000000000000012501324654574500166110ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/For.php000066400000000000000000000102701324654574500162600ustar00rootroot00000000000000 */ class Twig_Node_For extends Twig_Node { private $loop; public function __construct(Twig_Node_Expression_AssignName $keyTarget, Twig_Node_Expression_AssignName $valueTarget, Twig_Node_Expression $seq, Twig_Node_Expression $ifexpr = null, Twig_Node $body, Twig_Node $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); Twig-2.4.6/lib/Twig/Node/ForLoop.php000066400000000000000000000030501324654574500171100ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/If.php000066400000000000000000000032351324654574500160730ustar00rootroot00000000000000 */ class Twig_Node_If extends Twig_Node { public function __construct(Twig_Node $tests, Twig_Node $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); Twig-2.4.6/lib/Twig/Node/Import.php000066400000000000000000000025541324654574500170120ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/Include.php000066400000000000000000000050061324654574500171160ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/Macro.php000066400000000000000000000057041324654574500166010ustar00rootroot00000000000000 */ class Twig_Node_Macro extends Twig_Node { const VARARGS_NAME = 'varargs'; public function __construct($name, Twig_Node $body, Twig_Node $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 macro_%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 ($count) { $compiler->raw(', '); } $compiler ->raw('...$__varargs__') ->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(' => ') ; $compiler ->raw("\$__varargs__,\n") ->outdent() ->write("));\n\n") ->write("\$blocks = array();\n\n") ->write("ob_start();\n") ->write("try {\n") ->indent() ->subcompile($this->getNode('body')) ->raw("\n") ->write("return ('' === \$tmp = ob_get_contents()) ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset());\n") ->outdent() ->write("} finally {\n") ->indent() ->write("ob_end_clean();\n") ->outdent() ->write("}\n") ->outdent() ->write("}\n\n") ; } } class_alias('Twig_Node_Macro', 'Twig\Node\MacroNode', false); Twig-2.4.6/lib/Twig/Node/Module.php000066400000000000000000000335571324654574500167740ustar00rootroot00000000000000 * * @final since version 2.4.0 */ class Twig_Node_Module extends Twig_Node { private $source; public function __construct(Twig_Node $body, Twig_Node_Expression $parent = null, Twig_Node $blocks, Twig_Node $macros, Twig_Node $traits, $embeddedTemplates, Twig_Source $source) { if (__CLASS__ !== get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since version 2.4.0 and the class will be final in 3.0.', E_USER_DEPRECATED); } $this->source = $source; $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( '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); $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->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() ->write("private \$source;\n\n") ; } 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") ->write("\$this->source = \$this->getSourceContext();\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) { $node = $trait->getNode('template'); $compiler ->write(sprintf('$_trait_%s = $this->loadTemplate(', $i)) ->subcompile($node) ->raw(', ') ->repr($node->getTemplateName()) ->raw(', ') ->repr($node->getTemplateLine()) ->raw(");\n") ; $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 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); Twig-2.4.6/lib/Twig/Node/Print.php000066400000000000000000000015561324654574500166350ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/Sandbox.php000066400000000000000000000022731324654574500171340ustar00rootroot00000000000000 */ class Twig_Node_Sandbox extends Twig_Node { public function __construct(Twig_Node $body, $lineno, $tag = null) { parent::__construct(array('body' => $body), array(), $lineno, $tag); } public function compile(Twig_Compiler $compiler) { $compiler ->addDebugInfo($this) ->write("\$sandbox = \$this->extensions['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); Twig-2.4.6/lib/Twig/Node/SandboxedPrint.php000066400000000000000000000026161324654574500204630ustar00rootroot00000000000000 */ class Twig_Node_SandboxedPrint extends Twig_Node_Print { public function compile(Twig_Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('echo $this->extensions[\'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 */ private 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); Twig-2.4.6/lib/Twig/Node/Set.php000066400000000000000000000061741324654574500162750ustar00rootroot00000000000000 */ class Twig_Node_Set extends Twig_Node implements Twig_NodeCaptureInterface { public function __construct($capture, Twig_Node $names, Twig_Node $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); Twig-2.4.6/lib/Twig/Node/Spaceless.php000066400000000000000000000016301324654574500174540ustar00rootroot00000000000000 */ class Twig_Node_Spaceless extends Twig_Node { public function __construct(Twig_Node $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); Twig-2.4.6/lib/Twig/Node/Text.php000066400000000000000000000014561324654574500164640ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Node/With.php000066400000000000000000000036541324654574500164550ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/NodeCaptureInterface.php000066400000000000000000000007031324654574500206770ustar00rootroot00000000000000 */ interface Twig_NodeCaptureInterface { } class_alias('Twig_NodeCaptureInterface', 'Twig\Node\NodeCaptureInterface', false); Twig-2.4.6/lib/Twig/NodeOutputInterface.php000066400000000000000000000006541324654574500206010ustar00rootroot00000000000000 */ interface Twig_NodeOutputInterface { } class_alias('Twig_NodeOutputInterface', 'Twig\Node\NodeOutputInterface', false); Twig-2.4.6/lib/Twig/NodeTraverser.php000066400000000000000000000037361324654574500174410ustar00rootroot00000000000000 */ final class Twig_NodeTraverser { private $env; private $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_Node */ public function traverse(Twig_Node $node) { ksort($this->visitors); foreach ($this->visitors as $visitors) { foreach ($visitors as $visitor) { $node = $this->traverseForVisitor($visitor, $node); } } return $node; } private function traverseForVisitor(Twig_NodeVisitorInterface $visitor, Twig_Node $node) { $node = $visitor->enterNode($node, $this->env); foreach ($node as $k => $n) { if (false !== $n = $this->traverseForVisitor($visitor, $n)) { $node->setNode($k, $n); } else { $node->removeNode($k); } } return $visitor->leaveNode($node, $this->env); } } class_alias('Twig_NodeTraverser', 'Twig\NodeTraverser', false); Twig-2.4.6/lib/Twig/NodeVisitor/000077500000000000000000000000001324654574500164015ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/NodeVisitor/Escaper.php000066400000000000000000000115501324654574500204760ustar00rootroot00000000000000 */ final class Twig_NodeVisitor_Escaper extends Twig_BaseNodeVisitor { private $statusStack = array(); private $blocks = array(); private $safeAnalysis; private $traverser; private $defaultStrategy = false; private $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; } private 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() ); } private 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; } private function isSafeFor($type, Twig_Node $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); } private function needEscaping(Twig_Environment $env) { if (count($this->statusStack)) { return $this->statusStack[count($this->statusStack) - 1]; } return $this->defaultStrategy ? $this->defaultStrategy : false; } private function getEscaperFilter($type, Twig_Node $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); Twig-2.4.6/lib/Twig/NodeVisitor/Optimizer.php000066400000000000000000000146051324654574500211020ustar00rootroot00000000000000 */ final class Twig_NodeVisitor_Optimizer extends Twig_BaseNodeVisitor { const OPTIMIZE_ALL = -1; const OPTIMIZE_NONE = 0; const OPTIMIZE_FOR = 2; const OPTIMIZE_RAW_FILTER = 4; // obsolete, does not do anything const OPTIMIZE_VAR_ACCESS = 8; private $loops = array(); private $loopsTargets = array(); private $optimizers; /** * @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); } return $node; } protected function doLeaveNode(Twig_Node $node, Twig_Environment $env) { 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); return $node; } /** * Optimizes print nodes. * * It replaces: * * * "echo $this->render(Parent)Block()" with "$this->display(Parent)Block()" * * @return Twig_Node */ private function optimizePrintNode(Twig_Node $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_Node */ private function optimizeRawFilter(Twig_Node $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. */ private function enterOptimizeFor(Twig_Node $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. */ private function leaveOptimizeFor(Twig_Node $node, Twig_Environment $env) { if ($node instanceof Twig_Node_For) { array_shift($this->loops); array_shift($this->loopsTargets); array_shift($this->loopsTargets); } } private function addLoopToCurrent() { $this->loops[0]->setAttribute('with_loop', true); } private 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); Twig-2.4.6/lib/Twig/NodeVisitor/SafeAnalysis.php000066400000000000000000000112011324654574500214670ustar00rootroot00000000000000safeVars = $safeVars; } public function getSafe(Twig_Node $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']; } } private function setSafe(Twig_Node $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'); if (in_array($name, $this->safeVars)) { $this->setSafe($node, array('all')); } else { $this->setSafe($node, array()); } } else { $this->setSafe($node, array()); } return $node; } private 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); Twig-2.4.6/lib/Twig/NodeVisitor/Sandbox.php000066400000000000000000000044561324654574500205210ustar00rootroot00000000000000 */ final class Twig_NodeVisitor_Sandbox extends Twig_BaseNodeVisitor { private $inAModule = false; private $tags; private $filters; private $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; } // 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); Twig-2.4.6/lib/Twig/NodeVisitorInterface.php000066400000000000000000000022211324654574500207300ustar00rootroot00000000000000 */ interface Twig_NodeVisitorInterface { /** * Called before child nodes are visited. * * @return Twig_Node The modified node */ public function enterNode(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 */ public function leaveNode(Twig_Node $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'); Twig-2.4.6/lib/Twig/Parser.php000066400000000000000000000246221324654574500161070ustar00rootroot00000000000000 */ class Twig_Parser { private $stack = array(); private $stream; private $parent; private $handlers; private $visitors; private $expressionParser; private $blocks; private $blockStack; private $macros; private $env; private $importedSymbols; private $traits; private $embeddedTemplates = array(); private $varNameSalt = 0; public function __construct(Twig_Environment $env) { $this->env = $env; } public function getVarName() { return sprintf('__internal_%s', hash('sha256', __METHOD__.$this->varNameSalt++)); } public function parse(Twig_TokenStream $stream, $test = null, $dropNeedle = false) { $vars = get_object_vars($this); unset($vars['stack'], $vars['env'], $vars['handlers'], $vars['visitors'], $vars['expressionParser'], $vars['reservedMacroNames']); $this->stack[] = $vars; // tag handlers if (null === $this->handlers) { $this->handlers = array(); foreach ($this->env->getTokenParsers() as $handler) { $handler->setParser($this); $this->handlers[$handler->getTag()] = $handler; } } // 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 && $test($token)) { if ($dropNeedle) { $this->stream->next(); } if (1 === count($rv)) { return $rv[0]; } return new Twig_Node($rv, array(), $lineno); } if (!isset($this->handlers[$token->getValue()])) { 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(); $subparser = $this->handlers[$token->getValue()]; $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); } 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) { $this->macros[$name] = $node; } public function isReservedMacroName($name) { return false; } 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(); } private function filterBodyNodes(Twig_Node $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'); Twig-2.4.6/lib/Twig/Profiler/000077500000000000000000000000001324654574500157165ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Profiler/Dumper/000077500000000000000000000000001324654574500171525ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Profiler/Dumper/Base.php000066400000000000000000000034531324654574500205420ustar00rootroot00000000000000 */ 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'); Twig-2.4.6/lib/Twig/Profiler/Dumper/Blackfire.php000066400000000000000000000040271324654574500215500ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Profiler/Dumper/Html.php000066400000000000000000000027651324654574500206010ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Profiler/Dumper/Text.php000066400000000000000000000017101324654574500206060ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Profiler/Node/000077500000000000000000000000001324654574500166035ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Profiler/Node/EnterProfile.php000066400000000000000000000023651324654574500217200ustar00rootroot00000000000000 */ 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->extensions[', $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); Twig-2.4.6/lib/Twig/Profiler/Node/LeaveProfile.php000066400000000000000000000014711324654574500216740ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Profiler/NodeVisitor/000077500000000000000000000000001324654574500201635ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Profiler/NodeVisitor/Profiler.php000066400000000000000000000044131324654574500224600ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Profiler/Profile.php000066400000000000000000000100131324654574500200220ustar00rootroot00000000000000 * * @final since version 2.4.0 */ 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') { if (__CLASS__ !== get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since version 2.4.0 and the class will be final in 3.0.', E_USER_DEPRECATED); } $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); Twig-2.4.6/lib/Twig/RuntimeLoaderInterface.php000066400000000000000000000014361324654574500212440ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Sandbox/000077500000000000000000000000001324654574500155325ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Sandbox/SecurityError.php000066400000000000000000000007141324654574500210660ustar00rootroot00000000000000 */ class Twig_Sandbox_SecurityError extends Twig_Error { } class_alias('Twig_Sandbox_SecurityError', 'Twig\Sandbox\SecurityError', false); Twig-2.4.6/lib/Twig/Sandbox/SecurityNotAllowedFilterError.php000066400000000000000000000015641324654574500242310ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Sandbox/SecurityNotAllowedFunctionError.php000066400000000000000000000016041324654574500245640ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Sandbox/SecurityNotAllowedMethodError.php000066400000000000000000000020161324654574500242150ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Sandbox/SecurityNotAllowedPropertyError.php000066400000000000000000000020421324654574500246200ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Sandbox/SecurityNotAllowedTagError.php000066400000000000000000000015221324654574500235110ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/Sandbox/SecurityPolicy.php000066400000000000000000000076061324654574500212430ustar00rootroot00000000000000 */ final class Twig_Sandbox_SecurityPolicy implements Twig_Sandbox_SecurityPolicyInterface { private $allowedTags; private $allowedFilters; private $allowedMethods; private $allowedProperties; private $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_Template || $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); Twig-2.4.6/lib/Twig/Sandbox/SecurityPolicyInterface.php000066400000000000000000000012201324654574500230460ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/SimpleFilter.php000066400000000000000000000005401324654574500172430ustar00rootroot00000000000000 */ final 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); Twig-2.4.6/lib/Twig/SourceContextLoaderInterface.php000066400000000000000000000006641324654574500224300ustar00rootroot00000000000000load() * instead, which returns an instance of Twig_TemplateWrapper. * * @author Fabien Potencier * * @internal */ abstract class Twig_Template { const ANY_CALL = 'any'; const ARRAY_CALL = 'array'; const METHOD_CALL = 'method'; protected $parent; protected $parents = array(); protected $env; protected $blocks = array(); protected $traits = array(); /** * @internal */ protected $extensions = array(); public function __construct(Twig_Environment $env) { $this->env = $env; foreach ($env->getExtensions() as $extension) { // For BC/FC with namespaced aliases $class = (new ReflectionClass(get_class($extension)))->name; $this->extensions[ltrim($class, '\\')] = $extension; } } /** * @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 */ abstract public function getDebugInfo(); /** * Returns information about the original template source code. * * @return Twig_Source */ public function getSourceContext() { return new Twig_Source('', $this->getTemplateName()); } /** * Returns the parent template. * * This method is for internal use only and should never be called * directly. * * @param array $context * * @return Twig_Template|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()) { 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) { 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); } elseif (isset($blocks[$name])) { throw new Twig_Error_Runtime(sprintf('Block "%s" should not call parent() in "%s" as the block does not exist in the parent template "%s".', $name, $blocks[$name][0]->getTemplateName(), $this->getTemplateName()), -1, $blocks[$name][0]->getTemplateName()); } else { throw new Twig_Error_Runtime(sprintf('Block "%s" on template "%s" does not exist.', $name, $this->getTemplateName()), -1, $this->getTemplateName()); } } /** * 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, array $blocks = array()) { 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, array $blocks = array()) { $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 (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()); } class_alias('Twig_Template', 'Twig\Template', false); Twig-2.4.6/lib/Twig/TemplateWrapper.php000066400000000000000000000061121324654574500177610ustar00rootroot00000000000000 */ 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 (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); Twig-2.4.6/lib/Twig/Test.php000066400000000000000000000043351324654574500155710ustar00rootroot00000000000000 * * @see http://twig.sensiolabs.org/doc/templates.html#test-operator */ class Twig_Test { private $name; private $callable; private $options; /** * Creates a template test. * * @param string $name Name of this test * @param callable|null $callable A callable implementing the test. If null, you need to overwrite the "node_class" option to customize compilation. * @param array $options Options array */ public function __construct(string $name, $callable = null, array $options = array()) { if (__CLASS__ !== get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since version 2.4.0 and the class will be final in 3.0.', E_USER_DEPRECATED); } $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; } /** * Returns the callable to execute for this test. * * @return callable|null */ 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']; } } // For Twig 1.x compatibility class_alias('Twig_Test', 'Twig_SimpleTest', false); class_alias('Twig_Test', 'Twig\TwigTest', false); Twig-2.4.6/lib/Twig/Test/000077500000000000000000000000001324654574500150535ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Test/IntegrationTestCase.php000066400000000000000000000176051324654574500215140ustar00rootroot00000000000000 * @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_Filter[] */ protected function getTwigFilters() { return array(); } /** * @return Twig_Function[] */ protected function getTwigFunctions() { return array(); } /** * @return Twig_Test[] */ 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 legacy 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 $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"; echo $twig->compile($twig->parse($twig->tokenize($twig->getLoader()->getSourceContext($name)))); } } $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); Twig-2.4.6/lib/Twig/Test/NodeTestCase.php000066400000000000000000000033521324654574500201100ustar00rootroot00000000000000assertNodeCompilation($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" : ''; return sprintf('%s($context["%s"] ?? null)', $line, $name, $name); } protected function getAttributeGetter() { return 'twig_get_attribute($this->env, $this->source, '; } } class_alias('Twig_Test_NodeTestCase', 'Twig\Test\NodeTestCase', false); class_exists('Twig_Environment'); class_exists('Twig_Node'); Twig-2.4.6/lib/Twig/Token.php000066400000000000000000000132131324654574500157250ustar00rootroot00000000000000 */ final class Twig_Token { private $value; private $type; private $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|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); Twig-2.4.6/lib/Twig/TokenParser.php000066400000000000000000000012571324654574500171070ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/TokenParser/000077500000000000000000000000001324654574500163715ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/TokenParser/AutoEscape.php000066400000000000000000000027371324654574500211440ustar00rootroot00000000000000getLine(); $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 false.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); } $value = $expr->getAttribute('value'); } $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); Twig-2.4.6/lib/Twig/TokenParser/Block.php000066400000000000000000000045701324654574500201420ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Do.php000066400000000000000000000013571324654574500174520ustar00rootroot00000000000000parser->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); Twig-2.4.6/lib/Twig/TokenParser/Embed.php000066400000000000000000000042441324654574500201220ustar00rootroot00000000000000parser->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); Twig-2.4.6/lib/Twig/TokenParser/Extends.php000066400000000000000000000022071324654574500205150ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Filter.php000066400000000000000000000027111324654574500203300ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Flush.php000066400000000000000000000012521324654574500201630ustar00rootroot00000000000000parser->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); Twig-2.4.6/lib/Twig/TokenParser/For.php000066400000000000000000000107651324654574500176410ustar00rootroot00000000000000 *
      * {% 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 private function checkLoopUsageCondition(Twig_TokenStream $stream, Twig_Node $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) private function checkLoopUsageBody(Twig_TokenStream $stream, Twig_Node $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); Twig-2.4.6/lib/Twig/TokenParser/From.php000066400000000000000000000030431324654574500200050ustar00rootroot00000000000000 * {% 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) { $this->parser->addImportedSymbol('function', $alias, 'macro_'.$name, $node->getNode('var')); } return $node; } public function getTag() { return 'from'; } } class_alias('Twig_TokenParser_From', 'Twig\TokenParser\FromTokenParser', false); Twig-2.4.6/lib/Twig/TokenParser/If.php000066400000000000000000000046611324654574500174470ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Import.php000066400000000000000000000020631324654574500203550ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Include.php000066400000000000000000000031201324654574500204610ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Macro.php000066400000000000000000000034241324654574500201460ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Sandbox.php000066400000000000000000000033231324654574500205010ustar00rootroot00000000000000 * {% sandbox %} * {% include 'user.html' %} * {% endsandbox %} * * * @see http://www.twig-project.org/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); Twig-2.4.6/lib/Twig/TokenParser/Set.php000066400000000000000000000040251324654574500176360ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Spaceless.php000066400000000000000000000022311324654574500210220ustar00rootroot00000000000000 * {% 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); Twig-2.4.6/lib/Twig/TokenParser/Use.php000066400000000000000000000036321324654574500176420ustar00rootroot00000000000000 * {% extends "base.html" %} * * {% use "blocks.html" %} * * {% block title %}{% endblock %} * {% block content %}{% endblock %} * * * @see http://www.twig-project.org/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); Twig-2.4.6/lib/Twig/TokenParser/With.php000066400000000000000000000023561324654574500200230ustar00rootroot00000000000000 */ 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); Twig-2.4.6/lib/Twig/TokenParserInterface.php000066400000000000000000000017061324654574500207270ustar00rootroot00000000000000 */ 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_Node A Twig_Node instance * * @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'); Twig-2.4.6/lib/Twig/TokenStream.php000066400000000000000000000073751324654574500171150ustar00rootroot00000000000000 */ final class Twig_TokenStream { private $tokens; private $current = 0; private $source; /** * @param array $tokens An array of tokens * @param Twig_Source $source */ public function __construct(array $tokens, Twig_Source $source = null) { $this->tokens = $tokens; $this->source = $source ?: new Twig_Source('', ''); } 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 source associated with this stream. * * @return Twig_Source * * @internal */ public function getSourceContext() { return $this->source; } } class_alias('Twig_TokenStream', 'Twig\TokenStream', false); Twig-2.4.6/lib/Twig/Util/000077500000000000000000000000001324654574500150515ustar00rootroot00000000000000Twig-2.4.6/lib/Twig/Util/DeprecationCollector.php000066400000000000000000000040131324654574500216640ustar00rootroot00000000000000 */ final class Twig_Util_DeprecationCollector { private $twig; 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) { $deprecations = array(); set_error_handler(function ($type, $msg) use (&$deprecations) { if (E_USER_DEPRECATED === $type) { $deprecations[] = $msg; } }); 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(); return $deprecations; } } class_alias('Twig_Util_DeprecationCollector', 'Twig\Util\DeprecationCollector', false); Twig-2.4.6/lib/Twig/Util/TemplateDirIterator.php000066400000000000000000000011101324654574500214770ustar00rootroot00000000000000 */ 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); Twig-2.4.6/phpunit.xml.dist000066400000000000000000000014571324654574500156360ustar00rootroot00000000000000 ./test/Twig/ ./lib/Twig/ Twig-2.4.6/src/000077500000000000000000000000001324654574500132435ustar00rootroot00000000000000Twig-2.4.6/src/Cache/000077500000000000000000000000001324654574500142465ustar00rootroot00000000000000Twig-2.4.6/src/Cache/CacheInterface.php000066400000000000000000000002321324654574500176000ustar00rootroot00000000000000 */ interface RuntimeExtensionInterface { } Twig-2.4.6/src/Extension/SandboxExtension.php000066400000000000000000000002421324654574500212210ustar00rootroot00000000000000classname = '__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, )); } } Twig-2.4.6/test/Twig/Tests/CompilerTest.php000066400000000000000000000021331324654574500205710ustar00rootroot00000000000000getMockBuilder('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); } } Twig-2.4.6/test/Twig/Tests/ContainerRuntimeLoaderTest.php000066400000000000000000000022071324654574500234360ustar00rootroot00000000000000getMockBuilder(ContainerInterface::class)->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')); } public function testLoadUnknownRuntimeReturnsNull() { $container = $this->getMockBuilder(ContainerInterface::class)->getMock(); $container->expects($this->once())->method('has')->with('Foo'); $container->expects($this->never())->method('get'); $this->assertNull((new Twig_ContainerRuntimeLoader($container))->load('Foo')); } } Twig-2.4.6/test/Twig/Tests/CustomExtensionTest.php000066400000000000000000000036671324654574500222030ustar00rootroot00000000000000expectException('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 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 getOperators() { return $this->operators; } } Twig-2.4.6/test/Twig/Tests/EnvironmentTest.php000066400000000000000000000447761324654574500213460ustar00rootroot00000000000000 '{{ 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\x3Cbr\x2F\x20\x3E foo\x3Cbr\x2F\x20\x3E', $twig->render('js', array('bar' => 'foo
    '))); } public function escapingStrategyCallback($name) { return $name; } public function testGlobals() { $loader = $this->getMockBuilder('Twig_LoaderInterface')->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())); // 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->assertArrayNotHasKey('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->assertArrayNotHasKey('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->assertArrayNotHasKey('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->assertArrayNotHasKey('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); } 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); } public function testAddMockExtension() { $extension = $this->getMockBuilder('Twig_ExtensionInterface')->getMock(); $loader = new Twig_Loader_Array(array('page' => '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() { $loader = $this->getMockBuilder('Twig_LoaderInterface')->getMock(); $twig = new Twig_Environment($loader); $loader->expects($this->once())->method('getSourceContext')->will($this->returnValue(new Twig_Source('', ''))); $twig->addExtension(new Twig_Tests_EnvironmentTest_ExtensionWithoutDeprecationInitRuntime()); $twig->loadTemplate(''); // 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); } /** * @expectedException LogicException * @expectedExceptionMessage Unable to register extension "Twig_Tests_EnvironmentTest_Extension" as it is already registered. */ public function testOverrideExtension() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension()); $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension()); } 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 Failed to load Twig template "testFailLoadTemplate.twig", index "abc": cache is corrupted in "testFailLoadTemplate.twig". */ public function testFailLoadTemplate() { $template = 'testFailLoadTemplate.twig'; $twig = new Twig_Environment(new Twig_Loader_Array(array($template => false))); //$twig->setCache(new CorruptCache()); $twig->loadTemplate($template, 'abc'); } /** * @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) { $loader = $this->getMockBuilder('Twig_LoaderInterface')->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 CorruptCache implements Twig_CacheInterface { public function generateKey($name, $className) { return $name.':'.$className; } public function write($key, $content) { } public function load($key) { } public function getTimestamp($key) { time(); } } 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_Filter('foo_filter'), ); } public function getTests() { return array( new Twig_Test('foo_test'), ); } public function getFunctions() { return array( new Twig_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_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_Node $node, Twig_Environment $env) { return $node; } public function leaveNode(Twig_Node $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_Function('from_runtime_array', array('Twig_Tests_EnvironmentTest_Runtime', 'fromRuntime')), new Twig_Function('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; } } Twig-2.4.6/test/Twig/Tests/ErrorTest.php000066400000000000000000000166011324654574500201150ustar00rootroot00000000000000setSourceContext(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(__DIR__.'/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(__DIR__.'/Fixtures/errors/index.html', '/', DIRECTORY_SEPARATOR), $e->getFile()); } } public function testTwigExceptionGuessWithExceptionAndFilesystemLoader() { $loader = new Twig_Loader_Filesystem(__DIR__.'/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(__DIR__.'/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...'); } } Twig-2.4.6/test/Twig/Tests/ExpressionParserTest.php000066400000000000000000000351131324654574500223370ustar00rootroot00000000000000getMockBuilder('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'))); } } Twig-2.4.6/test/Twig/Tests/Extension/000077500000000000000000000000001324654574500174235ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Extension/CoreTest.php000066400000000000000000000255401324654574500216720ustar00rootroot00000000000000getMockBuilder('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() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $twig->setCharset('ISO-8859-1'); $text = iconv('UTF-8', 'ISO-8859-1', 'Äé'); for ($i = 0; $i < 30; ++$i) { $rand = twig_random($twig, $text); $this->assertTrue(in_array(iconv('ISO-8859-1', 'UTF-8', $rand), array('Ä', 'é'), true)); } } public function testReverseFilterOnNonUTF8String() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $twig->setCharset('ISO-8859-1'); $input = iconv('UTF-8', 'ISO-8859-1', 'Äé'); $output = iconv('ISO-8859-1', 'UTF-8', twig_reverse_filter($twig, $input)); $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]); } } Twig-2.4.6/test/Twig/Tests/Extension/SandboxTest.php000066400000000000000000000332071324654574500223770ustar00rootroot00000000000000 '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) }}', ); } /** * @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 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 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) { } 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'; } } Twig-2.4.6/test/Twig/Tests/FactoryRuntimeLoaderTest.php000066400000000000000000000013151324654574500231220ustar00rootroot00000000000000 'getRuntime')); $this->assertInstanceOf('stdClass', $loader->load('stdClass')); } public function testLoadReturnsNullForUnmappedRuntime() { $loader = new Twig_FactoryRuntimeLoader(); $this->assertNull($loader->load('stdClass')); } } function getRuntime() { return new stdClass(); } Twig-2.4.6/test/Twig/Tests/FileExtensionEscapingStrategyTest.php000066400000000000000000000025211324654574500247710ustar00rootroot00000000000000assertSame($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'), ); } } Twig-2.4.6/test/Twig/Tests/FilesystemHelper.php000066400000000000000000000012541324654574500214460ustar00rootroot00000000000000 $fileInfo) { if ($fileInfo->isDir()) { rmdir($filename); } else { unlink($filename); } } rmdir($dir); } } Twig-2.4.6/test/Twig/Tests/Fixtures/000077500000000000000000000000001324654574500172605ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/autoescape/000077500000000000000000000000001324654574500214115ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/autoescape/block.test000066400000000000000000000007641324654574500234130ustar00rootroot00000000000000--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 /> Twig-2.4.6/test/Twig/Tests/Fixtures/autoescape/name.test000066400000000000000000000006521324654574500232350ustar00rootroot00000000000000--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 /> \x3Cbr\x20\x2F\x3E <br />
    Twig-2.4.6/test/Twig/Tests/Fixtures/errors/000077500000000000000000000000001324654574500205745ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/errors/base.html000066400000000000000000000000421324654574500223700ustar00rootroot00000000000000{% block content %}{% endblock %} Twig-2.4.6/test/Twig/Tests/Fixtures/errors/index.html000066400000000000000000000002001324654574500225610ustar00rootroot00000000000000{% extends 'base.html' %} {% block content %} {{ foo.bar }} {% endblock %} {% block foo %} {{ foo.bar }} {% endblock %} Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/000077500000000000000000000000001324654574500214415ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/child_contents_outside_blocks.test000066400000000000000000000007341324654574500304370ustar00rootroot00000000000000--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? Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable.test000066400000000000000000000004561324654574500324700ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/multiline_array_with_undefined_variable_again.test000066400000000000000000000004331324654574500336220ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_undefined_variable.test000066400000000000000000000004231324654574500331710ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/multiline_function_with_unknown_argument.test000066400000000000000000000004671324654574500327740ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/multiline_tag_with_undefined_variable.test000066400000000000000000000003651324654574500321240ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/strict_comparison_operator.test000066400000000000000000000004231324654574500300160ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/syntax_error_in_reused_template.test000066400000000000000000000004611324654574500310320ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/unclosed_tag.test000066400000000000000000000004641324654574500250150ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/undefined_parent.test000066400000000000000000000003071324654574500256540ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/undefined_template_in_child_template.test000066400000000000000000000005441324654574500317250ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/exceptions/undefined_trait.test000066400000000000000000000003651324654574500255120ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/000077500000000000000000000000001324654574500216425ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/_self.test000066400000000000000000000001601324654574500236300ustar00rootroot00000000000000--TEST-- _self returns the template name --TEMPLATE-- {{ _self }} --DATA-- return array() --EXPECT-- index.twig Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/array.test000066400000000000000000000021431324654574500236610ustar00rootroot00000000000000--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(',') }} {# ArrayAccess #} {{ array_access['a'] }} --DATA-- return array('bar' => 'bar', 'foo' => array('bar' => 'bar'), 'array_access' => new ArrayObject(array('a' => 'b'))) --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 b Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/array_call.test000066400000000000000000000003601324654574500246530ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/array_non_strict.test000066400000000000000000000022301324654574500261200ustar00rootroot00000000000000--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(',') }} {# ArrayAccess #} {{ array_access['a'] }} --DATA-- return array('bar' => 'bar', 'foo' => array('bar' => 'bar'), 'array_access' => new ArrayObject(array('a' => 'b'))) --CONFIG-- return array('strict_variables' => false) --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 b Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/binary.test000066400000000000000000000007561324654574500240370ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/bitwise.test000066400000000000000000000003241324654574500242100ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/comparison.test000066400000000000000000000004351324654574500247170ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/divisibleby.test000066400000000000000000000004211324654574500250450ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/dotdot.test000066400000000000000000000010401324654574500240330ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/ends_with.test000066400000000000000000000010371324654574500245300ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/grouping.test000066400000000000000000000001631324654574500243750ustar00rootroot00000000000000--TEST-- Twig supports grouping of expressions --TEMPLATE-- {{ (2 + 2) / 2 }} --DATA-- return array() --EXPECT-- 2 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/literals.test000066400000000000000000000003241324654574500243610ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/magic_call.test000066400000000000000000000007401324654574500246170ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/matches.test000066400000000000000000000003421324654574500241660ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/method_call.test000066400000000000000000000007441324654574500250230ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/negative_numbers.test000066400000000000000000000002631324654574500261010ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/operators_as_variables.test000066400000000000000000000003741324654574500273000ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/postfix.test000066400000000000000000000004201324654574500242330ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/power.test000066400000000000000000000003501324654574500236750ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/sameas.test000066400000000000000000000005101324654574500240100ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/starts_with.test000066400000000000000000000010761324654574500251220ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/strings.test000066400000000000000000000003171324654574500242350ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/ternary_operator.test000066400000000000000000000005331324654574500261430ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/ternary_operator_noelse.test000066400000000000000000000002011324654574500275000ustar00rootroot00000000000000--TEST-- Twig supports the ternary operator --TEMPLATE-- {{ 1 ? 'YES' }} {{ 0 ? 'YES' }} --DATA-- return array() --EXPECT-- YES Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/ternary_operator_nothen.test000066400000000000000000000002071324654574500275140ustar00rootroot00000000000000--TEST-- Twig supports the ternary operator --TEMPLATE-- {{ 'YES' ?: 'NO' }} {{ 0 ?: 'NO' }} --DATA-- return array() --EXPECT-- YES NO Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/two_word_operators_as_variables.test000066400000000000000000000003651324654574500312240ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/unary.test000066400000000000000000000002701324654574500237000ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/unary_macro_arguments.test000066400000000000000000000011431324654574500271460ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/expressions/unary_precedence.test000066400000000000000000000002361324654574500260570ustar00rootroot00000000000000--TEST-- Twig unary operators precedence --TEMPLATE-- {{ -1 - 1 }} {{ -1 - -1 }} {{ -1 * -1 }} {{ 4 / -1 * 5 }} --DATA-- return array() --EXPECT-- -2 0 1 -20 Twig-2.4.6/test/Twig/Tests/Fixtures/extensions/000077500000000000000000000000001324654574500214575ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/extensions/anonymous_functions.test000066400000000000000000000002301324654574500264730ustar00rootroot00000000000000--TEST-- use an anonymous function as a function --TEMPLATE-- {{ anon_foo('bar') }} {{ 'bar'|anon_foo }} --DATA-- return array() --EXPECT-- *bar* *bar* Twig-2.4.6/test/Twig/Tests/Fixtures/filters/000077500000000000000000000000001324654574500207305ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/filters/abs.test000066400000000000000000000006141324654574500223770ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/batch.test000066400000000000000000000013001324654574500227040ustar00rootroot00000000000000--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
    Twig-2.4.6/test/Twig/Tests/Fixtures/filters/batch_float.test000066400000000000000000000012451324654574500241010ustar00rootroot00000000000000--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
    Twig-2.4.6/test/Twig/Tests/Fixtures/filters/batch_with_empty_fill.test000066400000000000000000000010751324654574500261740ustar00rootroot00000000000000--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--
    a b c
    d e f
    g h i
    j
    Twig-2.4.6/test/Twig/Tests/Fixtures/filters/batch_with_exact_elements.test000066400000000000000000000014161324654574500270270ustar00rootroot00000000000000--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
    Twig-2.4.6/test/Twig/Tests/Fixtures/filters/batch_with_fill.test000066400000000000000000000011111324654574500247450ustar00rootroot00000000000000--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--
    a b c
    d e f
    g h i
    j fill fill
    Twig-2.4.6/test/Twig/Tests/Fixtures/filters/batch_with_keys.test000066400000000000000000000004011324654574500247730ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/batch_with_zero_elements.test000066400000000000000000000002311324654574500266740ustar00rootroot00000000000000--TEST-- "batch" filter with zero elements --TEMPLATE-- {{ []|batch(3)|length }} {{ []|batch(3, 'fill')|length }} --DATA-- return array() --EXPECT-- 0 0 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/convert_encoding.test000066400000000000000000000003371324654574500251620ustar00rootroot00000000000000--TEST-- "convert_encoding" filter --TEMPLATE-- {{ "愛していますか?"|convert_encoding('ISO-2022-JP', 'UTF-8')|convert_encoding('UTF-8', 'ISO-2022-JP') }} --DATA-- return array() --EXPECT-- 愛していますか? Twig-2.4.6/test/Twig/Tests/Fixtures/filters/date.test000066400000000000000000000045471324654574500225600ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/date_default_format.test000066400000000000000000000004621324654574500256240ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/date_default_format_interval.test000066400000000000000000000005001324654574500275210ustar00rootroot00000000000000--TEST-- "date" filter (interval support) --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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/date_immutable.test000066400000000000000000000017311324654574500246070ustar00rootroot00000000000000--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', 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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/date_interval.test000066400000000000000000000006461324654574500244600ustar00rootroot00000000000000--TEST-- "date" filter (interval support) --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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/date_modify.test000066400000000000000000000005271324654574500241210ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/date_namedargs.test000066400000000000000000000006471324654574500245760ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/default.test000066400000000000000000000076631324654574500232710ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/dynamic_filter.test000066400000000000000000000002051324654574500246170ustar00rootroot00000000000000--TEST-- dynamic filter --TEMPLATE-- {{ 'bar'|foo_path }} {{ 'bar'|a_foo_b_bar }} --DATA-- return array() --EXPECT-- foo/bar a/b/bar Twig-2.4.6/test/Twig/Tests/Fixtures/filters/escape.test000066400000000000000000000001571324654574500230740ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {{ "foo
    "|e }} --DATA-- return array() --EXPECT-- foo <br /> Twig-2.4.6/test/Twig/Tests/Fixtures/filters/escape_html_attr.test000066400000000000000000000003141324654574500251450ustar00rootroot00000000000000--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 /> Twig-2.4.6/test/Twig/Tests/Fixtures/filters/escape_javascript.test000066400000000000000000000002061324654574500253150ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {{ "é ♜ 𝌆"|e('js') }} --DATA-- return array() --EXPECT-- \u00E9\x20\u265C\x20\uD834\uDF06 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/escape_non_supported_charset.test000066400000000000000000000002311324654574500275550ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {{ "愛していますか?
    "|e }} --DATA-- return array() --EXPECT-- 愛していますか? <br /> Twig-2.4.6/test/Twig/Tests/Fixtures/filters/first.test000066400000000000000000000004041324654574500227560ustar00rootroot00000000000000--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 Ä Twig-2.4.6/test/Twig/Tests/Fixtures/filters/force_escape.test000066400000000000000000000004421324654574500242470ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {% set foo %} foo
    {% endset %} {{ foo|e('html') -}} {{ foo|e('js') }} {% autoescape true %} {{ foo }} {% endautoescape %} --DATA-- return array() --EXPECT-- foo<br /> \x20\x20\x20\x20foo\x3Cbr\x20\x2F\x3E\x0A foo
    Twig-2.4.6/test/Twig/Tests/Fixtures/filters/format.test000066400000000000000000000002161324654574500231200ustar00rootroot00000000000000--TEST-- "format" filter --TEMPLATE-- {{ string|format(foo, 3) }} --DATA-- return array('string' => '%s/%d', 'foo' => 'bar') --EXPECT-- bar/3 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/join.test000066400000000000000000000003451324654574500225720ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/json_encode.test000066400000000000000000000003511324654574500241160ustar00rootroot00000000000000--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"] Twig-2.4.6/test/Twig/Tests/Fixtures/filters/last.test000066400000000000000000000003751324654574500226010ustar00rootroot00000000000000--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 é Twig-2.4.6/test/Twig/Tests/Fixtures/filters/length.test000066400000000000000000000014541324654574500231160ustar00rootroot00000000000000--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 }} --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(), ); --EXPECT-- 2 3 4 6 42 3 0 1 1 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/length_utf8.test000066400000000000000000000002651324654574500240630ustar00rootroot00000000000000--TEST-- "length" filter --TEMPLATE-- {{ string|length }} {{ markup|length }} --DATA-- return array('string' => 'été', 'markup' => new Twig_Markup('foo', 'UTF-8')) --EXPECT-- 3 3 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/merge.test000066400000000000000000000010411324654574500227240ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/nl2br.test000066400000000000000000000005761324654574500226600ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/filters/number_format.test000066400000000000000000000004621324654574500244730ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/number_format_default.test000066400000000000000000000006651324654574500262040ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/replace.test000066400000000000000000000007071324654574500232500ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/filters/replace_invalid_arg.test000066400000000000000000000004711324654574500256050ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/filters/reverse.test000066400000000000000000000006641324654574500233120ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/round.test000066400000000000000000000004061324654574500227600ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/slice.test000066400000000000000000000017541324654574500227370ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/sort.test000066400000000000000000000004301324654574500226150ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/filters/special_chars.test000066400000000000000000000001431324654574500244270ustar00rootroot00000000000000--TEST-- "§" custom filter --TEMPLATE-- {{ 'foo'|§ }} --DATA-- return array() --EXPECT-- §foo§ Twig-2.4.6/test/Twig/Tests/Fixtures/filters/split.test000066400000000000000000000007471324654574500227740ustar00rootroot00000000000000--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-threeTwig-2.4.6/test/Twig/Tests/Fixtures/filters/split_utf8.test000066400000000000000000000007331324654574500237350ustar00rootroot00000000000000--TEST-- "split" filter --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 éÄ-ßご-aTwig-2.4.6/test/Twig/Tests/Fixtures/filters/static_calls.test000066400000000000000000000002571324654574500243020ustar00rootroot00000000000000--TEST-- Filters as static method calls --TEMPLATE-- {{ 'foo'|static_call_string }} {{ 'foo'|static_call_array }} --DATA-- return array('foo' => 'foo') --EXPECT-- *foo* *foo* Twig-2.4.6/test/Twig/Tests/Fixtures/filters/trim.test000066400000000000000000000012631324654574500226060ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/filters/urlencode.test000066400000000000000000000007611324654574500236150ustar00rootroot00000000000000--TEST-- "url_encode" filter --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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/000077500000000000000000000000001324654574500212705ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/functions/attribute.test000066400000000000000000000007721324654574500242020ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/block.test000066400000000000000000000003721324654574500232650ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/block_with_template.test000066400000000000000000000010201324654574500262020ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/block_without_name.test000066400000000000000000000005511324654574500260470ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/functions/block_without_parent.test000066400000000000000000000006331324654574500264210ustar00rootroot00000000000000--TEST-- "block" calling parent() with no definition in parent template --TEMPLATE-- {% extends "parent.twig" %} {% block label %}{{ parent() }}{% endblock %} --TEMPLATE(parent.twig)-- {{ block('label') }} --DATA-- return array() --EXCEPTION-- Twig_Error_Runtime: Block "label" should not call parent() in "index.twig" as the block does not exist in the parent template "parent.twig" in "index.twig" at line 3. Twig-2.4.6/test/Twig/Tests/Fixtures/functions/constant.test000066400000000000000000000003641324654574500240250ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/cycle.test000066400000000000000000000004661324654574500232760ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/date.test000066400000000000000000000017051324654574500231110ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/date_namedargs.test000066400000000000000000000005331324654574500251300ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/dump.test000066400000000000000000000004561324654574500231430ustar00rootroot00000000000000--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" Twig-2.4.6/test/Twig/Tests/Fixtures/functions/dump_array.test000066400000000000000000000007421324654574500243370ustar00rootroot00000000000000--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" } Twig-2.4.6/test/Twig/Tests/Fixtures/functions/dynamic_function.test000066400000000000000000000002111324654574500255140ustar00rootroot00000000000000--TEST-- dynamic function --TEMPLATE-- {{ foo_path('bar') }} {{ a_foo_b_bar('bar') }} --DATA-- return array() --EXPECT-- foo/bar a/b/bar Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/000077500000000000000000000000001324654574500227135ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/assignment.test000066400000000000000000000002551324654574500257660ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {% set tmp = include("foo.twig") %} FOO{{ tmp }}BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return array() --EXPECT-- FOO FOOBARBAR Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/autoescaping.test000066400000000000000000000002571324654574500263020ustar00rootroot00000000000000--TEST-- "include" function is safe for auto-escaping --TEMPLATE-- {{ include("foo.twig") }} --TEMPLATE(foo.twig)--

    Test

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

    Test

    Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/basic.test000066400000000000000000000002361324654574500246760ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- FOO {{ include("foo.twig") }} BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return array() --EXPECT-- FOO FOOBAR BAR Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/expression.test000066400000000000000000000003311324654574500260100ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/ignore_missing.test000066400000000000000000000005231324654574500266300ustar00rootroot00000000000000--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-- Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/missing.test000066400000000000000000000002731324654574500252670ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/missing_nested.test000066400000000000000000000005121324654574500266250ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/sandbox.test000066400000000000000000000004201324654574500252460ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling.test000066400000000000000000000003771324654574500272750ustar00rootroot00000000000000--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 /> Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/sandbox_disabling_ignore_missing.test000066400000000000000000000003731324654574500323650ustar00rootroot00000000000000--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 /> Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/template_instance.test000066400000000000000000000003151324654574500273120ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/templates_as_array.test000066400000000000000000000003001324654574500274640ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {{ include(["foo.twig", "bar.twig"]) }} {{- include(["bar.twig", "foo.twig"]) }} --TEMPLATE(foo.twig)-- foo --DATA-- return array() --EXPECT-- foo foo Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/with_context.test000066400000000000000000000007151324654574500263360ustar00rootroot00000000000000--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, Twig-2.4.6/test/Twig/Tests/Fixtures/functions/include/with_variables.test000066400000000000000000000003601324654574500266160ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/magic_call.test000066400000000000000000000001471324654574500242460ustar00rootroot00000000000000--TEST-- __call calls --TEMPLATE-- {{ 'foo'|magic_call }} --DATA-- return array() --EXPECT-- magic_foo Twig-2.4.6/test/Twig/Tests/Fixtures/functions/magic_static_call.test000066400000000000000000000002511324654574500256110ustar00rootroot00000000000000--TEST-- __staticCall calls --TEMPLATE-- {{ 'foo'|magic_call_string }} {{ 'foo'|magic_call_array }} --DATA-- return array() --EXPECT-- static_magic_foo static_magic_foo Twig-2.4.6/test/Twig/Tests/Fixtures/functions/max.test000066400000000000000000000003001324654574500227470ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/min.test000066400000000000000000000003011324654574500227460ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/range.test000066400000000000000000000002061324654574500232630ustar00rootroot00000000000000--TEST-- "range" function --TEMPLATE-- {{ range(low=0+1, high=10+0, step=2)|join(',') }} --DATA-- return array() --EXPECT-- 1,3,5,7,9 Twig-2.4.6/test/Twig/Tests/Fixtures/functions/recursive_block_with_inheritance.test000066400000000000000000000021751324654574500307630ustar00rootroot00000000000000--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"
    Twig-2.4.6/test/Twig/Tests/Fixtures/functions/source.test000066400000000000000000000002561324654574500234740ustar00rootroot00000000000000--TEST-- "source" function --TEMPLATE-- FOO {{ source("foo.twig") }} BAR --TEMPLATE(foo.twig)-- {{ foo }}
    --DATA-- return array() --EXPECT-- FOO {{ foo }}
    BAR Twig-2.4.6/test/Twig/Tests/Fixtures/functions/special_chars.test000066400000000000000000000001461324654574500247720ustar00rootroot00000000000000--TEST-- "§" custom function --TEMPLATE-- {{ §('foo') }} --DATA-- return array() --EXPECT-- §foo§ Twig-2.4.6/test/Twig/Tests/Fixtures/functions/static_calls.test000066400000000000000000000002631324654574500246370ustar00rootroot00000000000000--TEST-- Functions as static method calls --TEMPLATE-- {{ static_call_string('foo') }} {{ static_call_array('foo') }} --DATA-- return array('foo' => 'foo') --EXPECT-- *foo* *foo* Twig-2.4.6/test/Twig/Tests/Fixtures/functions/template_from_string.test000066400000000000000000000007101324654574500264130ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/macros/000077500000000000000000000000001324654574500205445ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/macros/default_values.test000066400000000000000000000003271324654574500244520ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/macros/nested_calls.test000066400000000000000000000003461324654574500241100ustar00rootroot00000000000000--TEST-- macro --TEMPLATE-- {% import _self as macros %} {% macro foo(data) %} {{ data }} {% endmacro %} {% macro bar() %}
    {% endmacro %} {{ macros.foo(macros.bar()) }} --DATA-- return array(); --EXPECT--
    Twig-2.4.6/test/Twig/Tests/Fixtures/macros/reserved_variables.test000066400000000000000000000002721324654574500253150ustar00rootroot00000000000000--TEST-- macro --TEMPLATE-- {% from _self import test %} {% macro test(this) -%} {{ this }} {%- endmacro %} {{ test(this) }} --DATA-- return array('this' => 'foo'); --EXPECT-- foo Twig-2.4.6/test/Twig/Tests/Fixtures/macros/simple.test000066400000000000000000000005471324654574500227440ustar00rootroot00000000000000--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
    Twig-2.4.6/test/Twig/Tests/Fixtures/macros/varargs.test000066400000000000000000000005741324654574500231200ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/macros/varargs_argument.test000066400000000000000000000004231324654574500250130ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/macros/with_filters.test000066400000000000000000000003371324654574500241530ustar00rootroot00000000000000--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 /> Twig-2.4.6/test/Twig/Tests/Fixtures/regression/000077500000000000000000000000001324654574500214405ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/regression/combined_debug_info.test000066400000000000000000000005151324654574500263030ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/regression/empty_token.test000066400000000000000000000002021324654574500246710ustar00rootroot00000000000000--TEST-- Twig outputs 0 nodes correctly --TEMPLATE-- {{ foo }}0{{ foo }} --DATA-- return array('foo' => 'foo') --EXPECT-- foo0foo Twig-2.4.6/test/Twig/Tests/Fixtures/regression/issue_1143.test000066400000000000000000000007621324654574500241460ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/regression/multi_word_tests.test000066400000000000000000000003171324654574500257510ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/regression/simple_xml_element.test000066400000000000000000000007441324654574500262300ustar00rootroot00000000000000--TEST-- Twig is able to deal with SimpleXMLElement instances as variables --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 Twig-2.4.6/test/Twig/Tests/Fixtures/regression/strings_like_numbers.test000066400000000000000000000002601324654574500265670ustar00rootroot00000000000000--TEST-- Twig does not confuse strings with integers in getAttribute() --TEMPLATE-- {{ hash['2e2'] }} --DATA-- return array('hash' => array('2e2' => 'works')) --EXPECT-- works Twig-2.4.6/test/Twig/Tests/Fixtures/tags/000077500000000000000000000000001324654574500202165ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/000077500000000000000000000000001324654574500223475ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/basic.test000066400000000000000000000006431324654574500243340ustar00rootroot00000000000000--TEST-- "autoescape" tag applies escaping on its children --TEMPLATE-- {% autoescape %} {{ var }}
    {% endautoescape %} {% autoescape 'html' %} {{ var }}
    {% endautoescape %} {% autoescape false %} {{ var }}
    {% endautoescape %} {% autoescape false %} {{ var }}
    {% endautoescape %} --DATA-- return array('var' => '
    ') --EXPECT-- <br />
    <br />




    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/blocks.test000066400000000000000000000003511324654574500245240ustar00rootroot00000000000000--TEST-- "autoescape" tag applies escaping on embedded blocks --TEMPLATE-- {% autoescape 'html' %} {% block foo %} {{ var }} {% endblock %} {% endautoescape %} --DATA-- return array('var' => '
    ') --EXPECT-- <br /> Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/double_escaping.test000066400000000000000000000002741324654574500263760ustar00rootroot00000000000000--TEST-- "autoescape" tag does not double-escape --TEMPLATE-- {% autoescape 'html' %} {{ var|escape }} {% endautoescape %} --DATA-- return array('var' => '
    ') --EXPECT-- <br /> Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/functions.test000066400000000000000000000015421324654574500252620ustar00rootroot00000000000000--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 \x3Cbr\x20\x2F\x3E Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/literal.test000066400000000000000000000016301324654574500247040ustar00rootroot00000000000000--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
    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/nested.test000066400000000000000000000007061324654574500245350ustar00rootroot00000000000000--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 /> Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/objects.test000066400000000000000000000007201324654574500247000ustar00rootroot00000000000000--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 /> Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/raw.test000066400000000000000000000003111324654574500240340ustar00rootroot00000000000000--TEST-- "autoescape" tag does not escape when raw is used as a filter --TEMPLATE-- {% autoescape 'html' %} {{ var|raw }} {% endautoescape %} --DATA-- return array('var' => '
    ') --EXPECT--
    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/strategy.test000066400000000000000000000004121324654574500251070ustar00rootroot00000000000000--TEST-- "autoescape" tag accepts an escaping strategy --TEMPLATE-- {% autoescape 'js' %}{{ var }}{% endautoescape %} {% autoescape 'html' %}{{ var }}{% endautoescape %} --DATA-- return array('var' => '
    "') --EXPECT-- \x3Cbr\x20\x2F\x3E\x22 <br />" Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/type.test000066400000000000000000000027101324654574500242310ustar00rootroot00000000000000--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') Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/with_filters.test000066400000000000000000000075251324654574500257640ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/with_filters_arguments.test000066400000000000000000000007411324654574500300420ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/with_pre_escape_filters.test000066400000000000000000000026511324654574500301450ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/autoescape/with_preserves_safety_filters.test000066400000000000000000000023641324654574500314310ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/block/000077500000000000000000000000001324654574500213105ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/block/basic.test000066400000000000000000000003241324654574500232710ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/block/block_unique_name.test000066400000000000000000000003701324654574500256710ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/block/special_chars.test000066400000000000000000000002031324654574500250040ustar00rootroot00000000000000--TEST-- "§" special chars in a block name --TEMPLATE-- {% block § %} § {% endblock § %} --DATA-- return array() --EXPECT-- § Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/000077500000000000000000000000001324654574500212725ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/basic.test000066400000000000000000000006001324654574500232500ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/complex_dynamic_parent.test000066400000000000000000000006211324654574500267160ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/dynamic_parent.test000066400000000000000000000006141324654574500251710ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/error_line.test000066400000000000000000000005031324654574500243310ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/multiple.test000066400000000000000000000010741324654574500240300ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/nested.test000066400000000000000000000011141324654574500234520ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/embed/with_extends.test000066400000000000000000000014231324654574500247000ustar00rootroot00000000000000--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 BTwig-2.4.6/test/Twig/Tests/Fixtures/tags/filter/000077500000000000000000000000001324654574500215035ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/filter/basic.test000066400000000000000000000003101324654574500234570ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/filter/json_encode.test000066400000000000000000000002361324654574500246730ustar00rootroot00000000000000--TEST-- "filter" tag applies a filter on its children --TEMPLATE-- {% filter json_encode|raw %}test{% endfilter %} --DATA-- return array() --EXPECT-- "test" Twig-2.4.6/test/Twig/Tests/Fixtures/tags/filter/multiple.test000066400000000000000000000002621324654574500242370ustar00rootroot00000000000000--TEST-- "filter" tags accept multiple chained filters --TEMPLATE-- {% filter lower|title %} {{ var }} {% endfilter %} --DATA-- return array('var' => 'VAR') --EXPECT-- Var Twig-2.4.6/test/Twig/Tests/Fixtures/tags/filter/nested.test000066400000000000000000000003711324654574500236670ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/filter/with_for_tag.test000066400000000000000000000003301324654574500250540ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/filter/with_if_tag.test000066400000000000000000000005671324654574500247000ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/000077500000000000000000000000001324654574500210045ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/condition.test000066400000000000000000000004151324654574500236730ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/context.test000066400000000000000000000004321324654574500233700ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/else.test000066400000000000000000000005541324654574500226410ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/inner_variables.test000066400000000000000000000004461324654574500250540ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/keys.test000066400000000000000000000002661324654574500226640ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/keys_and_values.test000066400000000000000000000003211324654574500250550ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/loop_context.test000066400000000000000000000005451324654574500244260ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/loop_context_local.test000066400000000000000000000003311324654574500255710ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/loop_not_defined.test000066400000000000000000000004311324654574500252120ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/loop_not_defined_cond.test000066400000000000000000000004011324654574500262120ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/nested_else.test000066400000000000000000000004621324654574500242010ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/objects.test000066400000000000000000000015411324654574500233370ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/objects_countable.test000066400000000000000000000020551324654574500253740ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/recursive.test000066400000000000000000000005501324654574500237140ustar00rootroot00000000000000--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) Twig-2.4.6/test/Twig/Tests/Fixtures/tags/for/values.test000066400000000000000000000002671324654574500232110ustar00rootroot00000000000000--TEST-- "for" tag iterates over item values --TEMPLATE-- {% for item in items %} * {{ item }} {% endfor %} --DATA-- return array('items' => array('a', 'b')) --EXPECT-- * a * b Twig-2.4.6/test/Twig/Tests/Fixtures/tags/from.test000066400000000000000000000003751324654574500220670ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/if/000077500000000000000000000000001324654574500206145ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/if/basic.test000066400000000000000000000004431324654574500225770ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/if/expression.test000066400000000000000000000004231324654574500237130ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/000077500000000000000000000000001324654574500216415ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/basic.test000066400000000000000000000002271324654574500236240ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- FOO {% include "foo.twig" %} BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return array() --EXPECT-- FOO FOOBAR BAR Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/expression.test000066400000000000000000000003221324654574500247360ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/ignore_missing.test000066400000000000000000000004121324654574500255530ustar00rootroot00000000000000--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-- Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/missing.test000066400000000000000000000002651324654574500242160ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/missing_nested.test000066400000000000000000000005041324654574500255540ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/only.test000066400000000000000000000006371324654574500235310ustar00rootroot00000000000000--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, Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/template_instance.test000066400000000000000000000003071324654574500262410ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/templates_as_array.test000066400000000000000000000002701324654574500264200ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- {% include ["foo.twig", "bar.twig"] %} {% include ["bar.twig", "foo.twig"] %} --TEMPLATE(foo.twig)-- foo --DATA-- return array() --EXPECT-- foo foo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/include/with_variables.test000066400000000000000000000003601324654574500255440ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/000077500000000000000000000000001324654574500225075ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/basic.test000066400000000000000000000003051324654574500244670ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends "foo.twig" %} {% block content %} FOO {% endblock %} --TEMPLATE(foo.twig)-- {% block content %}{% endblock %} --DATA-- return array() --EXPECT-- FOO Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/block_expr.test000066400000000000000000000011531324654574500255400ustar00rootroot00000000000000--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:
    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/block_expr2.test000066400000000000000000000012401324654574500256170ustar00rootroot00000000000000--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:
    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/conditional.test000066400000000000000000000005171324654574500257160ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/dynamic.test000066400000000000000000000003211324654574500250300ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends foo %} {% block content %} FOO {% endblock %} --TEMPLATE(foo.twig)-- {% block content %}{% endblock %} --DATA-- return array('foo' => 'foo.twig') --EXPECT-- FOO Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/empty.test000066400000000000000000000002401324654574500245420ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends "foo.twig" %} --TEMPLATE(foo.twig)-- {% block content %}FOO{% endblock %} --DATA-- return array() --EXPECT-- FOO Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array.test000066400000000000000000000002601324654574500267410ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends ["foo.twig", "bar.twig"] %} --TEMPLATE(bar.twig)-- {% block content %} foo {% endblock %} --DATA-- return array() --EXPECT-- foo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_empty_name.test000066400000000000000000000002501324654574500322110ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends ["", "bar.twig"] %} --TEMPLATE(bar.twig)-- {% block content %} foo {% endblock %} --DATA-- return array() --EXPECT-- foo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/extends_as_array_with_null_name.test000066400000000000000000000002521324654574500320270ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends [null, "bar.twig"] %} --TEMPLATE(bar.twig)-- {% block content %} foo {% endblock %} --DATA-- return array() --EXPECT-- foo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/multiple.test000066400000000000000000000005231324654574500252430ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/multiple_dynamic.test000066400000000000000000000007161324654574500267530ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks.test000066400000000000000000000006141324654574500262300ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/nested_blocks_parent_only.test000066400000000000000000000003731324654574500306440ustar00rootroot00000000000000--TEST-- "block" tag --TEMPLATE-- {% block content %} CONTENT {%- block subcontent -%} SUBCONTENT {%- endblock -%} ENDCONTENT {% endblock %} --TEMPLATE(foo.twig)-- --DATA-- return array() --EXPECT-- CONTENTSUBCONTENTENDCONTENT Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/nested_inheritance.test000066400000000000000000000004671324654574500272520ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/parent.test000066400000000000000000000003501324654574500246770ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/parent_change.test000066400000000000000000000003571324654574500262130ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/parent_in_a_block.test000066400000000000000000000002731324654574500270430ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/parent_isolation.test000066400000000000000000000007201324654574500267610ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/parent_nested.test000066400000000000000000000005231324654574500262430ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends.test000066400000000000000000000003611324654574500302160ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/parent_without_extends_but_traits.test000066400000000000000000000003221324654574500324530ustar00rootroot00000000000000--TEST-- "parent" tag --TEMPLATE-- {% use 'foo.twig' %} {% block content %} {{ parent() }} {% endblock %} --TEMPLATE(foo.twig)-- {% block content %}BAR{% endblock %} --DATA-- return array() --EXPECT-- BAR Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/template_instance.test000066400000000000000000000004311324654574500271050ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/inheritance/use.test000066400000000000000000000017261324654574500242120ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/000077500000000000000000000000001324654574500213175ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/basic.test000066400000000000000000000007451324654574500233070ustar00rootroot00000000000000--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-- Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/endmacro_name.test000066400000000000000000000003701324654574500250100ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/external.test000066400000000000000000000010011324654574500240320ustar00rootroot00000000000000--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-- Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/from.test000066400000000000000000000005411324654574500231630ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/global.test000066400000000000000000000003741324654574500234640ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/self_import.test000066400000000000000000000007421324654574500245460ustar00rootroot00000000000000--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-- Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/special_chars.test000066400000000000000000000002771324654574500250260ustar00rootroot00000000000000--TEST-- "§" as a macro name --TEMPLATE-- {% import _self as macros %} {{ macros.§('foo') }} {% macro §(foo) %} §{{ foo }}§ {% endmacro %} --DATA-- return array() --EXPECT-- §foo§ Twig-2.4.6/test/Twig/Tests/Fixtures/tags/macro/super_globals.test000066400000000000000000000003071324654574500250610ustar00rootroot00000000000000--TEST-- Super globals as macro arguments --TEMPLATE-- {% import _self as macros %} {{ macros.foo('foo') }} {% macro foo(GET) %} {{ GET }} {% endmacro %} --DATA-- return array() --EXPECT-- foo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/sandbox/000077500000000000000000000000001324654574500216545ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/sandbox/not_valid1.test000066400000000000000000000003711324654574500246160ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/sandbox/not_valid2.test000066400000000000000000000004651324654574500246230ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/sandbox/simple.test000066400000000000000000000005051324654574500240460ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/set/000077500000000000000000000000001324654574500210115ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/set/basic.test000066400000000000000000000003361324654574500227750ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/set/capture-empty.test000066400000000000000000000002161324654574500245100ustar00rootroot00000000000000--TEST-- "set" tag block empty capture --TEMPLATE-- {% set foo %}{% endset %} {% if foo %}FAIL{% endif %} --DATA-- return array() --EXPECT-- Twig-2.4.6/test/Twig/Tests/Fixtures/tags/set/capture.test000066400000000000000000000002251324654574500233540ustar00rootroot00000000000000--TEST-- "set" tag block capture --TEMPLATE-- {% set foo %}f
    o
    o{% endset %} {{ foo }} --DATA-- return array() --EXPECT-- f
    o
    o Twig-2.4.6/test/Twig/Tests/Fixtures/tags/set/expression.test000066400000000000000000000002301324654574500241040ustar00rootroot00000000000000--TEST-- "set" tag --TEMPLATE-- {% set foo, bar = 'foo' ~ 'bar', 'bar' ~ 'foo' %} {{ foo }} {{ bar }} --DATA-- return array() --EXPECT-- foobar barfoo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/spaceless/000077500000000000000000000000001324654574500222005ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/spaceless/simple.test000066400000000000000000000003311324654574500243670ustar00rootroot00000000000000--TEST-- "spaceless" tag removes whites between HTML tags --TEMPLATE-- {% spaceless %}
    foo
    {% endspaceless %} --DATA-- return array() --EXPECT--
    foo
    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/special_chars.test000066400000000000000000000001251324654574500237150ustar00rootroot00000000000000--TEST-- "§" custom tag --TEMPLATE-- {% § %} --DATA-- return array() --EXPECT-- § Twig-2.4.6/test/Twig/Tests/Fixtures/tags/trim_block.test000066400000000000000000000016731324654574500232530ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/000077500000000000000000000000001324654574500210125ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/aliases.test000066400000000000000000000002731324654574500233360ustar00rootroot00000000000000--TEST-- "use" tag --TEMPLATE-- {% use "blocks.twig" with content as foo %} {{ block('foo') }} --TEMPLATE(blocks.twig)-- {% block content 'foo' %} --DATA-- return array() --EXPECT-- foo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/basic.test000066400000000000000000000002531324654574500227740ustar00rootroot00000000000000--TEST-- "use" tag --TEMPLATE-- {% use "blocks.twig" %} {{ block('content') }} --TEMPLATE(blocks.twig)-- {% block content 'foo' %} --DATA-- return array() --EXPECT-- foo Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/deep.test000066400000000000000000000005061324654574500226310ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/deep_empty.test000066400000000000000000000002331324654574500240440ustar00rootroot00000000000000--TEST-- "use" tag --TEMPLATE-- {% use "foo.twig" %} --TEMPLATE(foo.twig)-- {% use "bar.twig" %} --TEMPLATE(bar.twig)-- --DATA-- return array() --EXPECT-- Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/inheritance.test000066400000000000000000000011371324654574500242060ustar00rootroot00000000000000--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
    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/inheritance2.test000066400000000000000000000011361324654574500242670ustar00rootroot00000000000000--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
    Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/multiple.test000066400000000000000000000005051324654574500235460ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/multiple_aliases.test000066400000000000000000000006001324654574500252430ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/parent_block.test000066400000000000000000000011551324654574500243600ustar00rootroot00000000000000--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) Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/parent_block2.test000066400000000000000000000010241324654574500244350ustar00rootroot00000000000000--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) Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/parent_block3.test000066400000000000000000000014741324654574500244470ustar00rootroot00000000000000--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) Twig-2.4.6/test/Twig/Tests/Fixtures/tags/use/use_with_parent.test000066400000000000000000000005701324654574500251150ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/verbatim/000077500000000000000000000000001324654574500220275ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/verbatim/basic.test000066400000000000000000000001751324654574500240140ustar00rootroot00000000000000--TEST-- "verbatim" tag --TEMPLATE-- {% verbatim %} {{ foo }} {% endverbatim %} --DATA-- return array() --EXPECT-- {{ foo }} Twig-2.4.6/test/Twig/Tests/Fixtures/tags/verbatim/whitespace_control.test000066400000000000000000000007701324654574500266300ustar00rootroot00000000000000--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*** Twig-2.4.6/test/Twig/Tests/Fixtures/tags/with/000077500000000000000000000000001324654574500211715ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tags/with/basic.test000066400000000000000000000003151324654574500231520ustar00rootroot00000000000000--TEST-- "with" tag --TEMPLATE-- {% with %} {% set bar = 'BAZ' %} {{ foo }}{{ bar }} {% endwith %} {{ foo }}{{ bar }} --DATA-- return array('foo' => 'foo', 'bar' => 'bar') --EXPECT-- fooBAZ foobar Twig-2.4.6/test/Twig/Tests/Fixtures/tags/with/expression.test000066400000000000000000000002621324654574500242710ustar00rootroot00000000000000--TEST-- "with" tag with expression --TEMPLATE-- {% with {foo: 'foo', bar: 'BAZ'} %} {{ foo }}{{ bar }} {% endwith %} --DATA-- return array('foo' => 'baz') --EXPECT-- fooBAZ Twig-2.4.6/test/Twig/Tests/Fixtures/tags/with/nested.test000066400000000000000000000004021324654574500233500ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tags/with/with_no_hash.test000066400000000000000000000004261324654574500245460ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tags/with/with_only.test000066400000000000000000000004421324654574500241060ustar00rootroot00000000000000--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. Twig-2.4.6/test/Twig/Tests/Fixtures/tests/000077500000000000000000000000001324654574500204225ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Fixtures/tests/array.test000066400000000000000000000005761324654574500224510ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/constant.test000066400000000000000000000005641324654574500231610ustar00rootroot00000000000000--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 okTwig-2.4.6/test/Twig/Tests/Fixtures/tests/defined.test000066400000000000000000000057341324654574500227320ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/defined_for_attribute.test000066400000000000000000000014131324654574500256510ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/defined_for_blocks.test000066400000000000000000000015751324654574500251340ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/defined_for_blocks_with_template.test000066400000000000000000000007651324654574500300620ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/defined_for_constants.test000066400000000000000000000006161324654574500256660ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/empty.test000066400000000000000000000024461324654574500224670ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/even.test000066400000000000000000000003211324654574500222540ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/in.test000066400000000000000000000043061324654574500217340ustar00rootroot00000000000000--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(__DIR__), 'object' => new stdClass(), 'resource' => opendir(__DIR__)) --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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/in_with_objects.test000066400000000000000000000005141324654574500244750ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/iterable.test000066400000000000000000000005471324654574500231200ustar00rootroot00000000000000--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 koTwig-2.4.6/test/Twig/Tests/Fixtures/tests/null_coalesce.test000066400000000000000000000007161324654574500241370ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/Fixtures/tests/odd.test000066400000000000000000000002031324654574500220640ustar00rootroot00000000000000--TEST-- "odd" test --TEMPLATE-- {{ 1 is odd ? 'ok' : 'ko' }} {{ 2 is odd ? 'ko' : 'ok' }} --DATA-- return array() --EXPECT-- ok okTwig-2.4.6/test/Twig/Tests/IntegrationTest.php000066400000000000000000000173101324654574500213050ustar00rootroot00000000000000position = 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_Filter('§', array($this, '§Filter')), new Twig_Filter('escape_and_nl2br', array($this, 'escape_and_nl2br'), array('needs_environment' => true, 'is_safe' => array('html'))), new Twig_Filter('nl2br', array($this, 'nl2br'), array('pre_escape' => 'html', 'is_safe' => array('html'))), new Twig_Filter('escape_something', array($this, 'escape_something'), array('is_safe' => array('something'))), new Twig_Filter('preserves_safety', array($this, 'preserves_safety'), array('preserves_safety' => array('html'))), new Twig_Filter('static_call_string', 'TwigTestExtension::staticCall'), new Twig_Filter('static_call_array', array('TwigTestExtension', 'staticCall')), new Twig_Filter('magic_call', array($this, 'magicCall')), new Twig_Filter('magic_call_string', 'TwigTestExtension::magicStaticCall'), new Twig_Filter('magic_call_array', array('TwigTestExtension', 'magicStaticCall')), new Twig_Filter('*_path', array($this, 'dynamic_path')), new Twig_Filter('*_foo_*_bar', array($this, 'dynamic_foo')), new Twig_Filter('anon_foo', function ($name) { return '*'.$name.'*'; }), ); } public function getFunctions() { return array( new Twig_Function('§', array($this, '§Function')), new Twig_Function('safe_br', array($this, 'br'), array('is_safe' => array('html'))), new Twig_Function('unsafe_br', array($this, 'br')), new Twig_Function('static_call_string', 'TwigTestExtension::staticCall'), new Twig_Function('static_call_array', array('TwigTestExtension', 'staticCall')), new Twig_Function('*_path', array($this, 'dynamic_path')), new Twig_Function('*_foo_*_bar', array($this, 'dynamic_foo')), new Twig_Function('anon_foo', function ($name) { return '*'.$name.'*'; }), ); } public function getTests() { return array( new Twig_Test('multi word', array($this, 'is_multi_word')), ); } 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 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); } } Twig-2.4.6/test/Twig/Tests/LegacyFixtures/000077500000000000000000000000001324654574500204055ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/LegacyFixtures/autoescape/000077500000000000000000000000001324654574500225365ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/LegacyFixtures/autoescape/filename.legacy.test000066400000000000000000000005311324654574500264610ustar00rootroot00000000000000--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 />
    Twig-2.4.6/test/Twig/Tests/LegacyFixtures/functions/000077500000000000000000000000001324654574500224155ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/LegacyFixtures/functions/undefined_block.legacy.test000066400000000000000000000004611324654574500276750ustar00rootroot00000000000000--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 Twig-2.4.6/test/Twig/Tests/LexerTest.php000066400000000000000000000313731324654574500201060ustar00rootroot00000000000000getMockBuilder('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')); } } Twig-2.4.6/test/Twig/Tests/Loader/000077500000000000000000000000001324654574500166555ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/ArrayTest.php000066400000000000000000000042511324654574500213060ustar00rootroot00000000000000getSourceContext('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()); } } Twig-2.4.6/test/Twig/Tests/Loader/ChainTest.php000066400000000000000000000061721324654574500212560ustar00rootroot00000000000000 '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'); } 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_LoaderInterface')->getMock(); $loader1->expects($this->once())->method('exists')->will($this->returnValue(false)); $loader1->expects($this->never())->method('getSourceContext'); $loader2 = $this->getMockBuilder('Twig_LoaderInterface')->getMock(); $loader2->expects($this->once())->method('exists')->will($this->returnValue(true)); $loader2->expects($this->never())->method('getSourceContext'); $loader = new Twig_Loader_Chain(); $loader->addLoader($loader1); $loader->addLoader($loader2); $this->assertTrue($loader->exists('foo')); } } Twig-2.4.6/test/Twig/Tests/Loader/FilesystemTest.php000066400000000000000000000207001324654574500223510ustar00rootroot00000000000000assertEquals('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(__DIR__.'/../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( __DIR__.'/Fixtures', 'test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html', null, ), array( __DIR__.'/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 = __DIR__.'/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 = __DIR__.'/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(__DIR__.'/Fixtures/themes/theme2'); $loader->addPath(__DIR__.'/Fixtures/themes/theme1'); $loader->addPath(__DIR__.'/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(__DIR__.'/Fixtures/inheritance'); $twig = new Twig_Environment($loader); $template = $twig->loadTemplate($templateName); $this->assertSame('VALID Child', $template->renderBlock('body', array())); } 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://'.__DIR__.'/Fixtures/phar/phar-sample.phar'); $this->assertSame('hello from phar', $loader->getSourceContext('hello.twig')->getCode()); } } Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/000077500000000000000000000000001324654574500204665ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/inheritance/000077500000000000000000000000001324654574500227575ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_empty_parent.html.twig000066400000000000000000000001321324654574500330700ustar00rootroot00000000000000{% extends ['','parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} array_inheritance_nonexistent_parent.html.twig000066400000000000000000000001571324654574500342400ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/inheritance{% extends ['nonexistent.html.twig','parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_null_parent.html.twig000066400000000000000000000001341324654574500327060ustar00rootroot00000000000000{% extends [null,'parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/inheritance/array_inheritance_valid_parent.html.twig000066400000000000000000000001601324654574500330320ustar00rootroot00000000000000{% extends ['parent.html.twig','spare_parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/inheritance/parent.html.twig000066400000000000000000000000441324654574500261050ustar00rootroot00000000000000{% block body %}VALID{% endblock %} Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/inheritance/spare_parent.html.twig000066400000000000000000000000531324654574500272770ustar00rootroot00000000000000{% block body %}SPARE PARENT{% endblock %} Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named/000077500000000000000000000000001324654574500215525ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named/index.html000066400000000000000000000000131324654574500235410ustar00rootroot00000000000000named path Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_bis/000077500000000000000000000000001324654574500224075ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_bis/index.html000066400000000000000000000000211324654574500243750ustar00rootroot00000000000000named path (bis) Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_final/000077500000000000000000000000001324654574500227235ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_final/index.html000066400000000000000000000000231324654574500247130ustar00rootroot00000000000000named path (final) Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_quater/000077500000000000000000000000001324654574500231335ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_quater/named_absolute.html000066400000000000000000000000241324654574500267770ustar00rootroot00000000000000named path (quater) Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_ter/000077500000000000000000000000001324654574500224245ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/named_ter/index.html000066400000000000000000000000211324654574500244120ustar00rootroot00000000000000named path (ter) Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal/000077500000000000000000000000001324654574500217565ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal/index.html000066400000000000000000000000051324654574500237460ustar00rootroot00000000000000path Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal_bis/000077500000000000000000000000001324654574500226135ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal_bis/index.html000066400000000000000000000000131324654574500246020ustar00rootroot00000000000000path (bis) Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal_final/000077500000000000000000000000001324654574500231275ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal_final/index.html000066400000000000000000000000151324654574500251200ustar00rootroot00000000000000path (final) Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal_ter/000077500000000000000000000000001324654574500226305ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/normal_ter/index.html000066400000000000000000000000131324654574500246170ustar00rootroot00000000000000path (ter) Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/phar/000077500000000000000000000000001324654574500214205ustar00rootroot00000000000000Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/phar/phar-sample.phar000066400000000000000000000152021324654574500245050ustar00rootroot00000000000000 2, 'c' => 'text/plain', 'cc' => 'text/plain', 'cpp' => 'text/plain', 'c++' => 'text/plain', 'dtd' => 'text/plain', 'h' => 'text/plain', 'log' => 'text/plain', 'rng' => 'text/plain', 'txt' => 'text/plain', 'xsd' => 'text/plain', 'php' => 1, 'inc' => 1, 'avi' => 'video/avi', 'bmp' => 'image/bmp', 'css' => 'text/css', 'gif' => 'image/gif', 'htm' => 'text/html', 'html' => 'text/html', 'htmls' => 'text/html', 'ico' => 'image/x-ico', 'jpe' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'js' => 'application/x-javascript', 'midi' => 'audio/midi', 'mid' => 'audio/midi', 'mod' => 'audio/mod', 'mov' => 'movie/quicktime', 'mp3' => 'audio/mp3', 'mpg' => 'video/mpeg', 'mpeg' => 'video/mpeg', 'pdf' => 'application/pdf', 'png' => 'image/png', 'swf' => 'application/shockwave-flash', 'tif' => 'image/tiff', 'tiff' => 'image/tiff', 'wav' => 'audio/wav', 'xbm' => 'image/xbm', 'xml' => 'text/xml', ); header("Cache-Control: no-cache, must-revalidate"); header("Pragma: no-cache"); $basename = basename(__FILE__); if (!strpos($_SERVER['REQUEST_URI'], $basename)) { chdir(Extract_Phar::$temp); include $web; return; } $pt = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], $basename) + strlen($basename)); if (!$pt || $pt == '/') { $pt = $web; header('HTTP/1.1 301 Moved Permanently'); header('Location: ' . $_SERVER['REQUEST_URI'] . '/' . $pt); exit; } $a = realpath(Extract_Phar::$temp . DIRECTORY_SEPARATOR . $pt); if (!$a || strlen(dirname($a)) < strlen(Extract_Phar::$temp)) { header('HTTP/1.0 404 Not Found'); echo "\n \n File Not Found<title>\n </head>\n <body>\n <h1>404 - File ", $pt, " Not Found</h1>\n </body>\n</html>"; exit; } $b = pathinfo($a); if (!isset($b['extension'])) { header('Content-Type: text/plain'); header('Content-Length: ' . filesize($a)); readfile($a); exit; } if (isset($mimes[$b['extension']])) { if ($mimes[$b['extension']] === 1) { include $a; exit; } if ($mimes[$b['extension']] === 2) { highlight_file($a); exit; } header('Content-Type: ' .$mimes[$b['extension']]); header('Content-Length: ' . filesize($a)); readfile($a); exit; } } class Extract_Phar { static $temp; static $origdir; const GZ = 0x1000; const BZ2 = 0x2000; const MASK = 0x3000; const START = 'index.php'; const LEN = 6685; static function go($return = false) { $fp = fopen(__FILE__, 'rb'); fseek($fp, self::LEN); $L = unpack('V', $a = (binary)fread($fp, 4)); $m = (binary)''; do { $read = 8192; if ($L[1] - strlen($m) < 8192) { $read = $L[1] - strlen($m); } $last = (binary)fread($fp, $read); $m .= $last; } while (strlen($last) && strlen($m) < $L[1]); if (strlen($m) < $L[1]) { die('ERROR: manifest length read was "' . strlen($m) .'" should be "' . $L[1] . '"'); } $info = self::_unpack($m); $f = $info['c']; if ($f & self::GZ) { if (!function_exists('gzinflate')) { die('Error: zlib extension is not enabled -' . ' gzinflate() function needed for zlib-compressed .phars'); } } if ($f & self::BZ2) { if (!function_exists('bzdecompress')) { die('Error: bzip2 extension is not enabled -' . ' bzdecompress() function needed for bz2-compressed .phars'); } } $temp = self::tmpdir(); if (!$temp || !is_writable($temp)) { $sessionpath = session_save_path(); if (strpos ($sessionpath, ";") !== false) $sessionpath = substr ($sessionpath, strpos ($sessionpath, ";")+1); if (!file_exists($sessionpath) || !is_dir($sessionpath)) { die('Could not locate temporary directory to extract phar'); } $temp = $sessionpath; } $temp .= '/pharextract/'.basename(__FILE__, '.phar'); self::$temp = $temp; self::$origdir = getcwd(); @mkdir($temp, 0777, true); $temp = realpath($temp); if (!file_exists($temp . DIRECTORY_SEPARATOR . md5_file(__FILE__))) { self::_removeTmpFiles($temp, getcwd()); @mkdir($temp, 0777, true); @file_put_contents($temp . '/' . md5_file(__FILE__), ''); foreach ($info['m'] as $path => $file) { $a = !file_exists(dirname($temp . '/' . $path)); @mkdir(dirname($temp . '/' . $path), 0777, true); clearstatcache(); if ($path[strlen($path) - 1] == '/') { @mkdir($temp . '/' . $path, 0777); } else { file_put_contents($temp . '/' . $path, self::extractFile($path, $file, $fp)); @chmod($temp . '/' . $path, 0666); } } } chdir($temp); if (!$return) { include self::START; } } static function tmpdir() { if (strpos(PHP_OS, 'WIN') !== false) { if ($var = getenv('TMP') ? getenv('TMP') : getenv('TEMP')) { return $var; } if (is_dir('/temp') || mkdir('/temp')) { return realpath('/temp'); } return false; } if ($var = getenv('TMPDIR')) { return $var; } return realpath('/tmp'); } static function _unpack($m) { $info = unpack('V', substr($m, 0, 4)); $l = unpack('V', substr($m, 10, 4)); $m = substr($m, 14 + $l[1]); $s = unpack('V', substr($m, 0, 4)); $o = 0; $start = 4 + $s[1]; $ret['c'] = 0; for ($i = 0; $i < $info[1]; $i++) { $len = unpack('V', substr($m, $start, 4)); $start += 4; $savepath = substr($m, $start, $len[1]); $start += $len[1]; $ret['m'][$savepath] = array_values(unpack('Va/Vb/Vc/Vd/Ve/Vf', substr($m, $start, 24))); $ret['m'][$savepath][3] = sprintf('%u', $ret['m'][$savepath][3] & 0xffffffff); $ret['m'][$savepath][7] = $o; $o += $ret['m'][$savepath][2]; $start += 24 + $ret['m'][$savepath][5]; $ret['c'] |= $ret['m'][$savepath][4] & self::MASK; } return $ret; } static function extractFile($path, $entry, $fp) { $data = ''; $c = $entry[2]; while ($c) { if ($c < 8192) { $data .= @fread($fp, $c); $c = 0; } else { $c -= 8192; $data .= @fread($fp, 8192); } } if ($entry[4] & self::GZ) { $data = gzinflate($data); } elseif ($entry[4] & self::BZ2) { $data = bzdecompress($data); } if (strlen($data) != $entry[0]) { die("Invalid internal .phar file (size error " . strlen($data) . " != " . $stat[7] . ")"); } if ($entry[3] != sprintf("%u", crc32((binary)$data) & 0xffffffff)) { die("Invalid internal .phar file (checksum error)"); } return $data; } static function _removeTmpFiles($temp, $origdir) { chdir($temp); foreach (glob('*') as $f) { if (file_exists($f)) { is_dir($f) ? @rmdir($f) : @unlink($f); if (file_exists($f) && is_dir($f)) { self::_removeTmpFiles($f, getcwd()); } } } @rmdir($temp); clearstatcache(); chdir($origdir); } } Extract_Phar::go(); __HALT_COMPILER(); ?>8������������������ ���hello.twig���W���xY5A������hello from phar`E85Ax���GBMB����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/themes/��������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0021753�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/themes/theme1/�������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0023136�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/themes/theme1/blocks.html.twig���������������������������0000664�0000000�0000000�00000000137�13246545745�0026253�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% block b1 %}block from theme 1{% endblock %} {% block b2 %}block from theme 1{% endblock %} ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/themes/theme2/�������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0023137�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Loader/Fixtures/themes/theme2/blocks.html.twig���������������������������0000664�0000000�0000000�00000000134�13246545745�0026251�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% use '@default_theme/blocks.html.twig' %} {% block b2 %}block from theme 2{% endblock %} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/NativeExtensionTest.php��������������������������������������������������0000664�0000000�0000000�00000001410�13246545745�0022137�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_NativeExtensionTest extends \PHPUnit\Framework\TestCase { public function testGetProperties() { $twig = new Twig_Environment(new Twig_Loader_Array(array('index' => '{{ 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); } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/��������������������������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0016334�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/AutoEscapeTest.php��������������������������������������������������0000664�0000000�0000000�00000001472�13246545745�0021742�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_AutoEscapeTest extends Twig_Test_NodeTestCase { public function testConstructor() { $body = new Twig_Node(array(new Twig_Node_Text('foo', 1))); $node = new Twig_Node_AutoEscape(true, $body, 1); $this->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\";"), ); } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/BlockReferenceTest.php����������������������������������������������0000664�0000000�0000000�00000001237�13246545745�0022561�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_BlockReferenceTest extends Twig_Test_NodeTestCase { public function testConstructor() { $node = new Twig_Node_BlockReference('foo', 1); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { return array( array(new Twig_Node_BlockReference('foo', 1), <<<EOF // line 1 \$this->displayBlock('foo', \$context, \$blocks); EOF ), ); } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/BlockTest.php�������������������������������������������������������0000664�0000000�0000000�00000001543�13246545745�0020742�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_BlockTest extends Twig_Test_NodeTestCase { public function testConstructor() { $body = new Twig_Node_Text('foo', 1); $node = new Twig_Node_Block('foo', $body, 1); $this->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, <<<EOF // line 1 public function block_foo(\$context, array \$blocks = array()) { echo "foo"; } EOF ), ); } } �������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/DoTest.php����������������������������������������������������������0000664�0000000�0000000�00000001342�13246545745�0020247�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_DoTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant('foo', 1); $node = new Twig_Node_Do($expr, 1); $this->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; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/���������������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0020473�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/ArrayTest.php��������������������������������������������0000664�0000000�0000000�00000002025�13246545745�0023121�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_ArrayTest extends Twig_Test_NodeTestCase { public function testConstructor() { $elements = array(new Twig_Node_Expression_Constant('foo', 1), $foo = new Twig_Node_Expression_Constant('bar', 1)); $node = new Twig_Node_Expression_Array($elements, 1); $this->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")'), ); } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/AssignNameTest.php���������������������������������������0000664�0000000�0000000�00000001212�13246545745�0024065�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_AssignNameTest extends Twig_Test_NodeTestCase { public function testConstructor() { $node = new Twig_Node_Expression_AssignName('foo', 1); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { $node = new Twig_Node_Expression_AssignName('foo', 1); return array( array($node, '$context["foo"]'), ); } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/��������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0021717�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/AddTest.php���������������������������������������0000664�0000000�0000000�00000001661�13246545745�0023764�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_AddTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } �������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/AndTest.php���������������������������������������0000664�0000000�0000000�00000001662�13246545745�0023777�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_AndTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } ������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/ConcatTest.php������������������������������������0000664�0000000�0000000�00000001672�13246545745�0024505�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_ConcatTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } ����������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/DivTest.php���������������������������������������0000664�0000000�0000000�00000001661�13246545745�0024016�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_DivTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } �������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/FloorDivTest.php����������������������������������0000664�0000000�0000000�00000001715�13246545745�0025020�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_FloorDivTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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))'), ); } } ���������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/ModTest.php���������������������������������������0000664�0000000�0000000�00000001661�13246545745�0024013�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_ModTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } �������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/MulTest.php���������������������������������������0000664�0000000�0000000�00000001661�13246545745�0024031�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_MulTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } �������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/OrTest.php����������������������������������������0000664�0000000�0000000�00000001657�13246545745�0023661�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_OrTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } ���������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Binary/SubTest.php���������������������������������������0000664�0000000�0000000�00000001661�13246545745�0024025�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Binary_SubTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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)'), ); } } �������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/CallTest.php���������������������������������������������0000664�0000000�0000000�00000014414�13246545745�0022723�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_CallTest extends \PHPUnit\Framework\TestCase { public function testGetArguments() { $node = new Twig_Tests_Node_Expression_Call(array(), array('type' => 'function', 'name' => 'date')); $this->assertEquals(array('U', null), $this->getArguments($node, array('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')); $this->getArguments($node, array('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')); $this->getArguments($node, array('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')); $this->getArguments($node, array('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')); $this->getArguments($node, array('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')); $this->getArguments($node, array('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'), $this->getArguments($node, array(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'), $this->getArguments($node, array(__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)); $this->getArguments($node, array(array($this, 'customFunctionWithArbitraryArguments'), array())); } public static function customStaticFunction($arg1, $arg2 = 'default', $arg3 = array()) { } public function customFunction($arg1, $arg2 = 'default', $arg3 = array()) { } private function getArguments($call, $args) { $m = new ReflectionMethod($call, 'getArguments'); $m->setAccessible(true); return $m->invokeArgs($call, $args); } 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 = null, $arguments) { return parent::getArguments($callable, $arguments); } } class CallableTestClass { public function __invoke($required) { } } function custom_Twig_Tests_Node_Expression_CallTest_function($required) { } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/ConditionalTest.php��������������������������������������0000664�0000000�0000000�00000002236�13246545745�0024312�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_ConditionalTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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; } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/ConstantTest.php�����������������������������������������0000664�0000000�0000000�00000001223�13246545745�0023633�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_ConstantTest extends Twig_Test_NodeTestCase { public function testConstructor() { $node = new Twig_Node_Expression_Constant('foo', 1); $this->assertEquals('foo', $node->getAttribute('value')); } public function getTests() { $tests = array(); $node = new Twig_Node_Expression_Constant('foo', 1); $tests[] = array($node, '"foo"'); return $tests; } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/FilterTest.php�������������������������������������������0000664�0000000�0000000�00000014430�13246545745�0023273�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_FilterTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant('foo', 1); $name = new Twig_Node_Expression_Constant('upper', 1); $args = new Twig_Node(); $node = new Twig_Node_Expression_Filter($expr, $name, $args, 1); $this->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_Filter('bar', 'twig_tests_filter_dummy', array('needs_environment' => true))); $environment->addFilter(new Twig_Filter('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))); $tests[] = array($node, 'twig_number_format_filter($this->env, twig_upper_filter($this->env, "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 $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, 'twig_tests_filter_dummy($this->env, "abc")', $environment); $node = $this->createFilter($string, 'bar', array(new Twig_Node_Expression_Constant('bar', 1))); $tests[] = array($node, 'twig_tests_filter_dummy($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". */ 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() { $env = new Twig_Environment(new Twig_Loader_Array(array())); $env->addFilter(new Twig_Filter('anonymous', function () {})); return $env; } } function twig_tests_filter_dummy() { } function twig_tests_filter_barbar($context, $string, $arg1 = null, $arg2 = null, array $args = array()) { } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/FunctionTest.php�����������������������������������������0000664�0000000�0000000�00000011514�13246545745�0023633�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_FunctionTest extends Twig_Test_NodeTestCase { public function testConstructor() { $name = 'function'; $args = new Twig_Node(); $node = new Twig_Node_Expression_Function($name, $args, 1); $this->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_Function('foo', 'twig_tests_function_dummy', array())); $environment->addFunction(new Twig_Function('bar', 'twig_tests_function_dummy', array('needs_environment' => true))); $environment->addFunction(new Twig_Function('foofoo', 'twig_tests_function_dummy', array('needs_context' => true))); $environment->addFunction(new Twig_Function('foobar', 'twig_tests_function_dummy', array('needs_environment' => true, 'needs_context' => true))); $environment->addFunction(new Twig_Function('barbar', 'twig_tests_function_barbar', array('is_variadic' => true))); $tests = array(); $node = $this->createFunction('foo'); $tests[] = array($node, 'twig_tests_function_dummy()', $environment); $node = $this->createFunction('foo', array(new Twig_Node_Expression_Constant('bar', 1), new Twig_Node_Expression_Constant('foobar', 1))); $tests[] = array($node, 'twig_tests_function_dummy("bar", "foobar")', $environment); $node = $this->createFunction('bar'); $tests[] = array($node, 'twig_tests_function_dummy($this->env)', $environment); $node = $this->createFunction('bar', array(new Twig_Node_Expression_Constant('bar', 1))); $tests[] = array($node, 'twig_tests_function_dummy($this->env, "bar")', $environment); $node = $this->createFunction('foofoo'); $tests[] = array($node, 'twig_tests_function_dummy($context)', $environment); $node = $this->createFunction('foofoo', array(new Twig_Node_Expression_Constant('bar', 1))); $tests[] = array($node, 'twig_tests_function_dummy($context, "bar")', $environment); $node = $this->createFunction('foobar'); $tests[] = array($node, 'twig_tests_function_dummy($this->env, $context)', $environment); $node = $this->createFunction('foobar', array(new Twig_Node_Expression_Constant('bar', 1))); $tests[] = array($node, 'twig_tests_function_dummy($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 $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() { $env = new Twig_Environment(new Twig_Loader_Array(array())); $env->addFunction(new Twig_Function('anonymous', function () {})); return $env; } } function twig_tests_function_dummy() { } function twig_tests_function_barbar($arg1 = null, $arg2 = null, array $args = array()) { } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/GetAttrTest.php������������������������������������������0000664�0000000�0000000�00000004477�13246545745�0023432�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_GetAttrTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Name('foo', 1); $attr = new Twig_Node_Expression_Constant('bar', 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::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, '(($__internal_%s = // line 1'."\n". '($context["foo"] ?? null)) && is_array($__internal_%s) || $__internal_%s instanceof ArrayAccess ? ($__internal_%s["bar"] ?? null) : null)', null, true, ); $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; } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/NameTest.php���������������������������������������������0000664�0000000�0000000�00000002621�13246545745�0022725�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_NameTest extends Twig_Test_NodeTestCase { public function testConstructor() { $node = new Twig_Node_Expression_Name('foo', 1); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { $node = new Twig_Node_Expression_Name('foo', 1); $self = new Twig_Node_Expression_Name('_self', 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)); $output = '(isset($context["foo"]) || array_key_exists("foo", $context) ? $context["foo"] : (function () { throw new Twig_Error_Runtime(\'Variable "foo" does not exist.\', 1, $this->source); })())'; return array( array($node, "// line 1\n".$output, $env), array($node, $this->getVariableGetter('foo', 1), $env1), array($self, "// line 1\n\$this->getTemplateName()"), array($context, "// line 1\n\$context"), ); } } ���������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/NullCoalesceTest.php�������������������������������������0000664�0000000�0000000�00000001127�13246545745�0024416�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_NullCoalesceTest extends Twig_Test_NodeTestCase { public function getTests() { $left = new Twig_Node_Expression_Name('foo', 1); $right = new Twig_Node_Expression_Constant(2, 1); $node = new Twig_Node_Expression_NullCoalesce($left, $right, 1); return array(array($node, "((// line 1\n\$context[\"foo\"]) ?? (2))")); } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/ParentTest.php�������������������������������������������0000664�0000000�0000000�00000001241�13246545745�0023273�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_ParentTest extends Twig_Test_NodeTestCase { public function testConstructor() { $node = new Twig_Node_Expression_Parent('foo', 1); $this->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; } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/TestTest.php���������������������������������������������0000664�0000000�0000000�00000006174�13246545745�0022773�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_TestTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant('foo', 1); $name = new Twig_Node_Expression_Constant('null', 1); $args = new Twig_Node(); $node = new Twig_Node_Expression_Test($expr, $name, $args, 1); $this->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_Test('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 $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() { $env = new Twig_Environment(new Twig_Loader_Array(array())); $env->addTest(new Twig_Test('anonymous', function () {})); return $env; } } function twig_tests_test_barbar($string, $arg1 = null, $arg2 = null, array $args = array()) { } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Unary/���������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0021571�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Unary/NegTest.php����������������������������������������0000664�0000000�0000000�00000001460�13246545745�0023654�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Unary_NegTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant(1, 1); $node = new Twig_Node_Expression_Unary_Neg($expr, 1); $this->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'), ); } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Unary/NotTest.php����������������������������������������0000664�0000000�0000000�00000001347�13246545745�0023707�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Unary_NotTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant(1, 1); $node = new Twig_Node_Expression_Unary_Not($expr, 1); $this->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'), ); } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/Expression/Unary/PosTest.php����������������������������������������0000664�0000000�0000000�00000001347�13246545745�0023710�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_Expression_Unary_PosTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant(1, 1); $node = new Twig_Node_Expression_Unary_Pos($expr, 1); $this->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'), ); } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/ForTest.php���������������������������������������������������������0000664�0000000�0000000�00000017276�13246545745�0020450�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_ForTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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 = 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', 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, <<<EOF // line 1 \$context['_parent'] = \$context; \$context['_seq'] = twig_ensure_traversable({$this->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, <<<EOF // line 1 \$context['_parent'] = \$context; \$context['_seq'] = twig_ensure_traversable({$this->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, <<<EOF // line 1 \$context['_parent'] = \$context; \$context['_seq'] = twig_ensure_traversable({$this->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, <<<EOF // line 1 \$context['_parent'] = \$context; \$context['_seq'] = twig_ensure_traversable({$this->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; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/IfTest.php����������������������������������������������������������0000664�0000000�0000000�00000004604�13246545745�0020247�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_IfTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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, <<<EOF // line 1 if (true) { echo {$this->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, <<<EOF // line 1 if (true) { echo {$this->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, <<<EOF // line 1 if (true) { echo {$this->getVariableGetter('foo')}; } else { echo {$this->getVariableGetter('bar')}; } EOF ); return $tests; } } ����������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/ImportTest.php������������������������������������������������������0000664�0000000�0000000�00000002014�13246545745�0021154�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_ImportTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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, <<<EOF // line 1 \$context["macro"] = \$this->loadTemplate("foo.twig", null, 1); EOF ); return $tests; } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/IncludeTest.php�����������������������������������������������������0000664�0000000�0000000�00000005344�13246545745�0021276�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_IncludeTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant('foo.twig', 1); $node = new Twig_Node_Include($expr, null, false, false, 1); $this->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, <<<EOF // line 1 \$this->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, <<<EOF // line 1 \$this->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, <<<EOF // line 1 \$this->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, <<<EOF // line 1 \$this->loadTemplate("foo.twig", null, 1)->display(array("foo" => true)); EOF ); $node = new Twig_Node_Include($expr, $vars, true, true, 1); $tests[] = array($node, <<<EOF // line 1 try { \$this->loadTemplate("foo.twig", null, 1)->display(array("foo" => true)); } catch (Twig_Error_Loader \$e) { // ignore missing template } EOF ); return $tests; } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/MacroTest.php�������������������������������������������������������0000664�0000000�0000000�00000003140�13246545745�0020744�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_MacroTest extends Twig_Test_NodeTestCase { public function testConstructor() { $body = new Twig_Node_Text('foo', 1); $arguments = new Twig_Node(array(new Twig_Node_Expression_Name('foo', 1)), array(), 1); $node = new Twig_Node_Macro('foo', $body, $arguments, 1); $this->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); return array( array($node, <<<EOF // line 1 public function macro_foo(\$__foo__ = null, \$__bar__ = "Foo", ...\$__varargs__) { \$context = \$this->env->mergeGlobals(array( "foo" => \$__foo__, "bar" => \$__bar__, "varargs" => \$__varargs__, )); \$blocks = array(); ob_start(); try { echo "foo"; return ('' === \$tmp = ob_get_contents()) ? '' : new Twig_Markup(\$tmp, \$this->env->getCharset()); } finally { ob_end_clean(); } } EOF ), ); } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/ModuleTest.php������������������������������������������������������0000664�0000000�0000000�00000013357�13246545745�0021143�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_ModuleTest extends Twig_Test_NodeTestCase { public function testConstructor() { $body = new Twig_Node_Text('foo', 1); $parent = new Twig_Node_Expression_Constant('layout.twig', 1); $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, $parent, $blocks, $macros, $traits, new Twig_Node(array()), $source); $this->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, <<<EOF <?php /* foo.twig */ class __TwigTemplate_%x extends Twig_Template { private \$source; public function __construct(Twig_Environment \$env) { parent::__construct(\$env); \$this->source = \$this->getSourceContext(); \$this->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 ( 23 => 1,); } 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, <<<EOF <?php /* foo.twig */ class __TwigTemplate_%x extends Twig_Template { private \$source; public function __construct(Twig_Environment \$env) { parent::__construct(\$env); \$this->source = \$this->getSourceContext(); // line 1 \$this->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 ( 30 => 1, 28 => 2, 15 => 1,); } 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, <<<EOF <?php /* foo.twig */ class __TwigTemplate_%x extends Twig_Template { private \$source; public function __construct(Twig_Environment \$env) { parent::__construct(\$env); \$this->source = \$this->getSourceContext(); \$this->blocks = array( ); } protected function doGetParent(array \$context) { // line 2 return \$this->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 ( 29 => 2, 27 => 4, 21 => 2,); } public function getSourceContext() { return new Twig_Source("{{ foo }}", "foo.twig", ""); } } EOF , $twig, true); return $tests; } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/PrintTest.php�������������������������������������������������������0000664�0000000�0000000�00000001301�13246545745�0020774�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_PrintTest extends Twig_Test_NodeTestCase { public function testConstructor() { $expr = new Twig_Node_Expression_Constant('foo', 1); $node = new Twig_Node_Print($expr, 1); $this->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; } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/SandboxTest.php�����������������������������������������������������0000664�0000000�0000000�00000001670�13246545745�0021307�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_SandboxTest extends Twig_Test_NodeTestCase { public function testConstructor() { $body = new Twig_Node_Text('foo', 1); $node = new Twig_Node_Sandbox($body, 1); $this->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, <<<EOF // line 1 \$sandbox = \$this->extensions['Twig_Extension_Sandbox']; if (!\$alreadySandboxed = \$sandbox->isSandboxed()) { \$sandbox->enableSandbox(); } echo "foo"; if (!\$alreadySandboxed) { \$sandbox->disableSandbox(); } EOF ); return $tests; } } ������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/SandboxedPrintTest.php����������������������������������������������0000664�0000000�0000000�00000001442�13246545745�0022632�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_SandboxedPrintTest extends Twig_Test_NodeTestCase { public function testConstructor() { $node = new Twig_Node_SandboxedPrint($expr = new Twig_Node_Expression_Constant('foo', 1), 1); $this->assertEquals($expr, $node->getNode('expr')); } public function getTests() { $tests = array(); $tests[] = array(new Twig_Node_SandboxedPrint(new Twig_Node_Expression_Constant('foo', 1), 1), <<<EOF // line 1 echo \$this->extensions['Twig_Extension_Sandbox']->ensureToStringAllowed("foo"); EOF ); return $tests; } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/SetTest.php���������������������������������������������������������0000664�0000000�0000000�00000004773�13246545745�0020453�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_SetTest extends Twig_Test_NodeTestCase { public function testConstructor() { $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); $this->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, <<<EOF // line 1 \$context["foo"] = "foo"; EOF ); $names = new Twig_Node(array(new Twig_Node_Expression_AssignName('foo', 1)), array(), 1); $values = new Twig_Node(array(new Twig_Node_Print(new Twig_Node_Expression_Constant('foo', 1), 1)), array(), 1); $node = new Twig_Node_Set(true, $names, $values, 1); $tests[] = array($node, <<<EOF // line 1 ob_start(); echo "foo"; \$context["foo"] = ('' === \$tmp = ob_get_clean()) ? '' : new Twig_Markup(\$tmp, \$this->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, <<<EOF // line 1 \$context["foo"] = ('' === \$tmp = "foo") ? '' : new Twig_Markup(\$tmp, \$this->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, <<<EOF // line 1 list(\$context["foo"], \$context["bar"]) = array("foo", {$this->getVariableGetter('bar')}); EOF ); return $tests; } } �����Twig-2.4.6/test/Twig/Tests/Node/SpacelessTest.php���������������������������������������������������0000664�0000000�0000000�00000001661�13246545745�0021633�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_SpacelessTest extends Twig_Test_NodeTestCase { public function testConstructor() { $body = new Twig_Node(array(new Twig_Node_Text('<div> <div> foo </div> </div>', 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('<div> <div> foo </div> </div>', 1))); $node = new Twig_Node_Spaceless($body, 1); return array( array($node, <<<EOF // line 1 ob_start(); echo "<div> <div> foo </div> </div>"; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); EOF ), ); } } �������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Node/TextTest.php��������������������������������������������������������0000664�0000000�0000000�00000001140�13246545745�0020625�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Node_TextTest extends Twig_Test_NodeTestCase { public function testConstructor() { $node = new Twig_Node_Text('foo', 1); $this->assertEquals('foo', $node->getAttribute('data')); } public function getTests() { $tests = array(); $tests[] = array(new Twig_Node_Text('foo', 1), "// line 1\necho \"foo\";"); return $tests; } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/NodeVisitor/�������������������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0017714�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/NodeVisitor/OptimizerTest.php��������������������������������������������0000664�0000000�0000000�00000010752�13246545745�0023254�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_NodeVisitor_OptimizerTest extends \PHPUnit\Framework\TestCase { public function testRenderBlockOptimizer() { $env = new Twig_Environment($this->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')); } /** * @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_Node $node, $target, $withLoop) { 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; } } } } ����������������������Twig-2.4.6/test/Twig/Tests/ParserTest.php�����������������������������������������������������������0000664�0000000�0000000�00000014254�13246545745�0020262�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_ParserTest extends \PHPUnit\Framework\TestCase { /** * @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(); $m = new ReflectionMethod($parser, 'filterBodyNodes'); $m->setAccessible(true); $this->assertEquals($expected, $m->invoke($parser, $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(); $m = new ReflectionMethod($parser, 'filterBodyNodes'); $m->setAccessible(true); $m->invoke($parser, $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(); $m = new ReflectionMethod($parser, 'filterBodyNodes'); $m->setAccessible(true); $m->invoke($parser, 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(<<<EOF {% from _self import foo %} {% macro foo() %} {{ foo }} {% endmacro %} EOF , 'index'))); // The getVarName() must not depend on the template loaders, // If this test does not throw any exception, that's good. // see https://github.com/symfony/symfony/issues/4218 $this->addToAssertionCount(1); } protected function getParser() { $parser = new Twig_Parser(new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock())); $parser->setParent(new Twig_Node()); $p = new ReflectionProperty($parser, 'stream'); $p->setAccessible(true); $p->setValue($parser, new Twig_TokenStream(array())); return $parser; } } 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'; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Profiler/����������������������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0017231�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Profiler/Dumper/���������������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0020465�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Profiler/Dumper/AbstractTest.php�����������������������������������������0000664�0000000�0000000�00000010262�13246545745�0023602�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ abstract class Twig_Tests_Profiler_Dumper_AbstractTest extends \PHPUnit\Framework\TestCase { protected function getProfile() { $profile = $this->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; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Profiler/Dumper/BlackfireTest.php����������������������������������������0000664�0000000�0000000�00000001450�13246545745�0023720�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Profiler_Dumper_BlackfireTest extends Twig_Tests_Profiler_Dumper_AbstractTest { public function testDump() { $dumper = new Twig_Profiler_Dumper_Blackfire(); $this->assertStringMatchesFormat(<<<EOF file-format: BlackfireProbe cost-dimensions: wt mu pmu request-start: %d.%d main()//1 %d %d %d main()==>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())); } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Profiler/Dumper/HtmlTest.php���������������������������������������������0000664�0000000�0000000�00000002053�13246545745�0022742�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Profiler_Dumper_HtmlTest extends Twig_Tests_Profiler_Dumper_AbstractTest { public function testDump() { $dumper = new Twig_Profiler_Dumper_Html(); $this->assertStringMatchesFormat(<<<EOF <pre>main <span style="color: #d44">%d.%dms/%d%</span> └ <span style="background-color: #ffd">index.twig</span> <span style="color: #d44">%d.%dms/%d%</span> └ embedded.twig::block(<span style="background-color: #dfd">body</span>) └ <span style="background-color: #ffd">embedded.twig</span> │ └ <span style="background-color: #ffd">included.twig</span> └ index.twig::macro(<span style="background-color: #ddf">foo</span>) └ <span style="background-color: #ffd">embedded.twig</span> └ <span style="background-color: #ffd">included.twig</span> </pre> EOF , $dumper->dump($this->getProfile())); } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Profiler/Dumper/TextTest.php���������������������������������������������0000664�0000000�0000000�00000001252�13246545745�0022762�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Profiler_Dumper_TextTest extends Twig_Tests_Profiler_Dumper_AbstractTest { public function testDump() { $dumper = new Twig_Profiler_Dumper_Text(); $this->assertStringMatchesFormat(<<<EOF 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())); } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Profiler/ProfileTest.php�������������������������������������������������0000664�0000000�0000000�00000007243�13246545745�0022210�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Profiler_ProfileTest extends \PHPUnit\Framework\TestCase { public function testConstructor() { $profile = new Twig_Profiler_Profile('template', 'type', 'name'); $this->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()); } } �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/TemplateTest.php���������������������������������������������������������0000664�0000000�0000000�00000057340�13246545745�0020604�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_TemplateTest extends \PHPUnit\Framework\TestCase { /** * @expectedException LogicException */ public function testDisplayBlocksAcceptTemplateOnlyAsBlocks() { $template = $this->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()"/"hasa()" 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()"/"hasmissing_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 { twig_get_attribute($twig, $template->getSourceContext(), $object, $item, array(), 'any', false, false, true); 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), ); } /** * @expectedException Twig_Error_Runtime * @expectedExceptionMessage Block "unknown" on template "index.twig" does not exist in "index.twig". */ public function testRenderBlockWithUndefinedBlock() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $template = new Twig_TemplateTest($twig, 'index.twig'); try { $template->renderBlock('unknown', array()); } catch (\Exception $e) { ob_end_clean(); throw $e; } } /** * @expectedException Twig_Error_Runtime * @expectedExceptionMessage Block "unknown" on template "index.twig" does not exist in "index.twig". */ public function testDisplayBlockWithUndefinedBlock() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $template = new Twig_TemplateTest($twig, 'index.twig'); $template->displayBlock('unknown', array()); } /** * @expectedException Twig_Error_Runtime * @expectedExceptionMessage Block "foo" should not call parent() in "index.twig" as the block does not exist in the parent template "parent.twig" */ public function testDisplayBlockWithUndefinedParentBlock() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $template = new Twig_TemplateTest($twig, 'parent.twig'); $template->displayBlock('foo', array(), array('foo' => array(new Twig_TemplateTest($twig, 'index.twig'), 'block_foo')), false); } public function testGetAttributeOnArrayWithConfusableKey() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $template = new Twig_TemplateTest($twig); $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', twig_get_attribute($twig, $template->getSourceContext(), $array, false), 'false is treated as 0 when accessing an array (equals PHP behavior)'); $this->assertSame('One', twig_get_attribute($twig, $template->getSourceContext(), $array, true), 'true is treated as 1 when accessing an array (equals PHP behavior)'); $this->assertSame('One', twig_get_attribute($twig, $template->getSourceContext(), $array, 1.5), 'float is casted to int when accessing an array (equals PHP behavior)'); $this->assertSame('One', twig_get_attribute($twig, $template->getSourceContext(), $array, '1'), '"1" is treated as integer 1 when accessing an array (equals PHP behavior)'); $this->assertSame('MinusOne', twig_get_attribute($twig, $template->getSourceContext(), $array, -1.5), 'negative float is casted to int when accessing an array (equals PHP behavior)'); $this->assertSame('FloatButString', twig_get_attribute($twig, $template->getSourceContext(), $array, '1.5'), '"1.5" is treated as-is when accessing an array (equals PHP behavior)'); $this->assertSame('IntegerButStringWithLeadingZeros', twig_get_attribute($twig, $template->getSourceContext(), $array, '01'), '"01" is treated as-is when accessing an array (equals PHP behavior)'); $this->assertSame('EmptyString', twig_get_attribute($twig, $template->getSourceContext(), $array, null), 'null is treated as "" when accessing an array (equals PHP behavior)'); } /** * @dataProvider getGetAttributeTests */ public function testGetAttribute($defined, $value, $object, $item, $arguments, $type) { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $template = new Twig_TemplateTest($twig); $this->assertEquals($value, twig_get_attribute($twig, $template->getSourceContext(), $object, $item, $arguments, $type)); } /** * @dataProvider getGetAttributeTests */ public function testGetAttributeStrict($defined, $value, $object, $item, $arguments, $type, $exceptionMessage = null) { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true)); $template = new Twig_TemplateTest($twig); if ($defined) { $this->assertEquals($value, twig_get_attribute($twig, $template->getSourceContext(), $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, twig_get_attribute($twig, $template->getSourceContext(), $object, $item, $arguments, $type)); } } /** * @dataProvider getGetAttributeTests */ public function testGetAttributeDefined($defined, $value, $object, $item, $arguments, $type) { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $template = new Twig_TemplateTest($twig); $this->assertEquals($defined, twig_get_attribute($twig, $template->getSourceContext(), $object, $item, $arguments, $type, true)); } /** * @dataProvider getGetAttributeTests */ public function testGetAttributeDefinedStrict($defined, $value, $object, $item, $arguments, $type) { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true)); $template = new Twig_TemplateTest($twig); $this->assertEquals($defined, twig_get_attribute($twig, $template->getSourceContext(), $object, $item, $arguments, $type, true)); } public function testGetAttributeCallExceptions() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $template = new Twig_TemplateTest($twig); $object = new Twig_TemplateMagicMethodExceptionObject(); $this->assertNull(twig_get_attribute($twig, $template->getSourceContext(), $object, 'foo')); } public function getGetAttributeTests() { $array = array( 'defined' => 'defined', 'zero' => 0, 'null' => null, '1' => 1, 'bar' => true, 'foo' => true, 'baz' => 'baz', 'baf' => 'baf', '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, true, 'foo'), array(true, 'baz', 'baz'), array(true, 'baf', 'baf'), 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() { $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock(), array('strict_variables' => true)); $getIsObject = new Twig_TemplateGetIsMethods(); $template = new Twig_TemplateTest($twig, array('strict_variables' => true)); // first time should not create a cache for "get" $this->assertNull(twig_get_attribute($twig, $template->getSourceContext(), $getIsObject, 'get')); // 0 should be in the method cache now, so this should fail $this->assertNull(twig_get_attribute($twig, $template->getSourceContext(), $getIsObject, 0)); } } class Twig_TemplateTest extends Twig_Template { private $name; public function __construct(Twig_Environment $env, $name = 'index.twig') { parent::__construct($env); $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 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, 'foo' => true, 'baz' => 'baz', 'baf' => 'baf', '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, 'foo' => true, 'baz' => 'baz', 'baf' => 'baf', '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 $foo = true; public $baz = 'baz'; public $baf = 'baf'; 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 hasFoo() { return true; } public function hasBaz() { return 'should never be returned (has)'; } public function isBaz() { return 'should never be returned (is)'; } public function getBaz() { return 'Baz'; } public function baz() { return 'baz'; } public function hasBaf() { return 'should never be returned (has)'; } public function isBaf() { return 'baf'; } 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)); } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/TemplateWrapperTest.php��������������������������������������������������0000664�0000000�0000000�00000004700�13246545745�0022135�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_TemplateWrapperTest extends \PHPUnit\Framework\TestCase { public function testHasGetBlocks() { $twig = new Twig_Environment(new Twig_Loader_Array(array( 'index' => '{% 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()); } } ����������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/TokenStreamTest.php������������������������������������������������������0000664�0000000�0000000�00000003751�13246545745�0021262�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_TokenStreamTest extends \PHPUnit\Framework\TestCase { protected static $tokens; protected function setUp() { self::$tokens = array( new Twig_Token(Twig_Token::TEXT_TYPE, 1, 1), new Twig_Token(Twig_Token::TEXT_TYPE, 2, 1), new Twig_Token(Twig_Token::TEXT_TYPE, 3, 1), new Twig_Token(Twig_Token::TEXT_TYPE, 4, 1), new Twig_Token(Twig_Token::TEXT_TYPE, 5, 1), new Twig_Token(Twig_Token::TEXT_TYPE, 6, 1), new Twig_Token(Twig_Token::TEXT_TYPE, 7, 1), new Twig_Token(Twig_Token::EOF_TYPE, 0, 1), ); } 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(); } } } �����������������������Twig-2.4.6/test/Twig/Tests/Util/��������������������������������������������������������������������0000775�0000000�0000000�00000000000�13246545745�0016364�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/Util/DeprecationCollectorTest.php����������������������������������������0000664�0000000�0000000�00000002167�13246545745�0024047�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /* * This file is part of Twig. * * (c) Fabien Potencier * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ class Twig_Tests_Util_DeprecationCollectorTest extends \PHPUnit\Framework\TestCase { /** * @requires PHP 5.3 */ public function testCollect() { $twig = new Twig_Environment($this->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") }}', )); } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Twig-2.4.6/test/Twig/Tests/escapingTest.php���������������������������������������������������������0000664�0000000�0000000�00000024372�13246545745�0020621�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php /** * This class is adapted from code coming from Zend Framework. * * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Twig_Test_EscapingTest extends \PHPUnit\Framework\TestCase { /** * All character encodings supported by htmlspecialchars(). */ protected $htmlSpecialChars = array( '\'' => ''', '"' => '"', '<' => '<', '>' => '>', '&' => '&', ); 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 */ '<' => '\\x3C', '>' => '\\x3E', '\'' => '\\x27', '"' => '\\x22', '&' => '\\x26', /* Characters beyond ASCII value 255 to unicode escape */ 'Ā' => '\\u0100', /* Immune chars excluded */ ',' => ',', '.' => '.', '_' => '_', /* Basic alnums excluded */ 'a' => 'a', 'A' => 'A', 'z' => 'z', 'Z' => 'Z', '0' => '0', '9' => '9', /* Basic control characters and null */ "\r" => '\\x0D', "\n" => '\\x0A', "\t" => '\\x09', "\0" => '\\x00', /* Encode spaces for quoteless attribute protection */ ' ' => '\\x20', ); 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!"); } } } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������