pax_global_header00006660000000000000000000000064136245734470014531gustar00rootroot0000000000000052 comment=9c748d36b1838ee67fdbe117e9fe9c71cc211448 php-twig-2.12.5/000077500000000000000000000000001362457344700133575ustar00rootroot00000000000000php-twig-2.12.5/.editorconfig000066400000000000000000000003401362457344700160310ustar00rootroot00000000000000; 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 php-twig-2.12.5/.gitignore000066400000000000000000000000721362457344700153460ustar00rootroot00000000000000/composer.lock /phpunit.xml /vendor .phpunit.result.cache php-twig-2.12.5/.php_cs.dist000066400000000000000000000014371362457344700156030ustar00rootroot00000000000000setRules([ '@Symfony' => true, '@Symfony:risky' => true, '@PHPUnit75Migration:risky' => true, 'php_unit_dedicate_assert' => ['target' => '5.6'], 'array_syntax' => ['syntax' => 'short'], 'php_unit_fqcn_annotation' => true, 'no_unreachable_default_argument_value' => false, 'braces' => ['allow_single_line_closure' => true], 'heredoc_to_nowdoc' => false, 'ordered_imports' => true, 'phpdoc_types_order' => ['null_adjustment' => 'always_last', 'sort_algorithm' => 'none'], 'native_function_invocation' => ['include' => ['@compiler_optimized'], 'scope' => 'all'], ]) ->setRiskyAllowed(true) ->setFinder(PhpCsFixer\Finder::create()->in(__DIR__)) ; php-twig-2.12.5/.travis.yml000066400000000000000000000033631362457344700154750ustar00rootroot00000000000000language: php cache: directories: - vendor - extra/*/vendor - $HOME/.composer/cache/files env: global: - SYMFONY_PHPUNIT_REMOVE_RETURN_TYPEHINT=1 - SYMFONY_PHPUNIT_DISABLE_RESULT_CACHE=1 before_install: - phpenv config-rm xdebug.ini || return 0 install: - travis_retry composer install - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/cssinliner-extra && travis_retry composer install) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/html-extra && travis_retry composer install) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/inky-extra && travis_retry composer install) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/intl-extra && travis_retry composer install) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/markdown-extra && travis_retry composer install) - ([[ $TRAVIS_PHP_VERSION < 7.2 ]] || cd extra/string-extra && travis_retry composer install) script: - ./vendor/bin/simple-phpunit - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/cssinliner-extra && ./vendor/bin/simple-phpunit) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/html-extra && ./vendor/bin/simple-phpunit) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/inky-extra && ./vendor/bin/simple-phpunit) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/intl-extra && ./vendor/bin/simple-phpunit) - ([[ $TRAVIS_PHP_VERSION = 7.0 ]] || cd extra/markdown-extra && ./vendor/bin/simple-phpunit) - ([[ $TRAVIS_PHP_VERSION < 7.2 ]] || cd extra/string-extra && ./vendor/bin/simple-phpunit) jobs: fast_finish: true include: - php: 7.0 - php: 7.1 - php: 7.2 - php: 7.3 - php: 7.4 - stage: integration tests php: 7.3 script: ./drupal_test.sh php-twig-2.12.5/CHANGELOG000066400000000000000000001716541362457344700146070ustar00rootroot00000000000000* 2.12.5 (2020-02-11) * Add a check to ensure that iconv() is defined * 2.12.4 (2020-02-11) * Avoid exceptions when an intl resource is not found * Fix implementation of case-insensitivity for method names * 2.12.3 (2019-12-28) * fixed Symfony 5.0 support for the HTML extra extension * fixed number formatter in Intl extra extension when using a formatter prototype * 2.12.2 (2019-11-11) * added supported for exponential numbers * 2.12.1 (2019-10-17) * added the String extension in the "extra" repositories: "u" filter * 2.12.0 (2019-10-05) * added the spaceship operator ("<=>"), useful when using an arrow function in the "sort" filter * added support for an "arrow" function on the "sort" filter * added the CssInliner extension in the "extra" repositories: "inline_css" filter * added the Inky extension in the "extra" repositories: "inky_to_html" filter * added Intl extension in the "extra" repositories: "country_name", "currency_name", "currency_symbol", "language_name", "locale_name", "timezone_name", "format_currency", "format_number", "format_*_number", "format_datetime", "format_date", and "format_time" filters, and the "country_timezones" function * added the Markdown extension in the "extra" repositories: "markdown_to_html", and "html_to_markdown" filters * added the HtmlExtension extension in the "extra" repositories: "date_uri" filter, and "html_classes" function * optimized "block('foo') ?? 'bar'" * fixed the empty test on Traversable instances * fixed array_key_exists() on objects * fixed cache when opcache is installed but disabled * fixed using macros in arrow functions * fixed split filter on edge case * 2.11.3 (2019-06-18) * display partial output (PHP buffer) when an error occurs in debug mode * fixed the filter filter (allow the result to be used several times) * fixed macro auto-import when a template contains only macros * 2.11.2 (2019-06-05) * fixed macro auto-import * 2.11.1 (2019-06-04) * added support for "Twig\Markup" instances in the "in" test (again) * allowed string operators as variables names in assignments * fixed support for macros defined in parent templates * 2.11.0 (2019-05-31) * added the possibility to register classes/interfaces as being safe for the escaper ("EscaperExtension::addSafeClass()") * deprecated CoreExtension::setEscaper() and CoreExtension::getEscapers() in favor of the same methods on EscaperExtension * macros are now auto-imported in the template they are defined (under the ``_self`` variable) * added support for macros on "is defined" tests * fixed macros "import" when using the same name in the parent and child templates * fixed recursive macros * macros imported "globally" in a template are now available in macros without re-importing them * fixed the "filter" filter when the argument is \Traversable but does not implement \Iterator (\SimpleXmlElement for instance) * fixed a PHP fatal error when calling a macro imported in a block in a nested block * fixed a PHP fatal error when calling a macro imported in the template in another macro * fixed wrong error message on "import" and "from" * 2.10.0 (2019-05-14) * deprecated "if" conditions on "for" tags * added "filter", "map", and "reduce" filters (and support for arrow functions) * fixed partial output leak when a PHP fatal error occurs * optimized context access on PHP 7.4 * 2.9.0 (2019-04-28) * deprecated returning "false" to remove a Node from NodeVisitorInterface::leaveNode() * allowed Twig\NodeVisitor\NodeVisitorInterface::leaveNode() to return "null" instead of "false" (same meaning) * deprecated the "filter" tag (use the "apply" tag instead) * added the "apply" tag as a replacement for the "filter" tag * allowed Twig\Loader\FilesystemLoader::findTemplate() to return "null" instead of "false" (same meaning) * added support for "Twig\Markup" instances in the "in" test * fixed "import" when macros are stored in a template string * fixed Lexer when using custom options containing the # char * added template line number to twig_get_attribute() * 2.8.1 (2019-04-16) * fixed EscaperNodeVisitor * deprecated passing a 3rd, 4th, and 5th arguments to the Sandbox exception classes * deprecated Node::setTemplateName() in favor of Node::setSourceContext() * 2.8.0 (2019-04-16) * added Traversable support for the length filter * fixed some wrong location in error messages * made exception creation faster * made escaping on ternary expressions (?: and ??) more fine-grained * added the possibility to give a nice name to string templates (template_from_string function) * fixed the "with" behavior to always include the globals (for consistency with the "include" and "embed" tags) * fixed "include" with "ignore missing" when an error loading occurs in the included template * added support for a new whitespace trimming option ({%~ ~%}, {{~ ~}}, {#~ ~#}) * added the "column" filter * 2.7.4 (2019-03-23) * fixed variadic support * fixed CheckToStringNode implementation (broken when a function/filter is variadic) * 2.7.3 (2019-03-21) * fixed the spaceless filter so that it behaves like the spaceless tag * fixed BC break on Environment::resolveTemplate() * allowed Traversable objects to be used in the "with" tag * allowed Traversable objects to be used in the "with" tag * allowed Traversable objects to be used in the "with" argument of the "include" and "embed" tags * 2.7.2 (2019-03-12) * added TemplateWrapper::getTemplateName() * 2.7.1 (2019-03-12) * fixed class aliases * 2.7.0 (2019-03-12) * fixed sandbox security issue (under some circumstances, calling the __toString() method on an object was possible even if not allowed by the security policy) * fixed batch filter clobbers array keys when fill parameter is used * added preserveKeys support for the batch filter * fixed "embed" support when used from "template_from_string" * deprecated passing a Twig\Template to Twig\Environment::load()/Twig\Environment::resolveTemplate() * added the possibility to pass a TemplateWrapper to Twig\Environment::load() * marked Twig\Environment::getTemplateClass() as internal (implementation detail) * improved the performance of the sandbox * deprecated the spaceless tag * added a spaceless filter * added max value to the "random" function * deprecated Twig\Extension\InitRuntimeInterface * deprecated Twig\Loader\ExistsLoaderInterface * deprecated PSR-0 classes in favor of namespaced ones * made namespace classes the default classes (PSR-0 ones are aliases now) * added Twig\Loader\ChainLoader::getLoaders() * removed duplicated directory separator in FilesystemLoader * deprecated the "base_template_class" option on Twig\Environment * deprecated the Twig\Environment::getBaseTemplateClass() and Twig\Environment::setBaseTemplateClass() methods * changed internal code to use the namespaced classes as much as possible * deprecated Twig_Parser::isReservedMacroName() * 2.6.2 (2019-01-14) * fixed regression (key exists check for non ArrayObject objects) * 2.6.1 (2019-01-14) * fixed ArrayObject access with a null value * fixed embedded templates starting with a BOM * fixed using a Twig_TemplateWrapper instance as an argument to extends * fixed error location when calling an undefined block * deprecated passing a string as a source on Twig_Error * switched generated code to use the PHP short array notation * fixed float representation in compiled templates * added a second argument to the join filter (last separator configuration) * 2.6.0 (2018-12-16) * made sure twig_include returns a string * fixed multi-byte UFT-8 in escape('html_attr') * added the "deprecated" tag * added support for dynamically named tests * fixed GlobalsInterface extended class * fixed filesystem loader throwing an exception instead of returning false * 2.5.0 (2018-07-13) * deprecated using the spaceless tag at the root level of a child template (noop anyway) * deprecated the possibility to define a block in a non-capturing block in a child template * added the Symfony ctype polyfill as a dependency * fixed reporting the proper location for errors compiled in templates * fixed the error handling for the optimized extension-based function calls * ensured that syntax errors are triggered with the right line * "js" filter now produces valid JSON * 2.4.8 (2018-04-02) * fixed a regression when using the "default" filter or the "defined" test on non-existing arrays * 2.4.7 (2018-03-20) * optimized runtime performance * optimized parser performance by inlining the constant values * fixed block names unicity * fixed counting children of SimpleXMLElement objects * added missing else clause to avoid infinite loops * fixed .. (range operator) in sandbox policy * 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.42.6 (2020-XX-XX) * n/a * 1.42.5 (2020-02-11) * Fix implementation of case-insensitivity for method names * 1.42.4 (2019-11-11) * optimized "block('foo') ?? 'bar" * added supported for exponential numbers * 1.42.3 (2019-08-24) * fixed the "split" filter when the delimiter is "0" * fixed the "empty" test on Traversable instances * fixed cache when opcache is installed but disabled * fixed PHP 7.4 compatibility * bumped the minimal PHP version to 5.5 * 1.42.2 (2019-06-18) * Display partial output (PHP buffer) when an error occurs in debug mode * 1.42.1 (2019-06-04) * added support for "Twig\Markup" instances in the "in" test (again) * allowed string operators as variables names in assignments * 1.42.0 (2019-05-31) * fixed the "filter" filter when the argument is \Traversable but does not implement \Iterator (\SimpleXmlElement for instance) * fixed a PHP fatal error when calling a macro imported in a block in a nested block * fixed a PHP fatal error when calling a macro imported in the template in another macro * fixed wrong error message on "import" and "from" * 1.41.0 (2019-05-14) * fixed support for PHP 7.4 * added "filter", "map", and "reduce" filters (and support for arrow functions) * fixed partial output leak when a PHP fatal error occurs * optimized context access on PHP 7.4 * 1.40.1 (2019-04-29) * fixed regression in NodeTraverser * 1.40.0 (2019-04-28) * allowed Twig\NodeVisitor\NodeVisitorInterface::leaveNode() to return "null" instead of "false" (same meaning) * added the "apply" tag as a replacement for the "filter" tag * allowed Twig\Loader\FilesystemLoader::findTemplate() to return "null" instead of "false" (same meaning) * added support for "Twig\Markup" instances in the "in" test * fixed Lexer when using custom options containing the # char * fixed "import" when macros are stored in a template string * 1.39.1 (2019-04-16) * fixed EscaperNodeVisitor * 1.39.0 (2019-04-16) * added Traversable support for the length filter * fixed some wrong location in error messages * made exception creation faster * made escaping on ternary expressions (?: and ??) more fine-grained * added the possibility to give a nice name to string templates (template_from_string function) * fixed the "with" behavior to always include the globals (for consistency with the "include" and "embed" tags) * fixed "include" with "ignore missing" when an error loading occurs in the included template * added support for a new whitespace trimming option ({%~ ~%}, {{~ ~}}, {#~ ~#}) * 1.38.4 (2019-03-23) * fixed CheckToStringNode implementation (broken when a function/filter is variadic) * 1.38.3 (2019-03-21) * fixed the spaceless filter so that it behaves like the spaceless tag * fixed BC break on Environment::resolveTemplate() * fixed the bundled Autoloader to also load namespaced classes * allowed Traversable objects to be used in the "with" tag * allowed Traversable objects to be used in the "with" argument of the "include" and "embed" tags * 1.38.2 (2019-03-12) * added TemplateWrapper::getTemplateName() * 1.38.1 (2019-03-12) * fixed class aliases * 1.38.0 (2019-03-12) * fixed sandbox security issue (under some circumstances, calling the __toString() method on an object was possible even if not allowed by the security policy) * fixed batch filter clobbers array keys when fill parameter is used * added preserveKeys support for the batch filter * fixed "embed" support when used from "template_from_string" * added the possibility to pass a TemplateWrapper to Twig\Environment::load() * improved the performance of the sandbox * added a spaceless filter * added max value to the "random" function * made namespace classes the default classes (PSR-0 ones are aliases now) * removed duplicated directory separator in FilesystemLoader * added Twig\Loader\ChainLoader::getLoaders() * changed internal code to use the namespaced classes as much as possible * 1.37.1 (2019-01-14) * fixed regression (key exists check for non ArrayObject objects) * fixed logic in TemplateWrapper * 1.37.0 (2019-01-14) * fixed ArrayObject access with a null value * fixed embedded templates starting with a BOM * fixed using a Twig_TemplateWrapper instance as an argument to extends * switched generated code to use the PHP short array notation * dropped PHP 5.3 support * fixed float representation in compiled templates * added a second argument to the join filter (last separator configuration) * 1.36.0 (2018-12-16) * made sure twig_include returns a string * fixed multi-byte UFT-8 in escape('html_attr') * added the "deprecated" tag * added support for dynamically named tests * fixed GlobalsInterface extended class * fixed filesystem loader throwing an exception instead of returning false * 1.35.4 (2018-07-13) * ensured that syntax errors are triggered with the right line * added the Symfony ctype polyfill as a dependency * "js" filter now produces valid JSON * 1.35.3 (2018-03-20) * fixed block names unicity * fixed counting children of SimpleXMLElement objects * added missing else clause to avoid infinite loops * fixed .. (range operator) in sandbox policy * 1.35.2 (2018-03-03) * fixed a regression in the way the profiler is registered in templates * 1.35.1 (2018-03-02) * added an exception when using "===" instead of "same as" * fixed possible array to string conversion concealing actual error * made variable names deterministic in compiled templates * fixed length filter when passing an instance of IteratorAggregate * fixed Environment::resolveTemplate to accept instances of TemplateWrapper * 1.35.0 (2017-09-27) * added Twig_Profiler_Profile::reset() * fixed use TokenParser to return an empty Node * added RuntimeExtensionInterface * added circular reference detection when loading templates * 1.34.4 (2017-07-04) * added support for runtime loaders in IntegrationTestCase * fixed deprecation when using Twig_Profiler_Dumper_Html * 1.34.3 (2017-06-07) * fixed namespaces introduction * 1.34.2 (2017-06-05) * fixed namespaces introduction * 1.34.1 (2017-06-05) * fixed namespaces introduction * 1.34.0 (2017-06-05) * added support for PHPUnit 6 when testing extensions * fixed PHP 7.2 compatibility * fixed template name generation in Twig_Environment::createTemplate() * removed final tag on Twig_TokenParser_Include * added namespaced aliases for all (non-deprecated) classes and interfaces * dropped HHVM support * dropped PHP 5.2 support * 1.33.2 (2017-04-20) * fixed edge case in the method cache for Twig attributes * 1.33.1 (2017-04-18) * fixed the empty() test * 1.33.0 (2017-03-22) * fixed a race condition handling when writing cache files * "length" filter now returns string length when applied to an object that does not implement \Countable but provides __toString() * "empty" test will now consider the return value of the __toString() method for objects implement __toString() but not \Countable * fixed JS escaping for unicode characters with higher code points * 1.32.0 (2017-02-26) * fixed deprecation notice in Twig_Util_DeprecationCollector * added a PSR-11 compatible runtime loader * added `side` argument to `trim` to allow left or right trimming only. * 1.31.0 (2017-01-11) * added Twig_NodeCaptureInterface for nodes that capture all output * fixed marking the environment as initialized too early * fixed C89 compat for the C extension * turned fatal error into exception when a previously generated cache is corrupted * fixed offline cache warm-ups for embedded templates * 1.30.0 (2016-12-23) * added Twig_FactoryRuntimeLoader * deprecated function/test/filter/tag overriding * deprecated the "disable_c_ext" attribute on Twig_Node_Expression_GetAttr * 1.29.0 (2016-12-13) * fixed sandbox being left enabled if an exception is thrown while rendering * marked some classes as being final (via @final) * made Twig_Error report real source path when possible * added support for {{ _self }} to provide an upgrade path from 1.x to 2.0 (replaces {{ _self.templateName }}) * deprecated silent display of undefined blocks * deprecated support for mbstring.func_overload != 0 * 1.28.2 (2016-11-23) * fixed precedence between getFoo() and isFoo() in Twig_Template::getAttribute() * improved a deprecation message * 1.28.1 (2016-11-18) * fixed block() function when used with a template argument * 1.28.0 (2016-11-17) * added support for the PHP 7 null coalescing operator for the ?? Twig implementation * exposed a way to access template data and methods in a portable way * changed context access to use the PHP 7 null coalescing operator when available * added the "with" tag * added support for a custom template on the block() function * added "is defined" support for block() and constant() * optimized the way attributes are fetched * 1.27.0 (2016-10-25) * deprecated Twig_Parser::getEnvironment() * deprecated Twig_Parser::addHandler() and Twig_Parser::addNodeVisitor() * deprecated Twig_Compiler::addIndentation() * fixed regression when registering two extensions having the same class name * deprecated Twig_LoaderInterface::getSource() (implement Twig_SourceContextLoaderInterface instead) * fixed the filesystem loader with relative paths * deprecated Twig_Node::getLine() in favor of Twig_Node::getTemplateLine() * deprecated Twig_Template::getSource() in favor of Twig_Template::getSourceContext() * deprecated Twig_Node::getFilename() in favor of Twig_Node::getTemplateName() * deprecated the "filename" escaping strategy (use "name" instead) * added Twig_Source to hold information about the original template * deprecated Twig_Error::getTemplateFile() and Twig_Error::setTemplateFile() in favor of Twig_Error::getTemplateName() and Twig_Error::setTemplateName() * deprecated Parser::getFilename() * fixed template paths when a template name contains a protocol like vfs:// * improved debugging with Twig_Sandbox_SecurityError exceptions for disallowed methods and properties * 1.26.1 (2016-10-05) * removed template source code from generated template classes when debug is disabled * fixed default implementation of Twig_Template::getDebugInfo() for better BC * fixed regression on static calls for functions/filters/tests * 1.26.0 (2016-10-02) * added template cache invalidation based on more environment options * added a missing deprecation notice * fixed template paths when a template is stored in a PHAR file * allowed filters/functions/tests implementation to use a different class than the extension they belong to * deprecated Twig_ExtensionInterface::getName() * 1.25.0 (2016-09-21) * changed the way we store template source in template classes * removed usage of realpath in cache keys * fixed Twig cache sharing when used with different versions of PHP * removed embed parent workaround for simple use cases * deprecated the ability to store non Node instances in Node::$nodes * deprecated Twig_Environment::getLexer(), Twig_Environment::getParser(), Twig_Environment::getCompiler() * deprecated Twig_Compiler::getFilename() * 1.24.2 (2016-09-01) * fixed static callables * fixed a potential PHP warning when loading the cache * fixed a case where the autoescaping does not work as expected * 1.24.1 (2016-05-30) * fixed reserved keywords (forbids true, false, null and none keywords for variables names) * fixed support for PHP7 (Throwable support) * marked the following methods as being internals on Twig_Environment: getFunctions(), getFilters(), getTests(), getFunction(), getFilter(), getTest(), getTokenParsers(), getTags(), getNodeVisitors(), getUnaryOperators(), getBinaryOperators(), getFunctions(), getFilters(), getGlobals(), initGlobals(), initExtensions(), and initExtension() * 1.24.0 (2016-01-25) * adding support for the ?? operator * fixed the defined test when used on a constant, a map, or a sequence * undeprecated _self (should only be used to get the template name, not the template instance) * fixed parsing on PHP7 * 1.23.3 (2016-01-11) * fixed typo * 1.23.2 (2015-01-11) * added versions in deprecated messages * made file cache tolerant for trailing (back)slashes on directory configuration * deprecated unused Twig_Node_Expression_ExtensionReference class * 1.23.1 (2015-11-05) * fixed some exception messages which triggered PHP warnings * fixed BC on Twig_Test_NodeTestCase * 1.23.0 (2015-10-29) * deprecated the possibility to override an extension by registering another one with the same name * deprecated Twig_ExtensionInterface::getGlobals() (added Twig_Extension_GlobalsInterface for BC) * deprecated Twig_ExtensionInterface::initRuntime() (added Twig_Extension_InitRuntimeInterface for BC) * deprecated Twig_Environment::computeAlternatives() * 1.22.3 (2015-10-13) * fixed regression when using null as a cache strategy * improved performance when checking template freshness * fixed warnings when loaded templates do not exist * fixed template class name generation to prevent possible collisions * fixed logic for custom escapers to call them even on integers and null values * changed template cache names to take into account the Twig C extension * 1.22.2 (2015-09-22) * fixed a race condition in template loading * 1.22.1 (2015-09-15) * fixed regression in template_from_string * 1.22.0 (2015-09-13) * made Twig_Test_IntegrationTestCase more flexible * added an option to force PHP bytecode invalidation when writing a compiled template into the cache * fixed the profiler duration for the root node * changed template cache names to take into account enabled extensions * deprecated Twig_Environment::clearCacheFiles(), Twig_Environment::getCacheFilename(), Twig_Environment::writeCacheFile(), and Twig_Environment::getTemplateClassPrefix() * added a way to override the filesystem template cache system * added a way to get the original template source from Twig_Template * 1.21.2 (2015-09-09) * fixed variable names for the deprecation triggering code * fixed escaping strategy detection based on filename * added Traversable support for replace, merge, and sort * deprecated support for character by character replacement for the "replace" filter * 1.21.1 (2015-08-26) * fixed regression when using the deprecated Twig_Test_* classes * 1.21.0 (2015-08-24) * added deprecation notices for deprecated features * added a deprecation "framework" for filters/functions/tests and test fixtures * 1.20.0 (2015-08-12) * forbid access to the Twig environment from templates and internal parts of Twig_Template * fixed limited RCEs when in sandbox mode * deprecated Twig_Template::getEnvironment() * deprecated the _self variable for usage outside of the from and import tags * added Twig_BaseNodeVisitor to ease the compatibility of node visitors between 1.x and 2.x * 1.19.0 (2015-07-31) * fixed wrong error message when including an undefined template in a child template * added support for variadic filters, functions, and tests * added support for extra positional arguments in macros * added ignore_missing flag to the source function * fixed batch filter with zero items * deprecated Twig_Environment::clearTemplateCache() * fixed sandbox disabling when using the include function * 1.18.2 (2015-06-06) * fixed template/line guessing in exceptions for nested templates * optimized the number of inodes and the size of realpath cache when using the cache * 1.18.1 (2015-04-19) * fixed memory leaks in the C extension * deprecated Twig_Loader_String * fixed the slice filter when used with a SimpleXMLElement object * fixed filesystem loader when trying to load non-files (like directories) * 1.18.0 (2015-01-25) * fixed some error messages where the line was wrong (unknown variables or argument names) * added a new way to customize the main Module node (via empty nodes) * added Twig_Environment::createTemplate() to create a template from a string * added a profiler * fixed filesystem loader cache when different file paths are used for the same template * 1.17.0 (2015-01-14) * added a 'filename' autoescaping strategy, which dynamically chooses the autoescaping strategy for a template based on template file extension. * 1.16.3 (2014-12-25) * fixed regression for dynamic parent templates * fixed cache management with statcache * fixed a regression in the slice filter * 1.16.2 (2014-10-17) * fixed timezone on dates as strings * fixed 2-words test names when a custom node class is not used * fixed macros when using an argument named like a PHP super global (like GET or POST) * fixed date_modify when working with DateTimeImmutable * optimized for loops * fixed multi-byte characters handling in the split filter * fixed a regression in the in operator * fixed a regression in the slice filter * 1.16.1 (2014-10-10) * improved error reporting in a sandboxed template * fixed missing error file/line information under certain circumstances * fixed wrong error line number in some error messages * fixed the in operator to use strict comparisons * sped up the slice filter * fixed for mb function overload mb_substr acting different * fixed the attribute() function when passing a variable for the arguments * 1.16.0 (2014-07-05) * changed url_encode to always encode according to RFC 3986 * fixed inheritance in a 'use'-hierarchy * removed the __toString policy check when the sandbox is disabled * fixed recursively calling blocks in templates with inheritance * 1.15.1 (2014-02-13) * fixed the conversion of the special '0000-00-00 00:00' date * added an error message when trying to import an undefined block from a trait * fixed a C extension crash when accessing defined but uninitialized property. * 1.15.0 (2013-12-06) * made ignoreStrictCheck in Template::getAttribute() works with __call() methods throwing BadMethodCallException * added min and max functions * added the round filter * fixed a bug that prevented the optimizers to be enabled/disabled selectively * fixed first and last filters for UTF-8 strings * added a source function to include the content of a template without rendering it * fixed the C extension sandbox behavior when get or set is prepend to method name * 1.14.2 (2013-10-30) * fixed error filename/line when an error occurs in an included file * allowed operators that contain whitespaces to have more than one whitespace * allowed tests to be made of 1 or 2 words (like "same as" or "divisible by") * 1.14.1 (2013-10-15) * made it possible to use named operators as variables * fixed the possibility to have a variable named 'matches' * added support for PHP 5.5 DateTimeInterface * 1.14.0 (2013-10-03) * fixed usage of the html_attr escaping strategy to avoid double-escaping with the html strategy * added new operators: ends with, starts with, and matches * fixed some compatibility issues with HHVM * added a way to add custom escaping strategies * fixed the C extension compilation on Windows * fixed the batch filter when using a fill argument with an exact match of elements to batch * fixed the filesystem loader cache when a template name exists in several namespaces * fixed template_from_string when the template includes or extends other ones * fixed a crash of the C extension on an edge case * 1.13.2 (2013-08-03) * fixed the error line number for an error occurs in and embedded template * fixed crashes of the C extension on some edge cases * 1.13.1 (2013-06-06) * added the possibility to ignore the filesystem constructor argument in Twig_Loader_Filesystem * fixed Twig_Loader_Chain::exists() for a loader which implements Twig_ExistsLoaderInterface * adjusted backtrace call to reduce memory usage when an error occurs * added support for object instances as the second argument of the constant test * fixed the include function when used in an assignment * 1.13.0 (2013-05-10) * fixed getting a numeric-like item on a variable ('09' for instance) * fixed getting a boolean or float key on an array, so it is consistent with PHP's array access: `{{ array[false] }}` behaves the same as `echo $array[false];` (equals `$array[0]`) * made the escape filter 20% faster for happy path (escaping string for html with UTF-8) * changed ☃ to § in tests * enforced usage of named arguments after positional ones * 1.12.3 (2013-04-08) * fixed a security issue in the filesystem loader where it was possible to include a template one level above the configured path * fixed fatal error that should be an exception when adding a filter/function/test too late * added a batch filter * added support for encoding an array as query string in the url_encode filter * 1.12.2 (2013-02-09) * fixed the timezone used by the date filter and function when the given date contains a timezone (like 2010-01-28T15:00:00+02:00) * fixed globals when getGlobals is called early on * added the first and last filter * 1.12.1 (2013-01-15) * added support for object instances as the second argument of the constant function * relaxed globals management to avoid a BC break * added support for {{ some_string[:2] }} * 1.12.0 (2013-01-08) * added verbatim as an alias for the raw tag to avoid confusion with the raw filter * fixed registration of tests and functions as anonymous functions * fixed globals management * 1.12.0-RC1 (2012-12-29) * added an include function (does the same as the include tag but in a more flexible way) * added the ability to use any PHP callable to define filters, functions, and tests * added a syntax error when using a loop variable that is not defined * added the ability to set default values for macro arguments * added support for named arguments for filters, tests, and functions * moved filters/functions/tests syntax errors to the parser * added support for extended ternary operator syntaxes * 1.11.1 (2012-11-11) * fixed debug info line numbering (was off by 2) * fixed escaping when calling a macro inside another one (regression introduced in 1.9.1) * optimized variable access on PHP 5.4 * fixed a crash of the C extension when an exception was thrown from a macro called without being imported (using _self.XXX) * 1.11.0 (2012-11-07) * fixed macro compilation when a variable name is a PHP reserved keyword * changed the date filter behavior to always apply the default timezone, except if false is passed as the timezone * fixed bitwise operator precedences * added the template_from_string function * fixed default timezone usage for the date function * optimized the way Twig exceptions are managed (to make them faster) * added Twig_ExistsLoaderInterface (implementing this interface in your loader make the chain loader much faster) * 1.10.3 (2012-10-19) * fixed wrong template location in some error messages * reverted a BC break introduced in 1.10.2 * added a split filter * 1.10.2 (2012-10-15) * fixed macro calls on PHP 5.4 * 1.10.1 (2012-10-15) * made a speed optimization to macro calls when imported via the "import" tag * fixed C extension compilation on Windows * fixed a segfault in the C extension when using DateTime objects * 1.10.0 (2012-09-28) * extracted functional tests framework to make it reusable for third-party extensions * added namespaced templates support in Twig_Loader_Filesystem * added Twig_Loader_Filesystem::prependPath() * fixed an error when a token parser pass a closure as a test to the subparse() method * 1.9.2 (2012-08-25) * fixed the in operator for objects that contain circular references * fixed the C extension when accessing a public property of an object implementing the \ArrayAccess interface * 1.9.1 (2012-07-22) * optimized macro calls when auto-escaping is on * fixed wrong parent class for Twig_Function_Node * made Twig_Loader_Chain more explicit about problems * 1.9.0 (2012-07-13) * made the parsing independent of the template loaders * fixed exception trace when an error occurs when rendering a child template * added escaping strategies for CSS, URL, and HTML attributes * fixed nested embed tag calls * added the date_modify filter * 1.8.3 (2012-06-17) * fixed paths in the filesystem loader when passing a path that ends with a slash or a backslash * fixed escaping when a project defines a function named html or js * fixed chmod mode to apply the umask correctly * 1.8.2 (2012-05-30) * added the abs filter * fixed a regression when using a number in template attributes * fixed compiler when mbstring.func_overload is set to 2 * fixed DateTimeZone support in date filter * 1.8.1 (2012-05-17) * fixed a regression when dealing with SimpleXMLElement instances in templates * fixed "is_safe" value for the "dump" function when "html_errors" is not defined in php.ini * switched to use mbstring whenever possible instead of iconv (you might need to update your encoding as mbstring and iconv encoding names sometimes differ) * 1.8.0 (2012-05-08) * enforced interface when adding tests, filters, functions, and node visitors from extensions * fixed a side-effect of the date filter where the timezone might be changed * simplified usage of the autoescape tag; the only (optional) argument is now the escaping strategy or false (with a BC layer) * added a way to dynamically change the auto-escaping strategy according to the template "filename" * changed the autoescape option to also accept a supported escaping strategy (for BC, true is equivalent to html) * added an embed tag * 1.7.0 (2012-04-24) * fixed a PHP warning when using CIFS * fixed template line number in some exceptions * added an iterable test * added an error when defining two blocks with the same name in a template * added the preserves_safety option for filters * fixed a PHP notice when trying to access a key on a non-object/array variable * enhanced error reporting when the template file is an instance of SplFileInfo * added Twig_Environment::mergeGlobals() * added compilation checks to avoid misuses of the sandbox tag * fixed filesystem loader freshness logic for high traffic websites * fixed random function when charset is null * 1.6.5 (2012-04-11) * fixed a regression when a template only extends another one without defining any blocks * 1.6.4 (2012-04-02) * fixed PHP notice in Twig_Error::guessTemplateLine() introduced in 1.6.3 * fixed performance when compiling large files * optimized parent template creation when the template does not use dynamic inheritance * 1.6.3 (2012-03-22) * fixed usage of Z_ADDREF_P for PHP 5.2 in the C extension * fixed compilation of numeric values used in templates when using a locale where the decimal separator is not a dot * made the strategy used to guess the real template file name and line number in exception messages much faster and more accurate * 1.6.2 (2012-03-18) * fixed sandbox mode when used with inheritance * added preserveKeys support for the slice filter * fixed the date filter when a DateTime instance is passed with a specific timezone * added a trim filter * 1.6.1 (2012-02-29) * fixed Twig C extension * removed the creation of Twig_Markup instances when not needed * added a way to set the default global timezone for dates * fixed the slice filter on strings when the length is not specified * fixed the creation of the cache directory in case of a race condition * 1.6.0 (2012-02-04) * fixed raw blocks when used with the whitespace trim option * made a speed optimization to macro calls when imported via the "from" tag * fixed globals, parsers, visitors, filters, tests, and functions management in Twig_Environment when a new one or new extension is added * fixed the attribute function when passing arguments * added slice notation support for the [] operator (syntactic sugar for the slice operator) * added a slice filter * added string support for the reverse filter * fixed the empty test and the length filter for Twig_Markup instances * added a date function to ease date comparison * fixed unary operators precedence * added recursive parsing support in the parser * added string and integer handling for the random function * 1.5.1 (2012-01-05) * fixed a regression when parsing strings * 1.5.0 (2012-01-04) * added Traversable objects support for the join filter * 1.5.0-RC2 (2011-12-30) * added a way to set the default global date interval format * fixed the date filter for DateInterval instances (setTimezone() does not exist for them) * refactored Twig_Template::display() to ease its extension * added a number_format filter * 1.5.0-RC1 (2011-12-26) * removed the need to quote hash keys * allowed hash keys to be any expression * added a do tag * added a flush tag * added support for dynamically named filters and functions * added a dump function to help debugging templates * added a nl2br filter * added a random function * added a way to change the default format for the date filter * fixed the lexer when an operator ending with a letter ends a line * added string interpolation support * enhanced exceptions for unknown filters, functions, tests, and tags * 1.4.0 (2011-12-07) * fixed lexer when using big numbers (> PHP_INT_MAX) * added missing preserveKeys argument to the reverse filter * fixed macros containing filter tag calls * 1.4.0-RC2 (2011-11-27) * removed usage of Reflection in Twig_Template::getAttribute() * added a C extension that can optionally replace Twig_Template::getAttribute() * added negative timestamp support to the date filter * 1.4.0-RC1 (2011-11-20) * optimized variable access when using PHP 5.4 * changed the precedence of the .. operator to be more consistent with languages that implements such a feature like Ruby * added an Exception to Twig_Loader_Array::isFresh() method when the template does not exist to be consistent with other loaders * added Twig_Function_Node to allow more complex functions to have their own Node class * added Twig_Filter_Node to allow more complex filters to have their own Node class * added Twig_Test_Node to allow more complex tests to have their own Node class * added a better error message when a template is empty but contain a BOM * fixed "in" operator for empty strings * fixed the "defined" test and the "default" filter (now works with more than one call (foo.bar.foo) and for both values of the strict_variables option) * changed the way extensions are loaded (addFilter/addFunction/addGlobal/addTest/addNodeVisitor/addTokenParser/addExtension can now be called in any order) * added Twig_Environment::display() * made the escape filter smarter when the encoding is not supported by PHP * added a convert_encoding filter * moved all node manipulations outside the compile() Node method * made several speed optimizations * 1.3.0 (2011-10-08) no changes * 1.3.0-RC1 (2011-10-04) * added an optimization for the parent() function * added cache reloading when auto_reload is true and an extension has been modified * added the possibility to force the escaping of a string already marked as safe (instance of Twig_Markup) * allowed empty templates to be used as traits * added traits support for the "parent" function * 1.2.0 (2011-09-13) no changes * 1.2.0-RC1 (2011-09-10) * enhanced the exception when a tag remains unclosed * added support for empty Countable objects for the "empty" test * fixed algorithm that determines if a template using inheritance is valid (no output between block definitions) * added better support for encoding problems when escaping a string (available as of PHP 5.4) * added a way to ignore a missing template when using the "include" tag ({% include "foo" ignore missing %}) * added support for an array of templates to the "include" and "extends" tags ({% include ['foo', 'bar'] %}) * added support for bitwise operators in expressions * added the "attribute" function to allow getting dynamic attributes on variables * added Twig_Loader_Chain * added Twig_Loader_Array::setTemplate() * added an optimization for the set tag when used to capture a large chunk of static text * changed name regex to match PHP one "[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*" (works for blocks, tags, functions, filters, and macros) * removed the possibility to use the "extends" tag from a block * added "if" modifier support to "for" loops * 1.1.2 (2011-07-30) * fixed json_encode filter on PHP 5.2 * fixed regression introduced in 1.1.1 ({{ block(foo|lower) }}) * fixed inheritance when using conditional parents * fixed compilation of templates when the body of a child template is not empty * fixed output when a macro throws an exception * fixed a parsing problem when a large chunk of text is enclosed in a comment tag * added PHPDoc for all Token parsers and Core extension functions * 1.1.1 (2011-07-17) * added a performance optimization in the Optimizer (also helps to lower the number of nested level calls) * made some performance improvement for some edge cases * 1.1.0 (2011-06-28) * fixed json_encode filter * 1.1.0-RC3 (2011-06-24) * fixed method case-sensitivity when using the sandbox mode * added timezone support for the date filter * fixed possible security problems with NUL bytes * 1.1.0-RC2 (2011-06-16) * added an exception when the template passed to "use" is not a string * made 'a.b is defined' not throw an exception if a is not defined (in strict mode) * added {% line \d+ %} directive * 1.1.0-RC1 (2011-05-28) Flush your cache after upgrading. * fixed date filter when using a timestamp * fixed the defined test for some cases * fixed a parsing problem when a large chunk of text is enclosed in a raw tag * added support for horizontal reuse of template blocks (see docs for more information) * added whitespace control modifier to all tags (see docs for more information) * added null as an alias for none (the null test is also an alias for the none test now) * made TRUE, FALSE, NONE equivalent to their lowercase counterparts * wrapped all compilation and runtime exceptions with Twig_Error_Runtime and added logic to guess the template name and line * moved display() method to Twig_Template (generated templates should now use doDisplay() instead) * 1.0.0 (2011-03-27) * fixed output when using mbstring * fixed duplicate call of methods when using the sandbox * made the charset configurable for the escape filter * 1.0.0-RC2 (2011-02-21) * changed the way {% set %} works when capturing (the content is now marked as safe) * added support for macro name in the endmacro tag * make Twig_Error compatible with PHP 5.3.0 > * fixed an infinite loop on some Windows configurations * fixed the "length" filter for numbers * fixed Template::getAttribute() as properties in PHP are case sensitive * removed coupling between Twig_Node and Twig_Template * fixed the ternary operator precedence rule * 1.0.0-RC1 (2011-01-09) Backward incompatibilities: * the "items" filter, which has been deprecated for quite a long time now, has been removed * the "range" filter has been converted to a function: 0|range(10) -> range(0, 10) * the "constant" filter has been converted to a function: {{ some_date|date('DATE_W3C'|constant) }} -> {{ some_date|date(constant('DATE_W3C')) }} * the "cycle" filter has been converted to a function: {{ ['odd', 'even']|cycle(i) }} -> {{ cycle(['odd', 'even'], i) }} * the "for" tag does not support "joined by" anymore * the "autoescape" first argument is now "true"/"false" (instead of "on"/"off") * the "parent" tag has been replaced by a "parent" function ({{ parent() }} instead of {% parent %}) * the "display" tag has been replaced by a "block" function ({{ block('title') }} instead of {% display title %}) * removed the grammar and simple token parser (moved to the Twig Extensions repository) Changes: * added "needs_context" option for filters and functions (the context is then passed as a first argument) * added global variables support * made macros return their value instead of echoing directly (fixes calling a macro in sandbox mode) * added the "from" tag to import macros as functions * added support for functions (a function is just syntactic sugar for a getAttribute() call) * made macros callable when sandbox mode is enabled * added an exception when a macro uses a reserved name * the "default" filter now uses the "empty" test instead of just checking for null * added the "empty" test * 0.9.10 (2010-12-16) Backward incompatibilities: * The Escaper extension is enabled by default, which means that all displayed variables are now automatically escaped. You can revert to the previous behavior by removing the extension via $env->removeExtension('escaper') or just set the 'autoescape' option to 'false'. * removed the "without loop" attribute for the "for" tag (not needed anymore as the Optimizer take care of that for most cases) * arrays and hashes have now a different syntax * arrays keep the same syntax with square brackets: [1, 2] * hashes now use curly braces (["a": "b"] should now be written as {"a": "b"}) * support for "arrays with keys" and "hashes without keys" is not supported anymore ([1, "foo": "bar"] or {"foo": "bar", 1}) * the i18n extension is now part of the Twig Extensions repository Changes: * added the merge filter * removed 'is_escaper' option for filters (a left over from the previous version) -- you must use 'is_safe' now instead * fixed usage of operators as method names (like is, in, and not) * changed the order of execution for node visitors * fixed default() filter behavior when used with strict_variables set to on * fixed filesystem loader compatibility with PHAR files * enhanced error messages when an unexpected token is parsed in an expression * fixed filename not being added to syntax error messages * added the autoescape option to enable/disable autoescaping * removed the newline after a comment (mimics PHP behavior) * added a syntax error exception when parent block is used on a template that does not extend another one * made the Escaper extension enabled by default * fixed sandbox extension when used with auto output escaping * fixed escaper when wrapping a Twig_Node_Print (the original class must be preserved) * added an Optimizer extension (enabled by default; optimizes "for" loops and "raw" filters) * added priority to node visitors * 0.9.9 (2010-11-28) Backward incompatibilities: * the self special variable has been renamed to _self * the odd and even filters are now tests: {{ foo|odd }} must now be written {{ foo is odd }} * the "safe" filter has been renamed to "raw" * in Node classes, sub-nodes are now accessed via getNode() (instead of property access) attributes via getAttribute() (instead of array access) * the urlencode filter had been renamed to url_encode * the include tag now merges the passed variables with the current context by default (the old behavior is still possible by adding the "only" keyword) * moved Exceptions to Twig_Error_* (Twig_SyntaxError/Twig_RuntimeError are now Twig_Error_Syntax/Twig_Error_Runtime) * removed support for {{ 1 < i < 3 }} (use {{ i > 1 and i < 3 }} instead) * the "in" filter has been removed ({{ a|in(b) }} should now be written {{ a in b }}) Changes: * added file and line to Twig_Error_Runtime exceptions thrown from Twig_Template * changed trans tag to accept any variable for the plural count * fixed sandbox mode (__toString() method check was not enforced if called implicitly from complex statements) * added the ** (power) operator * changed the algorithm used for parsing expressions * added the spaceless tag * removed trim_blocks option * added support for is*() methods for attributes (foo.bar now looks for foo->getBar() or foo->isBar()) * changed all exceptions to extend Twig_Error * fixed unary expressions ({{ not(1 or 0) }}) * fixed child templates (with an extend tag) that uses one or more imports * added support for {{ 1 not in [2, 3] }} (more readable than the current {{ not (1 in [2, 3]) }}) * escaping has been rewritten * the implementation of template inheritance has been rewritten (blocks can now be called individually and still work with inheritance) * fixed error handling for if tag when a syntax error occurs within a subparse process * added a way to implement custom logic for resolving token parsers given a tag name * fixed js escaper to be stricter (now uses a whilelist-based js escaper) * added the following filers: "constant", "trans", "replace", "json_encode" * added a "constant" test * fixed objects with __toString() not being autoescaped * fixed subscript expressions when calling __call() (methods now keep the case) * added "test" feature (accessible via the "is" operator) * removed the debug tag (should be done in an extension) * fixed trans tag when no vars are used in plural form * fixed race condition when writing template cache * added the special _charset variable to reference the current charset * added the special _context variable to reference the current context * renamed self to _self (to avoid conflict) * fixed Twig_Template::getAttribute() for protected properties * 0.9.8 (2010-06-28) Backward incompatibilities: * the trans tag plural count is now attached to the plural tag: old: `{% trans count %}...{% plural %}...{% endtrans %}` new: `{% trans %}...{% plural count %}...{% endtrans %}` * added a way to translate strings coming from a variable ({% trans var %}) * fixed trans tag when used with the Escaper extension * fixed default cache umask * removed Twig_Template instances from the debug tag output * fixed objects with __isset() defined * fixed set tag when used with a capture * fixed type hinting for Twig_Environment::addFilter() method * 0.9.7 (2010-06-12) Backward incompatibilities: * changed 'as' to '=' for the set tag ({% set title as "Title" %} must now be {% set title = "Title" %}) * removed the sandboxed attribute of the include tag (use the new sandbox tag instead) * refactored the Node system (if you have custom nodes, you will have to update them to use the new API) * added self as a special variable that refers to the current template (useful for importing macros from the current template) * added Twig_Template instance support to the include tag * added support for dynamic and conditional inheritance ({% extends some_var %} and {% extends standalone ? "minimum" : "base" %}) * added a grammar sub-framework to ease the creation of custom tags * fixed the for tag for large arrays (some loop variables are now only available for arrays and objects that implement the Countable interface) * removed the Twig_Resource::resolveMissingFilter() method * fixed the filter tag which did not apply filtering to included files * added a bunch of unit tests * added a bunch of phpdoc * added a sandbox tag in the sandbox extension * changed the date filter to support any date format supported by DateTime * added strict_variable setting to throw an exception when an invalid variable is used in a template (disabled by default) * added the lexer, parser, and compiler as arguments to the Twig_Environment constructor * changed the cache option to only accepts an explicit path to a cache directory or false * added a way to add token parsers, filters, and visitors without creating an extension * added three interfaces: Twig_NodeInterface, Twig_TokenParserInterface, and Twig_FilterInterface * changed the generated code to match the new coding standards * fixed sandbox mode (__toString() method check was not enforced if called implicitly from a simple statement like {{ article }}) * added an exception when a child template has a non-empty body (as it is always ignored when rendering) * 0.9.6 (2010-05-12) * fixed variables defined outside a loop and for which the value changes in a for loop * fixed the test suite for PHP 5.2 and older versions of PHPUnit * added support for __call() in expression resolution * fixed node visiting for macros (macros are now visited by visitors as any other node) * fixed nested block definitions with a parent call (rarely useful but nonetheless supported now) * added the cycle filter * fixed the Lexer when mbstring.func_overload is used with an mbstring.internal_encoding different from ASCII * added a long-syntax for the set tag ({% set foo %}...{% endset %}) * unit tests are now powered by PHPUnit * added support for gettext via the `i18n` extension * fixed twig_capitalize_string_filter() and fixed twig_length_filter() when used with UTF-8 values * added a more useful exception if an if tag is not closed properly * added support for escaping strategy in the autoescape tag * fixed lexer when a template has a big chunk of text between/in a block * 0.9.5 (2010-01-20) As for any new release, don't forget to remove all cached templates after upgrading. If you have defined custom filters, you MUST upgrade them for this release. To upgrade, replace "array" with "new Twig_Filter_Function", and replace the environment constant by the "needs_environment" option: // before 'even' => array('twig_is_even_filter', false), 'escape' => array('twig_escape_filter', true), // after 'even' => new Twig_Filter_Function('twig_is_even_filter'), 'escape' => new Twig_Filter_Function('twig_escape_filter', array('needs_environment' => true)), If you have created NodeTransformer classes, you will need to upgrade them to the new interface (please note that the interface is not yet considered stable). * fixed list nodes that did not extend the Twig_NodeListInterface * added the "without loop" option to the for tag (it disables the generation of the loop variable) * refactored node transformers to node visitors * fixed automatic-escaping for blocks * added a way to specify variables to pass to an included template * changed the automatic-escaping rules to be more sensible and more configurable in custom filters (the documentation lists all the rules) * improved the filter system to allow object methods to be used as filters * changed the Array and String loaders to actually make use of the cache mechanism * included the default filter function definitions in the extension class files directly (Core, Escaper) * added the // operator (like the floor() PHP function) * added the .. operator (as a syntactic sugar for the range filter when the step is 1) * added the in operator (as a syntactic sugar for the in filter) * added the following filters in the Core extension: in, range * added support for arrays (same behavior as in PHP, a mix between lists and dictionaries, arrays and hashes) * enhanced some error messages to provide better feedback in case of parsing errors * 0.9.4 (2009-12-02) If you have custom loaders, you MUST upgrade them for this release: The Twig_Loader base class has been removed, and the Twig_LoaderInterface has also been changed (see the source code for more information or the documentation). * added support for DateTime instances for the date filter * fixed loop.last when the array only has one item * made it possible to insert newlines in tag and variable blocks * fixed a bug when a literal '\n' were present in a template text * fixed bug when the filename of a template contains */ * refactored loaders * 0.9.3 (2009-11-11) This release is NOT backward compatible with the previous releases. The loaders do not take the cache and autoReload arguments anymore. Instead, the Twig_Environment class has two new options: cache and auto_reload. Upgrading your code means changing this kind of code: $loader = new Twig_Loader_Filesystem('/path/to/templates', '/path/to/compilation_cache', true); $twig = new Twig_Environment($loader); to something like this: $loader = new Twig_Loader_Filesystem('/path/to/templates'); $twig = new Twig_Environment($loader, array( 'cache' => '/path/to/compilation_cache', 'auto_reload' => true, )); * deprecated the "items" filter as it is not needed anymore * made cache and auto_reload options of Twig_Environment instead of arguments of Twig_Loader * optimized template loading speed * removed output when an error occurs in a template and render() is used * made major speed improvements for loops (up to 300% on even the smallest loops) * added properties as part of the sandbox mode * added public properties support (obj.item can now be the item property on the obj object) * extended set tag to support expression as value ({% set foo as 'foo' ~ 'bar' %} ) * fixed bug when \ was used in HTML * 0.9.2 (2009-10-29) * made some speed optimizations * changed the cache extension to .php * added a js escaping strategy * added support for short block tag * changed the filter tag to allow chained filters * made lexer more flexible as you can now change the default delimiters * added set tag * changed default directory permission when cache dir does not exist (more secure) * added macro support * changed filters first optional argument to be a Twig_Environment instance instead of a Twig_Template instance * made Twig_Autoloader::autoload() a static method * avoid writing template file if an error occurs * added $ escaping when outputting raw strings * enhanced some error messages to ease debugging * fixed empty cache files when the template contains an error * 0.9.1 (2009-10-14) * fixed a bug in PHP 5.2.6 * fixed numbers with one than one decimal * added support for method calls with arguments ({{ foo.bar('a', 43) }}) * made small speed optimizations * made minor tweaks to allow better extensibility and flexibility * 0.9.0 (2009-10-12) * Initial release php-twig-2.12.5/LICENSE000066400000000000000000000027021362457344700143650ustar00rootroot00000000000000Copyright (c) 2009-2020 by the Twig Team. 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. php-twig-2.12.5/README.rst000066400000000000000000000014421362457344700150470ustar00rootroot00000000000000Twig, 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. Sponsors -------- .. raw:: html Blackfire.io More Information ---------------- Read the `documentation`_ for more information. .. _documentation: https://twig.symfony.com/documentation php-twig-2.12.5/composer.json000066400000000000000000000023761362457344700161110ustar00rootroot00000000000000{ "name": "twig/twig", "type": "library", "description": "Twig, the flexible, fast, and secure template language for PHP", "keywords": ["templating"], "homepage": "https://twig.symfony.com", "license": "BSD-3-Clause", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com", "homepage": "http://fabien.potencier.org", "role": "Lead Developer" }, { "name": "Twig Team", "role": "Contributors" }, { "name": "Armin Ronacher", "email": "armin.ronacher@active-4.com", "role": "Project Founder" } ], "require": { "php": "^7.0", "symfony/polyfill-mbstring": "^1.3", "symfony/polyfill-ctype": "^1.8" }, "require-dev": { "symfony/phpunit-bridge": "^4.4|^5.0", "psr/container": "^1.0" }, "autoload": { "psr-0" : { "Twig_" : "lib/" }, "psr-4" : { "Twig\\" : "src/" } }, "autoload-dev": { "psr-4" : { "Twig\\Tests\\" : "tests/" } }, "extra": { "branch-alias": { "dev-master": "2.12-dev" } } } php-twig-2.12.5/doc/000077500000000000000000000000001362457344700141245ustar00rootroot00000000000000php-twig-2.12.5/doc/advanced.rst000066400000000000000000000671231362457344700164340ustar00rootroot00000000000000Extending 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. 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:: twig {% 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:: twig {{ '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. Now, let's use a ``lipsum`` *filter*: .. code-block:: twig {{ 40|lipsum }} Again, it works. But a filter should transform the passed value to something else. 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:: twig {{ 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:: twig {{ 'some text' ~ lipsum(40) ~ 'some more text' }} {% set lipsum = lipsum(40) %} Lastly, you can also use a *global* object with a method able to generate lorem ipsum text: .. code-block:: twig {{ 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* simple frequent Content generation *global* simple frequent Helper object *function* simple frequent Content generation *filter* simple frequent Value transformation *tag* complex rare DSL language construct *test* simple rare Boolean decision *operator* simple 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:: twig {{ text.lipsum(40) }} Filters ------- Creating a filter consists of associating a name with a PHP callable:: // an anonymous function $filter = new \Twig\TwigFilter('rot13', function ($string) { return str_rot13($string); }); // or a simple PHP function $filter = new \Twig\TwigFilter('rot13', 'str_rot13'); // or a class static method $filter = new \Twig\TwigFilter('rot13', ['SomeClass', 'rot13Filter']); $filter = new \Twig\TwigFilter('rot13', 'SomeClass::rot13Filter'); // or a class method $filter = new \Twig\TwigFilter('rot13', [$this, 'rot13Filter']); // the one below needs a runtime implementation (see below for more information) $filter = new \Twig\TwigFilter('rot13', ['SomeClass', 'rot13Filter']); The first argument passed to the ``\Twig\TwigFilter`` 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 the Twig environment:: $twig = new \Twig\Environment($loader); $twig->addFilter($filter); And here is how to use it in a template: .. code-block:: twig {{ '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:: twig {{ 'TWIG'|lower }} {{ now|date('d/m/Y') }} is compiled to something like the following:: The ``\Twig\TwigFilter`` class takes an array of options as its last argument:: $filter = new \Twig\TwigFilter('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\TwigFilter('rot13', function (Twig_Environment $env, $string) { // get the current charset for instance $charset = $env->getCharset(); return str_rot13($string); }, ['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\TwigFilter('rot13', function ($context, $string) { // ... }, ['needs_context' => true]); $filter = new \Twig\TwigFilter('rot13', function (Twig_Environment $env, $context, $string) { // ... }, ['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\TwigFilter('nl2br', 'nl2br', ['is_safe' => ['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\TwigFilter('somefilter', 'somefilter', ['pre_escape' => 'html', 'is_safe' => ['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\TwigFilter('thumbnail', function ($file, array $options = []) { // ... }, ['is_variadic' => true]); Be warned that :ref:`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 and the ``*`` part will match any string:: $filter = new \Twig\TwigFilter('*_path', function ($name, $arguments) { // ... }); The following filters are matched by the above defined dynamic filter: * ``product_path`` * ``category_path`` A dynamic filter can define more than one dynamic parts:: $filter = new \Twig\TwigFilter('*_path_*', function ($name, $suffix, $arguments) { // ... }); The filter receives 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\TwigFilter('obsolete', function () { // ... }, ['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\TwigFunction``:: $twig = new \Twig\Environment($loader); $function = new \Twig\TwigFunction('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\TwigTest``:: $twig = new \Twig\Environment($loader); $test = new \Twig\TwigTest('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\TwigTest('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 must 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\TwigTest( 'odd', null, ['node_class' => \Twig\Node\Expression\Test\OddTest::class]); $twig->addTest($test); class Twig_Node_Expression_Test_Odd extends \Twig\Node\Expression\TestExpression { 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:: twig {% if my_value is odd %} The ``node`` sub-node will contain an expression of ``my_value``. Node-based tests also have access to the ``arguments`` node. This node will contain the various other arguments that have been provided to your test. .. versionadded:: 2.6 Dynamic tests support was added in Twig 2.6. If you want to pass a variable number of positional or named arguments to the test, set the ``is_variadic`` option to ``true``. Tests support dynamic names (see dynamic filters for the syntax). Tags ---- One of the most exciting features of a template engine like Twig is the possibility to define new **language constructs**. This is also the most complex feature as you need to understand how Twig's internals work. Most of the time though, a tag is not needed: * If your tag generates some output, use a **function** instead. * If your tag modifies some content and returns it, use a **filter** instead. For instance, if you want to create a tag that converts a Markdown formatted text to HTML, create a ``markdown`` filter instead: .. code-block:: twig {{ '**markdown** text'|markdown }} If you want use this filter on large amounts of text, wrap it with the :doc:`apply ` tag: .. code-block:: twig {% apply markdown %} Title ===== Much better than creating a tag as you can **compose** filters. {% endapply %} .. note:: The ``apply`` tag was introduced in Twig 2.9; use the ``filter`` tag with previous versions. * If your tag does not output anything, but only exists because of a side effect, create a **function** that returns nothing and call it via the :doc:`filter ` tag. For instance, if you want to create a tag that logs text, create a ``log`` function instead and call it via the :doc:`do ` tag: .. code-block:: twig {% do log('Log some things') %} If you still want to create a tag for a new language construct, great! Let's create a ``set`` tag that allows the definition of simple variables from within a template. The tag can be used like follows: .. code-block:: twig {% 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. 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 ~~~~~~~~~~~~~~~~~~~~~ Add a tag by 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\AbstractTokenParser { 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\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 quite short:: class Project_Set_Node extends \Twig\Node\Node { public function __construct($name, \Twig\Node\Expression\AbstractExpression $value, $line, $tag = null) { parent::__construct(['value' => $value], ['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\ForNode`` 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\BlockNode`` for a usage example). * ``outdent()``: Outdents the generated code (see ``\Twig\Node\BlockNode`` 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, 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). An extension is a class that implements the following interface:: interface \Twig\Extension\ExtensionInterface { /** * Returns the token parser instances to add to the existing list. * * @return \Twig\TokenParser\TokenParserInterface[] */ public function getTokenParsers(); /** * Returns the node visitor instances to add to the existing list. * * @return \Twig\NodeVisitor\NodeVisitorInterface[] */ public function getNodeVisitors(); /** * Returns a list of filters to add to the existing list. * * @return \Twig\TwigFilter[] */ public function getFilters(); /** * Returns a list of tests to add to the existing list. * * @return \Twig\TwigTest[] */ public function getTests(); /** * Returns a list of functions to add to the existing list. * * @return \Twig\TwigFunction[] */ public function getFunctions(); /** * Returns a list of operators to add to the existing list. * * @return array First array of unary operators, second array of binary operators */ public function getOperators(); } To keep your extension class clean and lean, inherit from the built-in ``\Twig\Extension\AbstractExtension`` class instead of implementing the interface as it provides empty implementations for all methods:: class Project_Twig_Extension extends \Twig\Extension\AbstractExtension { } This extension does nothing for now. We will customize it in the next sections. You can save your extension anywhere 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\AbstractExtension implements \Twig\Extension\GlobalsInterface { public function getGlobals() { return [ 'text' => new Text(), ]; } // ... } Functions ~~~~~~~~~ Functions can be registered in an extension via the ``getFunctions()`` method:: class Project_Twig_Extension extends \Twig\Extension\AbstractExtension { public function getFunctions() { return [ new \Twig\TwigFunction('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\AbstractExtension { public function getFilters() { return [ new \Twig\TwigFilter('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\AbstractExtension { public function getTokenParsers() { return [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 the ``!``, ``||``, and ``&&`` operators:: class Project_Twig_Extension extends \Twig\Extension\AbstractExtension { public function getOperators() { return [ [ '!' => ['precedence' => 50, 'class' => \Twig\Node\Expression\Unary\NotUnary::class], ], [ '||' => ['precedence' => 10, 'class' => \Twig\Node\Expression\Binary\OrBinary::class, 'associativity' => \Twig\ExpressionParser::OPERATOR_LEFT], '&&' => ['precedence' => 15, 'class' => \Twig\Node\Expression\Binary\AndBinary::class, 'associativity' => \Twig\ExpressionParser::OPERATOR_LEFT], ], ]; } // ... } Tests ~~~~~ The ``getTests()`` method lets you add new test functions:: class Project_Twig_Extension extends \Twig\Extension\AbstractExtension { public function getTests() { return [ new \Twig\TwigTest('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\AbstractExtension { private $rot13Provider; public function __construct($rot13Provider) { $this->rot13Provider = $rot13Provider; } public function getFunctions() { return [ new \Twig\TwigFunction('rot13', [$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 decouple the extension definitions from their runtime implementations by registering a ``\Twig\RuntimeLoader\RuntimeLoaderInterface`` instance on the environment that knows how to instantiate such runtime classes (runtime classes must be autoload-able):: class RuntimeLoader implements \Twig\RuntimeLoader\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\RuntimeLoader\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\AbstractExtension { public function getFunctions() { return [ new \Twig\TwigFunction('rot13', ['Project_Twig_RuntimeExtension', 'rot13']), // or new \Twig\TwigFunction('rot13', 'Project_Twig_RuntimeExtension::rot13'), ]; } } Testing an Extension -------------------- Functional Tests ~~~~~~~~~~~~~~~~ You can create functional tests for extensions 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 [ new Project_Twig_Extension1(), new Project_Twig_Extension2(), ]; } public function getFixturesDir() { return __DIR__.'/Fixtures/'; } } Fixtures examples can be found within the Twig repository `tests/Twig/Fixtures`_ directory. Node Tests ~~~~~~~~~~ Testing the node visitors can be complex, so extend your test cases from ``\Twig\Test\NodeTestCase``. Examples can be found in the Twig repository `tests/Twig/Node`_ directory. .. _`rot13`: https://secure.php.net/manual/en/function.str-rot13.php .. _`tests/Twig/Fixtures`: https://github.com/twigphp/Twig/tree/2.x/tests/Fixtures .. _`tests/Twig/Node`: https://github.com/twigphp/Twig/tree/2.x/tests/Node php-twig-2.12.5/doc/api.rst000066400000000000000000000476721362457344700154470ustar00rootroot00000000000000Twig 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. Most applications create one ``\Twig\Environment`` object on application initialization and use that to load templates. In some cases, it might be useful to have multiple environments side by side, with different configurations. The typical way to configure Twig to load templates for an application looks roughly like this:: require_once '/path/to/vendor/autoload.php'; $loader = new \Twig\Loader\FilesystemLoader('/path/to/templates'); $twig = new \Twig\Environment($loader, [ 'cache' => '/path/to/compilation_cache', ]); This creates a template environment with a default configuration and a loader that looks up templates in the ``/path/to/templates/`` directory. 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(['the' => 'variables', 'go' => 'here']); .. note:: The ``display()`` method is a shortcut to output the rendered template. You can also load and render the template in one fell swoop:: echo $twig->render('index.html', ['the' => 'variables', 'go' => 'here']); If a template defines blocks, they can be rendered individually via the ``renderBlock()`` call:: echo $template->renderBlock('block_name', ['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, ['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 OPCache. 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\Loader\FilesystemLoader`` ................................. ``\Twig\Loader\FilesystemLoader`` 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\FilesystemLoader($templateDir); It can also look for templates in an array of directories:: $loader = new \Twig\Loader\FilesystemLoader([$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', []); ``\Twig\Loader\FilesystemLoader`` 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\FilesystemLoader('templates', getcwd().'/..'); .. note:: When not passing the root path as a second argument, Twig uses ``getcwd()`` for relative paths. ``\Twig\Loader\ArrayLoader`` ............................ ``\Twig\Loader\ArrayLoader`` loads a template from a PHP array. It is passed an array of strings bound to template names:: $loader = new \Twig\Loader\ArrayLoader([ 'index.html' => 'Hello {{ name }}!', ]); $twig = new \Twig\Environment($loader); echo $twig->render('index.html', ['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\ChainLoader`` ............................ ``\Twig\Loader\ChainLoader`` delegates the loading of templates to other loaders:: $loader1 = new \Twig\Loader\ArrayLoader([ 'base.html' => '{% block content %}{% endblock %}', ]); $loader2 = new \Twig\Loader\ArrayLoader([ 'index.html' => '{% extends "base.html" %}{% block content %}Hello {{ name }}{% endblock %}', 'base.html' => 'Will never be loaded', ]); $loader = new \Twig\Loader\ChainLoader([$loader1, $loader2]); $twig = new \Twig\Environment($loader); When looking for a template, Twig tries each loader in turn and returns 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``. .. note:: You can also add loaders via the ``addLoader()`` method. Create your own Loader ~~~~~~~~~~~~~~~~~~~~~~ All loaders implement the ``\Twig\Loader\LoaderInterface``:: interface \Twig\Loader\LoaderInterface { /** * Returns the source context for a given template logical name. * * @param string $name The template logical name * * @return \Twig\Source * * @throws \Twig\Error\LoaderError 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\LoaderError When $name is not found */ public function getCacheKey($name); /** * Returns true if the template is still fresh. * * @param string $name The template name * @param timestamp $time The last modification time of the cached template * * @return bool true if the template is fresh, false otherwise * * @throws \Twig\Error\LoaderError 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. Register an extension via the ``addExtension()`` method:: $twig->addExtension(new \Twig\Extension\SandboxExtension()); Twig comes bundled with the following extensions: * *Twig\Extension\CoreExtension*: Defines all the core features of Twig. * *Twig\Extension\DebugExtension*: Defines the ``dump`` function to help debug template variables. * *Twig\Extension\EscaperExtension*: Adds automatic output-escaping and the possibility to escape/unescape blocks of code. * *Twig\Extension\SandboxExtension*: Adds a sandbox mode to the default Twig environment, making it safe to evaluate untrusted code. * *Twig\Extension\ProfilerExtension*: Enabled the built-in Twig profiler. * *Twig\Extension\OptimizerExtension*: Optimizes the node tree before compilation. * *Twig\Extension\StringLoaderExtension*: Defined the ``template_from_string`` function to allow loading templates from string in a template. The Core, Escaper, and Optimizer extensions are registered by default. Built-in Extensions ------------------- This section describes the features added by the built-in extensions. .. tip:: Read the chapter about :doc:`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\EscaperExtension('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:: twig {{ article.to_html|raw }} You can also change the escaping mode locally by using the ``autoescape`` tag: .. code-block:: twig {% 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:: twig {{ "Twig
" }} {# won't be escaped #} {% set text = "Twig
" %} {{ text }} {# will be escaped #} * Expressions which the result is a literal or a variable marked safe are never automatically escaped: .. code-block:: twig {{ foo ? "Twig
" : "
Twig" }} {# won't be escaped #} {% set text = "Twig
" %} {{ true ? text : "
Twig" }} {# will be escaped #} {{ false ? text : "
Twig" }} {# won't be escaped #} {% set text = "Twig
" %} {{ foo ? text|raw : "
Twig" }} {# won't be escaped #} * Objects with a ``__toString`` method are converted to strings and escaped. You can mark some classes and/or interfaces as being safe for some strategies via ``EscaperExtension::addSafeClass()``: .. code-block:: twig // mark object of class Foo as safe for the HTML strategy $escaper->addSafeClass('Foo', ['html']); // mark object of interface Foo as safe for the HTML strategy $escaper->addSafeClass('FooInterface', ['html']); // mark object of class Foo as safe for the HTML and JS strategies $escaper->addSafeClass('Foo', ['html', 'js']); // mark object of class Foo as safe for all strategies $escaper->addSafeClass('Foo', ['all']); * Escaping is applied before printing, after any other filter is applied: .. code-block:: twig {{ var|upper }} {# is equivalent to {{ var|upper|escape }} #} * The `raw` filter should only be used at the end of the filter chain: .. code-block:: twig {{ 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:: twig {% 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 = ['if']; $filters = ['upper']; $methods = [ 'Article' => ['getTitle', 'getBody'], ]; $properties = [ 'Article' => ['title', 'body'], ]; $functions = ['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\SandboxExtension($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:: twig {% 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\SandboxExtension($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\ProfilerExtension($profile)); $dumper = new \Twig\Profiler\Dumper\TextDumper(); 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\BlackfireDumper(); 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\OptimizerExtension()); 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\OptimizerExtension(\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR); $twig->addExtension($optimizer); Twig supports the following optimizations: * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_ALL``, enables all optimizations (this is the default value). * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_NONE``, disables all optimizations. This reduces the compilation time, but it can increase the execution time and the consumed memory. * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_FOR``, optimizes the ``for`` tag by removing the ``loop`` variable creation whenever possible. * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_RAW_FILTER``, removes the ``raw`` filter whenever possible. * ``\Twig\NodeVisitor\OptimizerNodeVisitor::OPTIMIZE_VAR_ACCESS``, simplifies the creation and access of variables in the compiled templates whenever possible. Exceptions ---------- Twig can throw exceptions: * ``\Twig\Error\Error``: The base exception for all errors. * ``\Twig\Error\SyntaxError``: Thrown to tell the user that there is a problem with the template syntax. * ``\Twig\Error\RuntimeError``: Thrown when an error occurs at runtime (when a filter does not exist for instance). * ``\Twig\Error\LoaderError``: 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. php-twig-2.12.5/doc/coding_standards.rst000066400000000000000000000045061362457344700201710ustar00rootroot00000000000000Coding 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:: twig {{ foo }} {# comment #} {% if foo %}{% endif %} When using the whitespace control character, do not put any spaces between it and the delimiter: .. code-block:: twig {{- 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:: twig {{ 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:: twig {{ [1, 2, 3] }} {{ {'foo': 'bar'} }} * Do not put any spaces after an opening parenthesis and before a closing parenthesis in expressions: .. code-block:: twig {{ 1 + (2 * 3) }} * Do not put any spaces before and after string delimiters: .. code-block:: twig {{ 'foo' }} {{ "foo" }} * Do not put any spaces before and after the following operators: ``|``, ``.``, ``..``, ``[]``: .. code-block:: twig {{ 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:: twig {{ 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:: twig {{ [1, 2, 3] }} {{ {'foo': 'bar'} }} * Use lower cased and underscored variable names: .. code-block:: twig {% 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:: twig {% block foo %} {% if true %} true {% endif %} {% endblock %} php-twig-2.12.5/doc/deprecated.rst000066400000000000000000000101161362457344700167550ustar00rootroot00000000000000Deprecated 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). PSR-0 ----- * PSR-0 classes are deprecated in favor of namespaced ones since Twig 2.7. Inheritance ----------- * Defining a "block" definition in a non-capturing block in a child template is deprecated since Twig 2.5.0. In Twig 3.0, it will throw a ``Twig\Error\SyntaxError`` exception. It does not work anyway, so most projects won't need to do anything to upgrade. Errors ------ * Passing a string as the ``$source`` argument on ``\Twig\Error\Error`` / ``Twig\Error\Error`` constructor is deprecated since Twig 2.6.1. Pass an instance of ``Twig\Source`` instead. Tags ---- * The ``spaceless`` tag is deprecated in Twig 2.7. Use the ``spaceless`` filter instead or ``{% apply spaceless %}`` (the ``Twig\Node\SpacelessNode`` and ``Twig\TokenParser\SpacelessTokenParser`` classes are also deprecated). * Using the ``spaceless`` tag at the root level of a child template is deprecated in Twig 2.5.0. This does not work as one would expect it to work anyway. In Twig 3.0, it will throw a ``Twig\Error\SyntaxError`` exception. * The ``filter`` tag is deprecated in Twig 2.9. Use the ``apply`` tag instead (the ``Twig\TokenParser\FilterTokenParser`` classes is also deprecated). * Adding an ``if`` condition on a ``for`` tag is deprecated in Twig 2.10. Use a ``filter`` filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop) Final Classes ------------- The following classes are marked as ``@final`` in Twig 2 and will be final in 3.0: * ``Twig\Node\ModuleNode`` * ``Twig\TwigFilter`` * ``Twig\TwigFunction`` * ``Twig\TwigTest`` * ``Twig\Profiler\Profile`` Parser ------ * As of Twig 2.7, the ``\Twig\Parser::isReservedMacroName()`` / ``Twig\Parser`` function is deprecated and will be removed in Twig 3.0. It always returns ``false`` anyway as Twig 2 does not have any reserved macro names. Environment ----------- * As of Twig 2.7, the ``base_template_class`` option on ``Twig\Environment`` is deprecated and will be removed in Twig 3.0. * As of Twig 2.7, the ``Twig\Environment::getBaseTemplateClass()`` and ``Twig\Environment::setBaseTemplateClass()`` methods are deprecated and will be removed in Twig 3.0. * As of Twig 2.7, the ``Twig\Environment::getTemplateClass()`` is marked as being internal and should not be used. * As of Twig 2.7, passing a ``Twig\Template`` instance to the ``Twig\Environment::load()`` and ``Twig\Environment::resolveTemplate()`` is deprecated. * Depending on the input, ``Twig\Environment::resolveTemplate()`` can return a ``Twig\Template`` or a ``Twig\TemplateWrapper`` instance. In Twig 3.0, this method will **always** return a ``Twig\TemplateWrapper`` instance. You should only rely on the methods of this class if you want to be forward-compatible. Interfaces ---------- * As of Twig 2.7, the empty ``Twig\Loader\ExistsLoaderInterface`` interface is deprecated and will be removed in Twig 3.0. * As of Twig 2.7, the ``Twig\Extension\InitRuntimeInterface`` interface is deprecated and will be removed in Twig 3.0. Extensions ---------- * As of Twig 2.11, the ``Twig\Extension\CoreExtension::setEscaper()`` and ``Twig\Extension\CoreExtension::getEscapers()`` are deprecated. Use the same methods on ``Twig\Extension\EscaperExtension`` instead. Miscellaneous ------------- * As of Twig 2.7, the ``Twig_SimpleFilter``, ``Twig_SimpleFunction``, and ``Twig_SimpleTest`` empty classes are deprecated and will be removed in Twig 3.0. Use ``Twig\TwigFilter``, ``Twig\TwigFunction``, and ``Twig\TwigTest`` respectively. * As of Twig 2.8.2, all usage of ``Twig\Loader\FilesystemLoader::findTemplate()`` check for a ``null`` return value (same meaning as returning ``false``). If you are overidding ``Twig\Loader\FilesystemLoader::findTemplate()``, you must return ``null`` instead of ``false`` to be compatible with Twig 3.0. php-twig-2.12.5/doc/filters/000077500000000000000000000000001362457344700155745ustar00rootroot00000000000000php-twig-2.12.5/doc/filters/abs.rst000066400000000000000000000003761362457344700171010ustar00rootroot00000000000000``abs`` ======= The ``abs`` filter returns the absolute value. .. code-block:: twig {# number = -5 #} {{ number|abs }} {# outputs 5 #} .. note:: Internally, Twig uses the PHP `abs`_ function. .. _`abs`: https://secure.php.net/abs php-twig-2.12.5/doc/filters/batch.rst000066400000000000000000000020501362457344700174040ustar00rootroot00000000000000``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:: twig {% 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:: twig
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 * ``preserve_keys``: Whether to preserve keys or not php-twig-2.12.5/doc/filters/capitalize.rst000066400000000000000000000003501362457344700204510ustar00rootroot00000000000000``capitalize`` ============== The ``capitalize`` filter capitalizes a value. The first character will be uppercase, all others lowercase: .. code-block:: twig {{ 'my first car'|capitalize }} {# outputs 'My first car' #} php-twig-2.12.5/doc/filters/column.rst000066400000000000000000000010531362457344700176220ustar00rootroot00000000000000``column`` ========== .. versionadded:: 2.8 The ``column`` filter was added in Twig 2.8. The ``column`` filter returns the values from a single column in the input array. .. code-block:: twig {% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %} {% set fruits = items|column('fruit') %} {# fruits now contains ['apple', 'orange'] #} .. note:: Internally, Twig uses the PHP `array_column`_ function. Arguments --------- * ``name``: The column name to extract .. _`array_column`: https://secure.php.net/array_column php-twig-2.12.5/doc/filters/convert_encoding.rst000066400000000000000000000007411362457344700216560ustar00rootroot00000000000000``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:: twig {{ data|convert_encoding('UTF-8', 'iso-2022-jp') }} .. note:: This filter relies on the `iconv`_ extension. Arguments --------- * ``to``: The output charset * ``from``: The input charset .. _`iconv`: https://secure.php.net/iconv php-twig-2.12.5/doc/filters/country_name.rst000066400000000000000000000016501362457344700210330ustar00rootroot00000000000000``country_name`` ================ .. versionadded:: 2.12 The ``country_name`` filter was added in Twig 2.12. The ``country_name`` filter returns the country name given its ISO-3166 two-letter code: .. code-block:: twig {# France #} {{ 'FR'|country_name }} By default, the filter uses the current locale. You can pass it explicitly: .. code-block:: twig {# États-Unis #} {{ 'US'|country_name('fr') }} .. note:: The ``country_name`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``locale``: The locale php-twig-2.12.5/doc/filters/currency_name.rst000066400000000000000000000017431362457344700211650ustar00rootroot00000000000000``currency_name`` ================= .. versionadded:: 2.12 The ``currency_name`` filter was added in Twig 2.12. The ``currency_name`` filter returns the currency name given its three-letter code: .. code-block:: twig {# Euro #} {{ 'EUR'|currency_name }} {# Japanese Yen #} {{ 'JPY'|currency_name }} By default, the filter uses the current locale. You can pass it explicitly: .. code-block:: twig {# yen japonais #} {{ 'JPY'|currency_name('fr_FR') }} .. note:: The ``currency_name`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``locale``: The locale php-twig-2.12.5/doc/filters/currency_symbol.rst000066400000000000000000000017351362457344700215530ustar00rootroot00000000000000``currency_symbol`` =================== .. versionadded:: 2.12 The ``currency_symbol`` filter was added in Twig 2.12. The ``currency_symbol`` filter returns the currency symbol given its three-letter code: .. code-block:: twig {# € #} {{ 'EUR'|currency_symbol }} {# ¥ #} {{ 'JPY'|currency_symbol }} By default, the filter uses the current locale. You can pass it explicitly: .. code-block:: twig {# ¥ #} {{ 'JPY'|currency_symbol('fr') }} .. note:: The ``currency_symbol`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``locale``: The locale php-twig-2.12.5/doc/filters/data_uri.rst000066400000000000000000000024701362457344700201210ustar00rootroot00000000000000``data_uri`` ============ .. versionadded:: 2.12 The ``data_uri`` filter was added in Twig 2.12. The ``data_uri`` filter generates a URL using the data scheme as defined in RFC 2397: .. code-block:: twig {{ image_data|data_uri }} {{ source('path_to_image')|data_uri }} {# force the mime type, disable the guessing of the mime type #} {{ image_data|data_uri(mime="image/svg") }} {# also works with plain text #} {{ 'foobar'|data_uri(mime="text/html") }} {# add some extra parameters #} {{ 'foobar'|data_uri(mime="text/html", parameters={charset: "ascii"}) }} .. note:: The ``data_uri`` filter is part of the ``HtmlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/html-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Html\HtmlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new HtmlExtension()); .. note:: The filter does not perform any length validation on purpose (limits depends on the usage context), validation should be done before calling this filter. Arguments --------- * ``mime``: The mime type * ``parameters``: An array of parameters php-twig-2.12.5/doc/filters/date.rst000066400000000000000000000051041362457344700172430ustar00rootroot00000000000000``date`` ======== The ``date`` filter formats a date to a given format: .. code-block:: twig {{ 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:: twig {{ "now"|date("m/d/Y") }} To escape words and characters in the date format use ``\\`` in front of each character: .. code-block:: twig {{ 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:: twig {{ 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 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\CoreExtension::class)->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:: twig {{ 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:: twig {{ 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\CoreExtension::class)->setTimezone('Europe/Paris'); Arguments --------- * ``format``: The date format * ``timezone``: The date timezone .. _`strtotime`: https://secure.php.net/strtotime .. _`DateTime`: https://secure.php.net/DateTime .. _`DateInterval`: https://secure.php.net/DateInterval .. _`date`: https://secure.php.net/date .. _`DateInterval::format`: https://secure.php.net/DateInterval.format php-twig-2.12.5/doc/filters/date_modify.rst000066400000000000000000000010431362457344700206100ustar00rootroot00000000000000``date_modify`` =============== The ``date_modify`` filter modifies a date with a given modifier string: .. code-block:: twig {{ 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 combine it with the :doc:`date` filter for formatting. Arguments --------- * ``modifier``: The modifier .. _`strtotime`: https://secure.php.net/strtotime .. _`DateTime`: https://secure.php.net/DateTime php-twig-2.12.5/doc/filters/default.rst000066400000000000000000000015301362457344700177510ustar00rootroot00000000000000``default`` =========== The ``default`` filter returns the passed default value if the value is undefined or empty, otherwise the value of the variable: .. code-block:: twig {{ 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:: twig {{ 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 php-twig-2.12.5/doc/filters/escape.rst000066400000000000000000000067311362457344700175750ustar00rootroot00000000000000``escape`` ========== The ``escape`` filter escapes a string using strategies that depend on the context. By default, it uses the HTML escaping strategy: .. code-block:: html+twig

{{ user.username|escape }}

For convenience, the ``e`` filter is defined as an alias: .. code-block:: html+twig

{{ 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:: twig {{ user.username|e }} {# is equivalent to #} {{ user.username|e('html') }} And here is how to escape variables included in JavaScript code: .. code-block:: twig {{ user.username|escape('js') }} {{ user.username|e('js') }} The ``escape`` filter supports the following escaping strategies for HTML documents: * ``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 that doing contextual escaping in HTML documents is hard and choosing the right escaping strategy depends on a lot of factors. Please, read related documentation like `the OWASP prevention cheat sheet `_ to learn more about this topic. .. 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:: twig {% 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:: twig {% 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\CoreExtension::class)->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 because they should be considered as the final implementation and also for better performance. Arguments --------- * ``strategy``: The escaping strategy * ``charset``: The string charset .. _`htmlspecialchars`: https://secure.php.net/htmlspecialchars php-twig-2.12.5/doc/filters/filter.rst000066400000000000000000000023671362457344700176230ustar00rootroot00000000000000``filter`` ========== .. versionadded:: 1.41 The ``filter`` filter was added in Twig 1.41 and 2.10. The ``filter`` filter filters elements of a sequence or a mapping using an arrow function. The arrow function receives the value of the sequence or mapping: .. code-block:: twig {% set sizes = [34, 36, 38, 40, 42] %} {{ sizes|filter(v => v > 38)|join(', ') }} {# output 40, 42 #} Combined with the ``for`` tag, it allows to filter the items to iterate over: .. code-block:: twig {% for v in sizes|filter(v => v > 38) -%} {{ v }} {% endfor %} {# output 40 42 #} It also works with mappings: .. code-block:: twig {% set sizes = { xs: 34, s: 36, m: 38, l: 40, xl: 42, } %} {% for k, v in sizes|filter(v => v > 38) -%} {{ k }} = {{ v }} {% endfor %} {# output l = 40 xl = 42 #} The arrow function also receives the key as a second argument: .. code-block:: twig {% for k, v in sizes|filter((v, k) => v > 38 and k != "xl") -%} {{ k }} = {{ v }} {% endfor %} {# output l = 40 #} Note that the arrow function has access to the current context. Arguments --------- * ``array``: The sequence or mapping * ``arrow``: The arrow function php-twig-2.12.5/doc/filters/first.rst000066400000000000000000000007021362457344700174540ustar00rootroot00000000000000``first`` ========= The ``first`` filter returns the first "element" of a sequence, a mapping, or a string: .. code-block:: twig {{ [1, 2, 3, 4]|first }} {# outputs 1 #} {{ { a: 1, b: 2, c: 3, d: 4 }|first }} {# outputs 1 #} {{ '1234'|first }} {# outputs 1 #} .. note:: It also works with objects implementing the `Traversable`_ interface. .. _`Traversable`: https://secure.php.net/manual/en/class.traversable.php php-twig-2.12.5/doc/filters/format.rst000066400000000000000000000006131362457344700176160ustar00rootroot00000000000000``format`` ========== The ``format`` filter formats a given string by replacing the placeholders (placeholders follows the `sprintf`_ notation): .. code-block:: twig {{ "I like %s and %s."|format(foo, "bar") }} {# outputs I like foo and bar if the foo parameter equals to the foo string. #} .. _`sprintf`: https://secure.php.net/sprintf .. seealso:: :doc:`replace` php-twig-2.12.5/doc/filters/format_currency.rst000066400000000000000000000034031362457344700215300ustar00rootroot00000000000000``format_currency`` =================== .. versionadded:: 2.12 The ``format_currency`` filter was added in Twig 2.12. The ``format_currency`` filter formats a number as a currency: .. code-block:: twig {# €1,000,000.00 #} {{ '1000000'|format_currency('EUR') }} You can pass attributes to tweak the output: .. code-block:: twig {# €12.34 #} {{ '12.345'|format_currency('EUR', {rounding_mode: 'floor'}) }} {# €1,000,000.0000 #} {{ '1000000'|format_currency('EUR', {fraction_digit: 4}) }} The list of supported options: * ``grouping_used``; * ``decimal_always_shown``; * ``max_integer_digit``; * ``min_integer_digit``; * ``integer_digit``; * ``max_fraction_digit``; * ``min_fraction_digit``; * ``fraction_digit``; * ``multiplier``; * ``grouping_size``; * ``rounding_mode``; * ``rounding_increment``; * ``format_width``; * ``padding_position``; * ``secondary_grouping_size``; * ``significant_digits_used``; * ``min_significant_digits_used``; * ``max_significant_digits_used``; * ``lenient_parse``. By default, the filter uses the current locale. You can pass it explicitly: .. code-block:: twig {# 1.000.000,00 € #} {{ '1000000'|format_currency('EUR', locale='de') }} .. note:: The ``format_currency`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``currency``: The currency * ``attrs``: A map of attributes * ``locale``: The locale php-twig-2.12.5/doc/filters/format_date.rst000066400000000000000000000014651362457344700206210ustar00rootroot00000000000000``format_date`` =============== .. versionadded:: 2.12 The ``format_date`` filter was added in Twig 2.12. The ``format_date`` filter formats a date. It behaves in the exact same way as the ``format_datetime`` filter, but without the time. .. note:: The ``format_date`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``locale``: The locale * ``dateFormat``: The date format * ``pattern``: A date time pattern php-twig-2.12.5/doc/filters/format_datetime.rst000066400000000000000000000037131362457344700214760ustar00rootroot00000000000000``format_datetime`` =================== .. versionadded:: 2.12 The ``format_datetime`` filter was added in Twig 2.12. The ``format_datetime`` filter formats a date time: public function formatDateTime(Environment $env, $date, ?string $dateFormat = 'medium', ?string $timeFormat = 'medium', string $pattern = '', $timezone = null, string $calendar = 'gregorian', string $locale = null): string .. code-block:: twig {# Aug 7, 2019, 11:39:12 PM #} {{ '2019-08-07 23:39:12'|format_datetime() }} You can tweak the output for the date part and the time part: .. code-block:: twig {# 23:39 #} {{ '2019-08-07 23:39:12'|format_datetime('none', 'short', locale='fr') }} {# 07/08/2019 #} {{ '2019-08-07 23:39:12'|format_datetime('short', 'none', locale='fr') }} {# mercredi 7 août 2019 23:39:12 UTC #} {{ '2019-08-07 23:39:12'|format_datetime('full', 'full', locale='fr') }} Supported values are: ``none``, ``short``, ``medium``, ``long``, and ``full``. For greater flexiblity, you can even define your own pattern: .. code-block:: twig {# 11 oclock PM, GMT #} {{ '2019-08-07 23:39:12'|format_datetime(pattern="hh 'oclock' a, zzzz") }} By default, the filter uses the current locale. You can pass it explicitly: .. code-block:: twig {# 7 août 2019 23:39:12 #} {{ '2019-08-07 23:39:12'|format_datetime(locale='fr') }} .. note:: The ``format_datetime`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``locale``: The locale * ``dateFormat``: The date format * ``timeFormat``: The time format * ``pattern``: A date time pattern php-twig-2.12.5/doc/filters/format_number.rst000066400000000000000000000051451362457344700211730ustar00rootroot00000000000000``format_number`` ================= .. versionadded:: 2.12 The ``format_number`` filter was added in Twig 2.12. The ``format_number`` filter formats a number: .. code-block:: twig {{ '12.345'|format_number }} You can pass attributes to tweak the output: .. code-block:: twig {# 12.34 #} {{ '12.345'|format_number({rounding_mode: 'floor'}) }} {# 1000000.0000 #} {{ '1000000'|format_number({fraction_digit: 4}) }} The list of supported options: * ``grouping_used``; * ``decimal_always_shown``; * ``max_integer_digit``; * ``min_integer_digit``; * ``integer_digit``; * ``max_fraction_digit``; * ``min_fraction_digit``; * ``fraction_digit``; * ``multiplier``; * ``grouping_size``; * ``rounding_mode``; * ``rounding_increment``; * ``format_width``; * ``padding_position``; * ``secondary_grouping_size``; * ``significant_digits_used``; * ``min_significant_digits_used``; * ``max_significant_digits_used``; * ``lenient_parse``. Besides plain numbers, the filter can also format numbers in various styles: .. code-block:: twig {# 1,234% #} {{ '12.345'|format_number(style='percent') }} {# twelve point three four five #} {{ '12.345'|format_number(style='spellout') }} {# 12 sec. #} {{ '12'|format_duration_number }} The list of supported styles: * ``decimal``; * ``currency``; * ``percent``; * ``scientific``; * ``spellout``; * ``ordinal``; * ``duration``. As a shortcut, you can use the ``format_*_number`` filters by replacing `*` with a style: .. code-block:: twig {# 1,234% #} {{ '12.345'|format_percent_number }} {# twelve point three four five #} {{ '12.345'|format_spellout_number }} You can pass attributes to tweak the output: .. code-block:: twig {# €12.34 #} {{ '12.345'|format_number('EUR', {rounding_mode: 'floor'}) }} {# €1,000,000.0000 #} {{ '1000000'|format_number('EUR', {fraction_digit: 4}) }} By default, the filter uses the current locale. You can pass it explicitly: .. code-block:: twig {# 12,345 #} {{ '12.345'|format_number(locale='fr') }} .. note:: The ``format_number`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``locale``: The locale * ``attrs``: A map of attributes * ``style``: The style of the number output php-twig-2.12.5/doc/filters/format_time.rst000066400000000000000000000014651362457344700206420ustar00rootroot00000000000000``format_time`` =============== .. versionadded:: 2.12 The ``format_time`` filter was added in Twig 2.12. The ``format_time`` filter formats a time. It behaves in the exact same way as the ``format_datetime`` filter, but without the date. .. note:: The ``format_time`` filter is part of the ``IntlExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/intl-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Intl\IntlExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new IntlExtension()); Arguments --------- * ``locale``: The locale * ``timeFormat``: The time format * ``pattern``: A date time pattern php-twig-2.12.5/doc/filters/html_to_markdown.rst000066400000000000000000000034271362457344700217040ustar00rootroot00000000000000``html_to_markdown`` ==================== .. versionadded:: 2.12 The ``html_to_markdown`` filter was added in Twig 2.12. The ``html_to_markdown`` filter converts a block of HTML to Markdown: .. code-block:: twig {% apply html_to_markdown %}

Hello!

{% endapply %} You can also add some options by passing them as an argument to the filter: .. code-block:: twig {% apply html_to_markdown({hard_break: false}) %}

Hello!

{% endapply %} .. note:: The options are the ones provided by the ``league/html-to-markdown`` package. You can also use the filter on an included file: .. code-block:: twig {{ include('some_template.html.twig')|html_to_markdown }} .. note:: The ``html_to_markdown`` filter is part of the ``MarkdownExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/markdown-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Markdown\MarkdownMarkdownExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new MarkdownExtension()); If you are not using Symfony, you must also register the extension runtime:: use Twig\Extra\Markdown\DefaultMarkdown; use Twig\Extra\Markdown\MarkdownRuntime; use Twig\RuntimeLoader\RuntimeLoaderInterface; $twig->addRuntimeLoader(new class implements RuntimeLoaderInterface { public function load($class) { if (MarkdownRuntime::class === $class) { return new MarkdownRuntime(new DefaultMarkdown()); } } }); php-twig-2.12.5/doc/filters/index.rst000066400000000000000000000013531362457344700174370ustar00rootroot00000000000000Filters ======= .. toctree:: :maxdepth: 1 abs batch capitalize column convert_encoding country_name currency_name currency_symbol data_uri date date_modify default escape filter first format format_currency format_date format_datetime format_number format_time html_to_markdown inline_css inky_to_html join json_encode keys language_name last length locale_name lower map markdown_to_html merge nl2br number_format raw reduce replace reverse round slice sort spaceless split striptags timezone_name title trim u upper url_encode php-twig-2.12.5/doc/filters/inky_to_html.rst000066400000000000000000000017331362457344700210320ustar00rootroot00000000000000``inky_to_html`` ================ .. versionadded:: 2.12 The ``inky_to_html`` filter was added in Twig 2.12. The ``inky_to_html`` filter processes an `inky email template `_: .. code-block:: twig {% apply inky_to_html %} {% endapply %} You can also use the filter on an included file: .. code-block:: twig {{ include('some_template.inky.twig')|inky_to_html }} .. note:: The ``inky_to_html`` filter is part of the ``InkyExtension`` which is not installed by default. Install it first: .. code-block:: bash $ composer req twig/inky-extra Then, use the ``twig/extra-bundle`` on Symfony projects or add the extension explictly on the Twig environment:: use Twig\Extra\Inky\InkyExtension; $twig = new \Twig\Environment(...); $twig->addExtension(new InkyExtension()); php-twig-2.12.5/doc/filters/inline_css.rst000066400000000000000000000031671362457344700204630ustar00rootroot00000000000000``inline_css`` ============== .. versionadded:: 2.12 The ``inline_css`` filter was added in Twig 2.12. The ``inline_css`` filter inline CSS styles in HTML documents: .. code-block:: twig {% apply inline_css %}

Hello CSS!

{% endapply %} You can also add some stylesheets by passing them as arguments to the filter: .. code-block:: twig {% apply inline_css(source("some_styles.css"), source("another.css")) %}

Hello CSS!

{% endapply %} Styles loaded via the filter override the styles defined in the `` {% 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:: twig {% 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:: twig {% 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 (the name after the ``endblock`` word must match the block name): .. code-block:: twig {% block sidebar %} {% block inner_sidebar %} ... {% endblock inner_sidebar %} {% endblock sidebar %} Block Nesting and Scope ----------------------- Blocks can be nested for more complex layouts. Per default, blocks have access to variables from outer scopes: .. code-block:: twig {% 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:: twig {% block title %} {{ page_title|title }} {% endblock %} .. code-block:: twig {% block title page_title|title %} Dynamic Inheritance ------------------- Twig supports dynamic inheritance by using a variable as the base template: .. code-block:: twig {% 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', ['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:: twig {% 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:: twig {% 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:: twig {# 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:: twig {# 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:: twig {% for post in posts %}
    {{ post.title }}
    {{ post.text }}
    {% endfor %} Let's take another example: a block included within an ``if`` statement: .. code-block:: twig {% 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:: twig {% 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>` php-twig-2.12.5/doc/tags/filter.rst000066400000000000000000000012141362457344700170770ustar00rootroot00000000000000``filter`` ========== .. note:: As of Twig 2.9, you should use the ``apply`` tag instead which does the same thing except that the wrapped template data is not scoped. 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:: twig {% filter upper %} This text becomes uppercase {% endfilter %} You can also chain filters and pass arguments to them: .. code-block:: twig {% filter lower|escape('html') %} SOME TEXT {% endfilter %} {# outputs "<strong>some text</strong>" #} php-twig-2.12.5/doc/tags/flush.rst000066400000000000000000000003411362457344700167330ustar00rootroot00000000000000``flush`` ========= The ``flush`` tag tells Twig to flush the output buffer: .. code-block:: twig {% flush %} .. note:: Internally, Twig uses the PHP `flush`_ function. .. _`flush`: https://secure.php.net/flush php-twig-2.12.5/doc/tags/for.rst000066400000000000000000000113201362457344700163770ustar00rootroot00000000000000``for`` ======= Loop over each item in a sequence. For example, to display a list of users provided in a variable called ``users``: .. code-block:: twig

    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:: twig {% 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:: twig {% for letter in 'a'..'z' %} * {{ letter }} {% endfor %} The ``..`` operator can take any expression at both sides: .. code-block:: twig {% 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:: twig {% 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 ------------------ .. tip:: As of Twig 2.10, use the :doc:`filter <../filters/filter>` filter instead, or an ``if`` condition inside the ``for`` body (if your condition depends on a variable updated inside the loop and you are not using the ``loop`` variable). 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:: twig
      {% 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:: twig
      {% 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:: twig

    Members

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

    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:: twig

    Top Ten Members

      {% for user in users|slice(0, 10) %}
    • {{ user.username|e }}
    • {% endfor %}
    php-twig-2.12.5/doc/tags/from.rst000066400000000000000000000003101362457344700165510ustar00rootroot00000000000000``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:`macro<../tags/macro>` tag. php-twig-2.12.5/doc/tags/if.rst000066400000000000000000000037721362457344700162230ustar00rootroot00000000000000``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:: twig {% 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:: twig {% 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:: twig {% if not user.subscribed %}

    You are not subscribed to our mailing list.

    {% endif %} For multiple conditions, ``and`` and ``or`` can be used: .. code-block:: twig {% 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:: twig {% if product.stock > 10 %} Available {% elseif product.stock > 0 %} Only {{ product.stock }} left! {% else %} Sold-out! {% endif %} .. note:: The rules to determine if an expression is ``true`` or ``false`` are the same as in PHP; here are the edge cases rules: ====================== ==================== Value Boolean evaluation ====================== ==================== empty string false numeric zero false NAN (Not A Number) true INF (Infinity) true whitespace-only string true string "0" or '0' false empty array false null false non-empty array true object true ====================== ==================== php-twig-2.12.5/doc/tags/import.rst000066400000000000000000000003071362457344700171260ustar00rootroot00000000000000``import`` ========== The ``import`` tag imports :doc:`macro<../tags/macro>` names in a local variable. The tag is documented in detail in the documentation for the :doc:`macro<../tags/macro>` tag. php-twig-2.12.5/doc/tags/include.rst000066400000000000000000000066731362457344700172530ustar00rootroot00000000000000``include`` =========== The ``include`` statement includes a template and returns the rendered content of that file: .. code-block:: twig {% include 'header.html' %} Body {% include 'footer.html' %} .. note:: As of Twig 1.12, it is recommended to use the :doc:`include<../functions/include>` function instead as it provides the same features with a bit more flexibility: * The ``include`` function is semantically more "correct" (including a template outputs its rendered contents in the current scope; a tag should not display anything); * The ``include`` function is more "composable": .. code-block:: twig {# Store a rendered template in a variable #} {% set content %} {% include 'template.html' %} {% endset %} {# vs #} {% set content = include('template.html') %} {# Filter a rendered template #} {% filter upper %} {% include 'template.html' %} {% endfilter %} {# vs #} {{ include('template.html')|upper }} * The ``include`` function does not impose any specific order for arguments thanks to :ref:`named arguments `. 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:: twig {# 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:: twig {# only the foo variable will be accessible #} {% include 'template.html' with {'foo': 'bar'} only %} .. code-block:: twig {# 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:: twig {% 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', ['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:: twig {% 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:: twig {% 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. php-twig-2.12.5/doc/tags/index.rst000066400000000000000000000004071362457344700167240ustar00rootroot00000000000000Tags ==== .. toctree:: :maxdepth: 1 apply autoescape block deprecated do embed extends filter flush for from if import include macro sandbox set spaceless use verbatim with php-twig-2.12.5/doc/tags/macro.rst000066400000000000000000000126071362457344700167230ustar00rootroot00000000000000``macro`` ========= Macros are comparable with functions in regular programming languages. They are useful to reuse template fragments to not repeat yourself. Macros are defined in regular templates. Imagine having a generic helper template that define how to render HTML forms via macros (called ``forms.html``): .. code-block:: twig {% macro input(name, value, type = "text", size = 20) %} {% endmacro %} {% macro textarea(name, value, rows = 10, cols = 40) %} {% endmacro %} Each macro argument can have a default value (here ``text`` is the default value for ``type`` if not provided in the call). Macros differ from native PHP functions in a few ways: * 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. Importing Macros ---------------- There are two ways to import macros. You can import the complete template containing the macros into a local variable (via the ``import`` tag) or only import specific macros from the template (via the ``from`` tag). To import all macros from a template into a local variable, use the ``import`` tag: .. code-block:: twig {% 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 macros as items of the ``forms`` local variable. The macros can then be called at will in the *current* template: .. code-block:: twig

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

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

    Alternatively you can import names from the template into the current namespace via the ``from`` tag: .. code-block:: twig {% from 'forms.html' import input as input_field, textarea %}

    {{ input_field('password', '', 'password') }}

    {{ textarea('comment') }}

    .. tip:: When macro usages and definitions are in the same template, you don't need to import the macros as they are automatically available under the special ``_self`` variable: .. code-block:: twig

    {{ _self.input('password', '', 'password') }}

    {% macro input(name, value, type = "text", size = 20) %} {% endmacro %} Auto-import is only available as of Twig 2.11. For older versions, import macros using the special ``_self`` variable for the template name: .. code-block:: twig {% import _self as forms %}

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

    .. note:: Before Twig 2.11, when you want to use a macro in another macro from the same file, you need to import it locally: .. code-block:: twig {% 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 %} Macros Scoping -------------- .. versionadded:: 2.11 The scoping rules described in this paragraph are implemented as of Twig 2.11. The scoping rules are the same whether you imported macros via ``import`` or ``from``. Imported macros are always **local** to the current template. It means that macros are available in all blocks and other macros defined in the current template, but they are not available in included templates or child templates; you need to explicitely re-import macros in each template. When calling ``import`` or ``from`` from a ``block`` tag, the imported macros are only defined in the current block and they override macros defined at the template level with the same names. When calling ``import`` or ``from`` from a ``macro`` tag, the imported macros are only defined in the current macro and they override macros defined at the template level with the same names. .. note:: Before Twig 2.11, it was possible to use macros imported in a block in a "sub-block". When upgrading to 2.11, you need to either move the import in the global scope or reimport the macros explicitly in the "sub-blocks". Checking if a Macro is defined ------------------------------ .. versionadded:: 2.11 Support for the ``defined`` test on macros was added in Twig 2.11. You can check if a macro is defined via the ``defined`` test: .. code-block:: twig {% import "macros.twig" as macros %} {% from "macros.twig" import hello %} {% if macros.hello is defined -%} OK {% endif %} {% if hello is defined -%} OK {% endif %} Named Macro End-Tags -------------------- Twig allows you to put the name of the macro after the end tag for better readability (the name after the ``endmacro`` word must match the macro name): .. code-block:: twig {% macro input() %} ... {% endmacro input %} php-twig-2.12.5/doc/tags/sandbox.rst000066400000000000000000000013721362457344700172550ustar00rootroot00000000000000``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:: twig {% 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:: twig {% sandbox %} {% for i in 1..2 %} {{ i }} {% endfor %} {% endsandbox %} php-twig-2.12.5/doc/tags/set.rst000066400000000000000000000032121362457344700164050ustar00rootroot00000000000000``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:: twig {% set foo = 'bar' %} After the ``set`` call, the ``foo`` variable is available in the template like any other ones: .. code-block:: twig {# displays bar #} {{ foo }} The assigned value can be any valid :ref:`Twig expression `: .. code-block:: twig {% set foo = [1, 2] %} {% set foo = {'foo': 'bar'} %} {% set foo = 'foo' ~ 'bar' %} Several variables can be assigned in one block: .. code-block:: twig {% 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:: twig {% 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:: twig {% 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:: twig {% set foo = "" %} {% for item in list %} {% set foo = item %} {% endfor %} {# foo is available #} php-twig-2.12.5/doc/tags/spaceless.rst000066400000000000000000000023631362457344700176020ustar00rootroot00000000000000``spaceless`` ============= .. tip:: As of Twig 1.38, use the :doc:`spaceless <../filters/spaceless>` filter instead. Use the ``spaceless`` tag to remove whitespace *between HTML tags*, not whitespace within HTML tags or whitespace in plain text: .. code-block:: twig {% 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. php-twig-2.12.5/doc/tags/use.rst000066400000000000000000000062661362457344700164220ustar00rootroot00000000000000``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:: twig {% 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:: twig {% 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:: twig {# 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:: twig {% 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:: twig {% 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:: twig {% 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:: twig {% 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. php-twig-2.12.5/doc/tags/verbatim.rst000066400000000000000000000005561362457344700174330ustar00rootroot00000000000000``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:: twig {% verbatim %}
      {% for item in seq %}
    • {{ item }}
    • {% endfor %}
    {% endverbatim %} php-twig-2.12.5/doc/tags/with.rst000066400000000000000000000020741362457344700165720ustar00rootroot00000000000000``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:: twig {% 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:: twig {% 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:: twig {% set bar = 'bar' %} {% with { foo: 42 } only %} {# only foo is defined #} {# bar is not defined #} {% endwith %} php-twig-2.12.5/doc/templates.rst000066400000000000000000000624071362457344700166650ustar00rootroot00000000000000Twig 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 a regular 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 template's logic. Below is a minimal template that illustrates a few basics. We will cover further details later on: .. code-block:: html+twig 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 outputs the result of an expression. 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. Use a dot (``.``) to access attributes of a variable (methods or properties of a PHP object, or items of a PHP array): .. code-block:: twig {{ foo.bar }} .. 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. .. 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. Twig also supports a specific syntax for accessing items on PHP arrays, ``foo['bar']``: * check if ``foo`` is an array and ``bar`` a valid element; * if not, return a ``null`` value. 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`). .. note:: If you want to access a dynamic attribute of a variable, use the :doc:`attribute` function instead. The ``attribute`` function is also useful when the attribute contains special characters (like ``-`` that would be interpreted as the minus operator): .. code-block:: twig {# equivalent to the non-working foo.data-foo #} {{ attribute(foo, 'data-foo') }} 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:: twig {% 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 (``|``). 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:: twig {{ name|striptags|title }} Filters that accept arguments have parentheses around the arguments. This example joins the elements of a list by commas: .. code-block:: twig {{ list|join(', ') }} To apply a filter on a section of code, wrap it with the :doc:`apply` tag: .. code-block:: twig {% apply upper %} This text becomes uppercase {% endapply %} Go to the :doc:`filters` page to learn more about built-in filters. .. note:: The ``apply`` tag was introduced in Twig 2.9; use the ``filter`` tag with previous versions. 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:: twig {% for i in range(0, 3) %} {{ i }}, {% endfor %} Go to the :doc:`functions` page to learn more about the built-in functions. .. _named-arguments: Named Arguments --------------- .. code-block:: twig {% 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:: twig {{ 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:: twig {# 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:: twig {{ "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:: twig

    Members

      {% for user in users %}
    • {{ user.username|e }}
    • {% endfor %}
    The :doc:`if` tag can be used to test an expression: .. code-block:: twig {% 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:: twig {# 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:: twig {{ 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:: twig {% for box in boxes %} {{ include('render_box.html') }} {% endfor %} The included template ``render_box.html`` is able to access the ``box`` variable. The name of the template depends on the template loader. For instance, the ``\Twig\Loader\FilesystemLoader`` allows you to access other templates by giving the filename. You can access templates in subdirectories with a slash: .. code-block:: twig {{ 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. It's easier to understand the concept by starting with an example. Let's define a base template, ``base.html``, which defines an HTML skeleton document that might be used for a two-column page: .. code-block:: html+twig {% 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:: twig {% 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:: twig {% 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 via "horizontal reuse" with the help of the :doc:`use` tag. 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 that comes from an untrusted source. Escaping works by using the :doc:`escape` or ``e`` filter: .. code-block:: twig {{ user.username|e }} By default, the ``escape`` filter uses the ``html`` strategy, but depending on the escaping context, you might want to explicitly use an other strategy: .. code-block:: twig {{ 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:: twig {% 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:: twig {% 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:: twig {{ '{{' }} 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 HTML fragments to not repeat yourself. They are described in the :doc:`macro` tag documentation. .. _twig-expressions: Expressions ----------- Twig allows expressions everywhere. .. note:: The operator precedence is as follows, with the lowest-precedence operators listed first: ``?:`` (ternary operator), ``b-and``, ``b-xor``, ``b-or``, ``or``, ``and``, ``==``, ``!=``, ``<=>``, ``<``, ``>``, ``>=``, ``<=``, ``in``, ``matches``, ``starts with``, ``ends with``, ``..``, ``+``, ``-``, ``~``, ``*``, ``/``, ``//``, ``%``, ``is`` (tests), ``**``, ``??``, ``|`` (filters), ``[]``, and ``.``: .. code-block:: twig {% 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 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:: twig {# 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:: twig {% set foo = [1, {"foo": "bar"}] %} .. tip:: Using double-quoted or single-quoted strings has no impact on performance but :ref:`string interpolation ` is only supported in double-quoted strings. Math ~~~~ Twig allows you to do math in templates; the following operators are supported: * ``+``: Adds two numbers together (the operands are casted to numbers). ``{{ 1 + 1 }}`` is ``2``. * ``-``: Subtracts the second number from the first one. ``{{ 3 - 2 }}`` is ``1``. * ``/``: Divides two numbers. The returned value will be a floating point number. ``{{ 1 / 2 }}`` is ``{{ 0.5 }}``. * ``%``: Calculates the remainder of an integer division. ``{{ 11 % 7 }}`` is ``4``. * ``//``: Divides two numbers and returns the floored integer result. ``{{ 20 // 7 }}`` is ``2``, ``{{ -20 // 7 }}`` is ``-3`` (this is just syntactic sugar for the :doc:`round` filter). * ``*``: Multiplies the left operand with the right one. ``{{ 2 * 2 }}`` would return ``4``. * ``**``: Raises the left operand to the power of the right operand. ``{{ 2 ** 3 }}`` would return ``8``. .. _template_logic: Logic ~~~~~ You can combine multiple expressions with the following operators: * ``and``: Returns true if the left and the right operands are both true. * ``or``: Returns true if the left or the right operand is true. * ``not``: Negates a statement. * ``(expr)``: Groups an expression. .. note:: Twig also supports bitwise operators (``b-and``, ``b-xor``, and ``b-or``). .. note:: Operators are case sensitive. Comparisons ~~~~~~~~~~~ The following comparison operators are supported in any expression: ``==``, ``!=``, ``<``, ``>``, ``>=``, and ``<=``. You can also check if a string ``starts with`` or ``ends with`` another string: .. code-block:: twig {% 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:: twig {% 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:: twig {# 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:: twig {% 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:: twig {# find out if a variable is odd #} {{ name is odd }} Tests can accept arguments too: .. code-block:: twig {% if post.status is constant('Post::PUBLISHED') %} Tests can be negated by using the ``is not`` operator: .. code-block:: twig {% 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 syntactic sugar for the :doc:`range` function): .. code-block:: twig {{ 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:: twig (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 a variable. * ``?:``: The ternary operator: .. code-block:: twig {{ 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:: twig {# returns the value of foo if it is defined and not null, 'no' otherwise #} {{ foo ?? 'no' }} .. _templates-string-interpolation: 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:: twig {{ "foo #{bar} baz" }} {{ "foo #{1 + 2} baz" }} .. _templates-whitespace-control: Whitespace Control ------------------ .. versionadded:: 2.8 Tag level Line whitespace control was added in Twig 2.8. 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. You can also control whitespace on a per tag level. By using the whitespace control modifiers on your tags, you can trim leading and or trailing whitespace. Twig supports two modifiers: * *Whitespace trimming* via the ``-`` modifier: Removes all whitespace (including newlines); * *Line whitespace trimming* via the ``~`` modifier: Removes all whitespace (excluding newlines). Using this modifier on the right disables the default removal of the first newline inherited from PHP. The modifiers can be used on either side of the tags like in ``{%-`` or ``-%}`` and they consume all whitespace for that side of the tag. It is possible to use the modifiers on one side of a tag or on both sides: .. code-block:: twig {% set value = 'no spaces' %} {#- No leading/trailing whitespace -#} {%- if true -%} {{- value -}} {%- endif -%} {# output 'no spaces' #}
  • {{ value }}
  • {# outputs '
  • \n no spaces
  • ' #}
  • {{- value }}
  • {# outputs '
  • no spaces
  • ' #}
  • {{~ value }}
  • {# outputs '
  • \nno spaces
  • ' #} .. tip:: In addition to the whitespace modifiers, Twig also has a ``spaceless`` filter that removes whitespace **between HTML tags**: .. code-block:: twig {% apply spaceless %}
    foo bar
    {% endapply %} {# output will be
    foo bar
    #} The ``apply`` tag was introduced in Twig 2.9; use the ``filter`` tag with previous versions. Extensions ---------- Twig can be extended. If you want to create your own extensions, 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 .. _`Twig syntax mode`: https://github.com/bobthecow/Twig-HTML.mode .. _`other Twig syntax mode`: https://github.com/muxx/Twig-HTML.mode .. _`Notepad++ Twig Highlighter`: https://github.com/Banane9/notepadplusplus-twig .. _`web-mode.el`: http://web-mode.org/ .. _`regular expressions`: https://secure.php.net/manual/en/pcre.pattern.php .. _`PHP-twig for atom`: https://github.com/reesef/php-twig .. _`TwigFiddle`: https://twigfiddle.com/ .. _`Twig pack`: https://marketplace.visualstudio.com/items?itemName=bajdzis.vscode-twig-pack php-twig-2.12.5/doc/tests/000077500000000000000000000000001362457344700152665ustar00rootroot00000000000000php-twig-2.12.5/doc/tests/constant.rst000066400000000000000000000010321362457344700176450ustar00rootroot00000000000000``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:: twig {% 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:: twig {% if post.status is constant('PUBLISHED', post) %} the status attribute is exactly the same as Post::PUBLISHED {% endif %} php-twig-2.12.5/doc/tests/defined.rst000066400000000000000000000012641362457344700174210ustar00rootroot00000000000000``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:: twig {# 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:: twig {% if var is defined and foo.method(var) is defined %} ... {% endif %} php-twig-2.12.5/doc/tests/divisibleby.rst000066400000000000000000000003011362457344700203170ustar00rootroot00000000000000``divisible by`` ================ ``divisible by`` checks if a variable is divisible by a number: .. code-block:: twig {% if loop.index is divisible by(3) %} ... {% endif %} php-twig-2.12.5/doc/tests/empty.rst000066400000000000000000000011021362457344700171500ustar00rootroot00000000000000``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:: twig {% if foo is empty %} ... {% endif %} php-twig-2.12.5/doc/tests/even.rst000066400000000000000000000002361362457344700167560ustar00rootroot00000000000000``even`` ======== ``even`` returns ``true`` if the given number is even: .. code-block:: twig {{ var is even }} .. seealso:: :doc:`odd<../tests/odd>` php-twig-2.12.5/doc/tests/index.rst000066400000000000000000000002211362457344700171220ustar00rootroot00000000000000Tests ===== .. toctree:: :maxdepth: 1 constant defined divisibleby empty even iterable null odd sameas php-twig-2.12.5/doc/tests/iterable.rst000066400000000000000000000006121362457344700176060ustar00rootroot00000000000000``iterable`` ============ ``iterable`` checks if a variable is an array or a traversable object: .. code-block:: twig {# 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 %} php-twig-2.12.5/doc/tests/null.rst000066400000000000000000000002521362457344700167710ustar00rootroot00000000000000``null`` ======== ``null`` returns ``true`` if the variable is ``null``: .. code-block:: twig {{ var is null }} .. note:: ``none`` is an alias for ``null``. php-twig-2.12.5/doc/tests/odd.rst000066400000000000000000000002331362457344700165640ustar00rootroot00000000000000``odd`` ======= ``odd`` returns ``true`` if the given number is odd: .. code-block:: twig {{ var is odd }} .. seealso:: :doc:`even<../tests/even>` php-twig-2.12.5/doc/tests/sameas.rst000066400000000000000000000004171362457344700172730ustar00rootroot00000000000000``same as`` =========== ``same as`` checks if a variable is the same as another variable. This is equivalent to ``===`` in PHP: .. code-block:: twig {% if foo.attribute is same as(false) %} the foo attribute really is the 'false' PHP value {% endif %} php-twig-2.12.5/drupal_test.sh000077500000000000000000000033211362457344700162430ustar00rootroot00000000000000#!/bin/bash set -x set -e REPO=`pwd` cd /tmp rm -rf drupal-twig-test composer create-project --no-interaction drupal-composer/drupal-project:8.x-dev drupal-twig-test cd drupal-twig-test (cd vendor/twig && rm -rf twig && ln -sf $REPO twig) echo '$config["system.logging"]["error_level"] = "verbose";' >> web/sites/default/settings.php composer require drupal/core:8.7.x-dev webflo/drupal-core-require-dev:8.7.x-dev "egulias/email-validator:^2.0" php ./web/core/scripts/drupal install --no-interaction demo_umami > output perl -p -i -e 's/^([A-Za-z]+)\: (.+)$/export DRUPAL_\1=\2/' output source output wget https://get.symfony.com/cli/installer -O - | bash export PATH="$HOME/.symfony/bin:$PATH" symfony server:start -d --no-tls curl -OLsS https://get.blackfire.io/blackfire-player.phar chmod +x blackfire-player.phar cat > drupal-tests.bkf < ./tests/ ./ ./tests ./vendor php-twig-2.12.5/extra/cssinliner-extra/src/000077500000000000000000000000001362457344700205635ustar00rootroot00000000000000php-twig-2.12.5/extra/cssinliner-extra/src/CssInlinerExtension.php000066400000000000000000000015241362457344700252440ustar00rootroot00000000000000 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Twig\Extra\CssInliner; use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; class CssInlinerExtension extends AbstractExtension { public function getFilters() { return [ new TwigFilter('inline_css', 'Twig\\Extra\\CssInliner\\twig_inline_css', ['is_safe' => ['all']]), ]; } } function twig_inline_css(string $body, string ...$css): string { static $inliner; if (null === $inliner) { $inliner = new CssToInlineStyles(); } return $inliner->convert($body, implode("\n", $css)); } php-twig-2.12.5/extra/cssinliner-extra/tests/000077500000000000000000000000001362457344700211365ustar00rootroot00000000000000php-twig-2.12.5/extra/cssinliner-extra/tests/Fixtures/000077500000000000000000000000001362457344700227475ustar00rootroot00000000000000php-twig-2.12.5/extra/cssinliner-extra/tests/Fixtures/inline_css.test000066400000000000000000000032161362457344700260000ustar00rootroot00000000000000--TEST-- "inline_css" filter --TEMPLATE-- {% apply inline_css|spaceless %}

    Great!

    {% endapply %} {% apply inline_css(source('css'))|spaceless %}

    Great!

    {% endapply %} {% apply inline_css(source('css'), source('more_css'))|spaceless %}

    Great!

    {% endapply %} {% apply inline_css(source('css') ~ source('more_css'))|spaceless %}

    Great!

    {% endapply %} {{ include('html')|inline_css(source('css') ~ source('more_css'))|spaceless }} --TEMPLATE(html)--

    Great!

    --TEMPLATE(css)-- p { color: red } --TEMPLATE(more_css)-- p { color: blue } --DATA-- return [] --EXPECT--

    Great!

    Great!

    Great!

    Great!

    Great!

    php-twig-2.12.5/extra/cssinliner-extra/tests/IntegrationTest.php000066400000000000000000000011051362457344700247670ustar00rootroot00000000000000 ./tests/ ./ ./tests ./vendor php-twig-2.12.5/extra/html-extra/src/000077500000000000000000000000001362457344700173565ustar00rootroot00000000000000php-twig-2.12.5/extra/html-extra/src/HtmlExtension.php000066400000000000000000000055171362457344700227000ustar00rootroot00000000000000mimeTypes = $mimeTypes; } public function getFilters() { return [ new TwigFilter('data_uri', [$this, 'dataUri']), ]; } public function getFunctions() { return [ new TwigFunction('html_classes', 'twig_html_classes'), ]; } /** * Creates a data URI (RFC 2397). * * Length validation is not perfomed on purpose, validation should * be done before calling this filter. * * @return string The generated data URI */ public function dataUri(string $data, string $mime = null, array $parameters = []): string { $repr = 'data:'; if (null === $mime) { if (null === $this->mimeTypes) { $this->mimeTypes = new MimeTypes(); } $tmp = tempnam(sys_get_temp_dir(), 'mime'); file_put_contents($tmp, $data); try { if (null === $mime = $this->mimeTypes->guessMimeType($tmp)) { $mime = 'text/plain'; } } finally { @unlink($tmp); } } $repr .= $mime; foreach ($parameters as $key => $value) { $repr .= ';'.$key.'='.rawurlencode($value); } if (0 === strpos($mime, 'text/')) { $repr .= ','.rawurlencode($data); } else { $repr .= ';base64,'.base64_encode($data); } return $repr; } } } namespace { use Twig\Error\RuntimeError; function twig_html_classes(...$args): string { $classes = []; foreach ($args as $i => $arg) { if (\is_string($arg)) { $classes[] = $arg; } elseif (\is_array($arg)) { foreach ($arg as $class => $condition) { if (!\is_string($class)) { throw new RuntimeError(sprintf('The html_classes function argument %d (key %d) should be a string, got "%s".', $i, $class, \gettype($class))); } if (!$condition) { continue; } $classes[] = $class; } } else { throw new RuntimeError(sprintf('The html_classes function argument %d should be either a string or an array, got "%s".', $i, \gettype($arg))); } } return implode(' ', array_unique($classes)); } } php-twig-2.12.5/extra/html-extra/tests/000077500000000000000000000000001362457344700177315ustar00rootroot00000000000000php-twig-2.12.5/extra/html-extra/tests/Fixtures/000077500000000000000000000000001362457344700215425ustar00rootroot00000000000000php-twig-2.12.5/extra/html-extra/tests/Fixtures/data_uri.test000066400000000000000000000075631362457344700242460ustar00rootroot00000000000000--TEST-- "data_uri" filter --TEMPLATE-- {{ 'foobar#'|data_uri(parameters={charset: "utf-8", foo: "\$bar"}) }} {{ 'foobar'|data_uri(mime="text/html", parameters={charset: "ascii"}) }} --DATA-- return [ 'sf_logo' => base64_decode('iVBORw0KGgoAAAANSUhEUgAAAG8AAAAlCAQAAADmD3/hAAAE70lEQVRoBd3BAUTdiQMH8C+PR0TEOCIiRsQ4xvgTY4zHGDHGOCIeMY7HccQYESPG8YhjRETEY4wYcYwYMUbEI0bEiEc8Pv/f+9X+3brtrduM9f98ks9QVbNk07b3eGPbit/dyOXnujVHPq2tYSCXlXGrvuSdGZVcPuYcu5hXRnKZqHrq33jnei4LVS/8Wx03czn4w0Xt2rbnxHvj+fGpu5hlE2YtqLqjo+etofzYjDn2ZcfuGrSD3RQsOdHMj82Ki5hJPNazkYI/neiayI/LNRfRSgw41NP1h6YzrXySW37X1HAtX0XVkre6buTrWfNPx7Y0vdJ14r2RRM3nTOQcVRs4tm3b7XwV81h3XzVfy7CO81pGVdwxbcyKnsUUPNKza8N5CznHLB7lm9i2r5JvYdp5W6qJZT2H7nmoaywFL/RcTaz72E7OsYKBfBNtr/JtPHVeLQW7PlhwLSUHeu4lXjrvSj5iGbfzPxrmVVNS8ZuZxIIbRv1h25/GEzUbWuZVDWhqOvJOU9N4YkjDqpbHxlIy54Gqhk3rGiqJOY9VU1LRUI+XzhtPwawz91IwbNu2Z0Yt+qepfMR1XR0NAylp4H5K7uKXRNsre15Zd6xtTkfLX1hX0bLt2JFtm35y3b5jmzYcOnIvBS2HXti36jXWErOop6SG2dhzXi0lT3wwmoJxs+Y07fmUX3KOKbvYN5OCEV2tlKzoGEy0sZiCeT23UrCJ0RS0baWgqu3YVApG7Toykmhh23AKNjFhWMfzlCzrGI73znuRkqpXevZS8rt+HuYfDJh3hDWVxAsdA4kBHaspaDs2mILr+CslDUyloG0rBffxJKfcw2KihVpKZnA/sa5rOFFxaD2J9868s+w95lIyoedZSlb108gnGfYSs4kHuJe4i9spaHubkkk8SUkdtRS0baXgEWo5ZRCbiRaGUnIH9cRd/JK4jbtJvHPmRuIBuqZTcoCHKXmjn3o+wxWsJgZ0rCRWHKikoG0nJZNYSEkdtRS0baXgEe7klGFsJlrklBrqiapDrUTToYEkXjsznpjW814lMegYN1IwpKufO/kMA1hLwTNHhnUspaRtJyWTWEhJHbUUtG2l4D4e55QaFhItckoN9RQ0dVxxqJkeq84sJFb1tFPwUM9QCm7pbyKfYREPU3ALy7iekradlExiISV11FLQtpWCqtcOTaZg2GtHRhItckoN9RTcwDKm0uNXfzfvmqcWTSRmdPA2JUv6OVTJR9Ts2LDiAFuqKajYx9uc0vY6JZNYSEkdtRS0baXkmj1H1j3zzpHpFLTIKTXUU7KHdk6Y9LFDK55oeuvESkra+lnPOa5Z8pdtTQ9UcsoS5nPKglpKRjRNpGTKIwMpWHA3pwyZt2HToqspmfMwp0x6aiQlj/A4H3ijn3oKpvQ3nQvxRNdYvivzuJoPPNTP1RQ818+BgVyASUdW810Zd+h5zhh04HPaKZjS32/5IiNe6to3lu/GsE1d70zk79T93Z663xzqaSSGtPWzazBfZFTTr37Kd+QnTQ2j+ZiKl87cTME8DgyqWNNP16386Fyx54OJRNWmjuuq1vTXyGVg0pETGwb97IlJN+3o71kuC1MOnDiw4Zm2L/lTNZeHUTsuqquRy8agp4592Rs3czkZs6KftplcbkbMea7rY/ueuq2S/w+qfvYfs2ZN+9lYLp3/AoptWBePkE2wAAAAAElFTkSuQmCC'), ] --EXPECT-- data:text/plain;charset=utf-8;foo=%24bar,foobar%23 data:text/html;charset=ascii,%3Cb%3Efoobar%3C%2Fb%3E php-twig-2.12.5/extra/html-extra/tests/Fixtures/html_classes.test000066400000000000000000000003521362457344700251240ustar00rootroot00000000000000--TEST-- "html_classes" function --TEMPLATE-- {{ html_classes('a', {'b': true, 'c': false}, 'd') }} {% set class_a = 'a' %} {% set class_b = 'b' %} {{ html_classes(class_a, {(class_b): true})}} --DATA-- return [] --EXPECT-- a b d a b php-twig-2.12.5/extra/html-extra/tests/Fixtures/html_classes_with_unsupported_arg.test000066400000000000000000000003661362457344700314650ustar00rootroot00000000000000--TEST-- "html_classes" function --TEMPLATE-- {{ html_classes(true) }} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: The html_classes function argument 0 should be either a string or an array, got "boolean" in "index.twig" at line 2. php-twig-2.12.5/extra/html-extra/tests/Fixtures/html_classes_with_unsupported_key.test000066400000000000000000000003561362457344700315030ustar00rootroot00000000000000--TEST-- "html_classes" function --TEMPLATE-- {{ html_classes(['foo']) }} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: The html_classes function argument 0 (key 0) should be a string, got "integer" in "index.twig" at line 2. php-twig-2.12.5/extra/html-extra/tests/IntegrationTest.php000066400000000000000000000010551362457344700235660ustar00rootroot00000000000000 ./tests/ ./ ./tests ./vendor php-twig-2.12.5/extra/inky-extra/src/000077500000000000000000000000001362457344700173645ustar00rootroot00000000000000php-twig-2.12.5/extra/inky-extra/src/InkyExtension.php000066400000000000000000000012651362457344700227100ustar00rootroot00000000000000 * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Twig\Extra\Inky; use Pinky; use Twig\Extension\AbstractExtension; use Twig\TwigFilter; class InkyExtension extends AbstractExtension { public function getFilters() { return [ new TwigFilter('inky_to_html', 'Twig\\Extra\\Inky\\twig_inky', ['is_safe' => ['html']]), ]; } } function twig_inky(string $body): string { return false === ($html = Pinky\transformString($body)->saveHTML()) ? '' : $html; } php-twig-2.12.5/extra/inky-extra/tests/000077500000000000000000000000001362457344700177375ustar00rootroot00000000000000php-twig-2.12.5/extra/inky-extra/tests/Fixtures/000077500000000000000000000000001362457344700215505ustar00rootroot00000000000000php-twig-2.12.5/extra/inky-extra/tests/Fixtures/inky.test000066400000000000000000000010511362457344700234200ustar00rootroot00000000000000--TEST-- "inky_to_html" filter --TEMPLATE-- {% apply inky_to_html %} {{ var }} {%- endapply %} {{ include("inky")|inky_to_html }} --TEMPLATE(inky)-- {{ var }} --DATA-- return ['var' => 'value
    '] --EXPECT--
    value<br />
    value<br />
    php-twig-2.12.5/extra/inky-extra/tests/IntegrationTest.php000066400000000000000000000010551362457344700235740ustar00rootroot00000000000000 ./tests/ ./ ./tests ./vendor php-twig-2.12.5/extra/intl-extra/src/000077500000000000000000000000001362457344700173605ustar00rootroot00000000000000php-twig-2.12.5/extra/intl-extra/src/IntlExtension.php000066400000000000000000000424721362457344700227050ustar00rootroot00000000000000 \IntlDateFormatter::NONE, 'short' => \IntlDateFormatter::SHORT, 'medium' => \IntlDateFormatter::MEDIUM, 'long' => \IntlDateFormatter::LONG, 'full' => \IntlDateFormatter::FULL, ]; private const NUMBER_TYPES = [ 'default' => \NumberFormatter::TYPE_DEFAULT, 'int32' => \NumberFormatter::TYPE_INT32, 'int64' => \NumberFormatter::TYPE_INT64, 'double' => \NumberFormatter::TYPE_DOUBLE, 'currency' => \NumberFormatter::TYPE_CURRENCY, ]; private const NUMBER_STYLES = [ 'decimal' => \NumberFormatter::DECIMAL, 'currency' => \NumberFormatter::CURRENCY, 'percent' => \NumberFormatter::PERCENT, 'scientific' => \NumberFormatter::SCIENTIFIC, 'spellout' => \NumberFormatter::SPELLOUT, 'ordinal' => \NumberFormatter::ORDINAL, 'duration' => \NumberFormatter::DURATION, ]; private const NUMBER_ATTRIBUTES = [ 'grouping_used' => \NumberFormatter::GROUPING_USED, 'decimal_always_shown' => \NumberFormatter::DECIMAL_ALWAYS_SHOWN, 'max_integer_digit' => \NumberFormatter::MAX_INTEGER_DIGITS, 'min_integer_digit' => \NumberFormatter::MIN_INTEGER_DIGITS, 'integer_digit' => \NumberFormatter::INTEGER_DIGITS, 'max_fraction_digit' => \NumberFormatter::MAX_FRACTION_DIGITS, 'min_fraction_digit' => \NumberFormatter::MIN_FRACTION_DIGITS, 'fraction_digit' => \NumberFormatter::FRACTION_DIGITS, 'multiplier' => \NumberFormatter::MULTIPLIER, 'grouping_size' => \NumberFormatter::GROUPING_SIZE, 'rounding_mode' => \NumberFormatter::ROUNDING_MODE, 'rounding_increment' => \NumberFormatter::ROUNDING_INCREMENT, 'format_width' => \NumberFormatter::FORMAT_WIDTH, 'padding_position' => \NumberFormatter::PADDING_POSITION, 'secondary_grouping_size' => \NumberFormatter::SECONDARY_GROUPING_SIZE, 'significant_digits_used' => \NumberFormatter::SIGNIFICANT_DIGITS_USED, 'min_significant_digits_used' => \NumberFormatter::MIN_SIGNIFICANT_DIGITS, 'max_significant_digits_used' => \NumberFormatter::MAX_SIGNIFICANT_DIGITS, 'lenient_parse' => \NumberFormatter::LENIENT_PARSE, ]; private const NUMBER_ROUNDING_ATTRIBUTES = [ 'ceiling' => \NumberFormatter::ROUND_CEILING, 'floor' => \NumberFormatter::ROUND_FLOOR, 'down' => \NumberFormatter::ROUND_DOWN, 'up' => \NumberFormatter::ROUND_UP, 'halfeven' => \NumberFormatter::ROUND_HALFEVEN, 'halfdown' => \NumberFormatter::ROUND_HALFDOWN, 'halfup' => \NumberFormatter::ROUND_HALFUP, ]; private const NUMBER_PADDING_ATTRIBUTES = [ 'before_prefix' => \NumberFormatter::PAD_BEFORE_PREFIX, 'after_prefix' => \NumberFormatter::PAD_AFTER_PREFIX, 'before_suffix' => \NumberFormatter::PAD_BEFORE_SUFFIX, 'after_suffix' => \NumberFormatter::PAD_AFTER_SUFFIX, ]; private const NUMBER_TEXT_ATTRIBUTES = [ 'positive_prefix' => \NumberFormatter::POSITIVE_PREFIX, 'positive_suffix' => \NumberFormatter::POSITIVE_SUFFIX, 'negative_prefix' => \NumberFormatter::NEGATIVE_PREFIX, 'negative_suffix' => \NumberFormatter::NEGATIVE_SUFFIX, 'padding_character' => \NumberFormatter::PADDING_CHARACTER, 'currency_mode' => \NumberFormatter::CURRENCY_CODE, 'default_ruleset' => \NumberFormatter::DEFAULT_RULESET, 'public_rulesets' => \NumberFormatter::PUBLIC_RULESETS, ]; private const NUMBER_SYMBOLS = [ 'decimal_separator' => \NumberFormatter::DECIMAL_SEPARATOR_SYMBOL, 'grouping_separator' => \NumberFormatter::GROUPING_SEPARATOR_SYMBOL, 'pattern_separator' => \NumberFormatter::PATTERN_SEPARATOR_SYMBOL, 'percent' => \NumberFormatter::PERCENT_SYMBOL, 'zero_digit' => \NumberFormatter::ZERO_DIGIT_SYMBOL, 'digit' => \NumberFormatter::DIGIT_SYMBOL, 'minus_sign' => \NumberFormatter::MINUS_SIGN_SYMBOL, 'plus_sign' => \NumberFormatter::PLUS_SIGN_SYMBOL, 'currency' => \NumberFormatter::CURRENCY_SYMBOL, 'intl_currency' => \NumberFormatter::INTL_CURRENCY_SYMBOL, 'monetary_separator' => \NumberFormatter::MONETARY_SEPARATOR_SYMBOL, 'exponential' => \NumberFormatter::EXPONENTIAL_SYMBOL, 'permill' => \NumberFormatter::PERMILL_SYMBOL, 'pad_escape' => \NumberFormatter::PAD_ESCAPE_SYMBOL, 'infinity' => \NumberFormatter::INFINITY_SYMBOL, 'nan' => \NumberFormatter::NAN_SYMBOL, 'significant_digit' => \NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL, 'monetary_grouping_separator' => \NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL, ]; private $dateFormatters = []; private $numberFormatters = []; private $dateFormatterPrototype; private $numberFormatterPrototype; public function __construct(\IntlDateFormatter $dateFormatterPrototype = null, \NumberFormatter $numberFormatterPrototype = null) { $this->dateFormatterPrototype = $dateFormatterPrototype; $this->numberFormatterPrototype = $numberFormatterPrototype; } public function getFilters() { return [ // internationalized names new TwigFilter('country_name', [$this, 'getCountryName']), new TwigFilter('currency_name', [$this, 'getCurrencyName']), new TwigFilter('currency_symbol', [$this, 'getCurrencySymbol']), new TwigFilter('language_name', [$this, 'getLanguageName']), new TwigFilter('locale_name', [$this, 'getLocaleName']), new TwigFilter('timezone_name', [$this, 'getTimezoneName']), // localized formatters new TwigFilter('format_currency', [$this, 'formatCurrency']), new TwigFilter('format_number', [$this, 'formatNumber']), new TwigFilter('format_*_number', [$this, 'formatNumberStyle']), new TwigFilter('format_datetime', [$this, 'formatDateTime'], ['needs_environment' => true]), new TwigFilter('format_date', [$this, 'formatDate'], ['needs_environment' => true]), new TwigFilter('format_time', [$this, 'formatTime'], ['needs_environment' => true]), ]; } public function getFunctions() { return [ // internationalized names new TwigFunction('country_timezones', [$this, 'getCountryTimezones']), ]; } public function getCountryName(string $country, string $locale = null): string { try { return Countries::getName($country, $locale); } catch (MissingResourceException $exception) { return $country; } } public function getCurrencyName(string $currency, string $locale = null): string { try { return Currencies::getName($currency, $locale); } catch (MissingResourceException $exception) { return $currency; } } public function getCurrencySymbol(string $currency, string $locale = null): string { try { return Currencies::getSymbol($currency, $locale); } catch (MissingResourceException $exception) { return $currency; } } public function getLanguageName(string $language, string $locale = null): string { try { return Languages::getName($language, $locale); } catch (MissingResourceException $exception) { return $language; } } public function getLocaleName(string $data, string $locale = null): string { try { return Locales::getName($data, $locale); } catch (MissingResourceException $exception) { return $data; } } public function getTimezoneName(string $timezone, string $locale = null): string { try { return Timezones::getName($timezone, $locale); } catch (MissingResourceException $exception) { return $timezone; } } public function getCountryTimezones(string $country): array { try { return Timezones::forCountryCode($country); } catch (MissingResourceException $exception) { return []; } } public function formatCurrency($amount, string $currency, array $attrs = [], string $locale = null): string { $formatter = $this->createNumberFormatter($locale, 'currency', $attrs); if (false === $ret = $formatter->formatCurrency($amount, $currency)) { throw new RuntimeError('Unable to format the given number as a currency.'); } return $ret; } public function formatNumber($number, array $attrs = [], string $style = 'decimal', string $type = 'default', string $locale = null): string { if (!isset(self::NUMBER_TYPES[$type])) { throw new RuntimeError(sprintf('The type "%s" does not exist, known types are: "%s".', $type, implode('", "', array_keys(self::NUMBER_TYPES)))); } $formatter = $this->createNumberFormatter($locale, $style, $attrs); if (false === $ret = $formatter->format($number, self::NUMBER_TYPES[$type])) { throw new RuntimeError('Unable to format the given number.'); } return $ret; } public function formatNumberStyle(string $style, $number, array $attrs = [], string $type = 'default', string $locale = null): string { return $this->formatNumber($number, $attrs, $style, $type, $locale); } /** * @param \DateTimeInterface|string|null $date A date or null to use the current time * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged */ public function formatDateTime(Environment $env, $date, ?string $dateFormat = 'medium', ?string $timeFormat = 'medium', string $pattern = '', $timezone = null, string $calendar = 'gregorian', string $locale = null): string { $date = \twig_date_converter($env, $date, $timezone); $formatter = $this->createDateFormatter($locale, $dateFormat, $timeFormat, $pattern, $date->getTimezone(), $calendar); if (false === $ret = $formatter->format($date)) { throw new RuntimeError('Unable to format the given date.'); } return $ret; } /** * @param \DateTimeInterface|string|null $date A date or null to use the current time * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged */ public function formatDate(Environment $env, $date, ?string $dateFormat = 'medium', string $pattern = '', $timezone = null, string $calendar = 'gregorian', string $locale = null): string { return $this->formatDateTime($env, $date, $dateFormat, 'none', $pattern, $timezone, $calendar, $locale); } /** * @param \DateTimeInterface|string|null $date A date or null to use the current time * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged */ public function formatTime(Environment $env, $date, ?string $timeFormat = 'medium', string $pattern = '', $timezone = null, string $calendar = 'gregorian', string $locale = null): string { return $this->formatDateTime($env, $date, 'none', $timeFormat, $pattern, $timezone, $calendar, $locale); } private function createDateFormatter(?string $locale, ?string $dateFormat, ?string $timeFormat, string $pattern = '', \DateTimeZone $timezone, string $calendar): \IntlDateFormatter { if (null !== $dateFormat && !isset(self::DATE_FORMATS[$dateFormat])) { throw new RuntimeError(sprintf('The date format "%s" does not exist, known formats are: "%s".', $dateFormat, implode('", "', array_keys(self::DATE_FORMATS)))); } if (null !== $timeFormat && !isset(self::DATE_FORMATS[$timeFormat])) { throw new RuntimeError(sprintf('The time format "%s" does not exist, known formats are: "%s".', $timeFormat, implode('", "', array_keys(self::DATE_FORMATS)))); } if (null === $locale) { $locale = \Locale::getDefault(); } $calendar = 'gregorian' === $calendar ? \IntlDateFormatter::GREGORIAN : \IntlDateFormatter::TRADITIONAL; $dateFormatValue = self::DATE_FORMATS[$dateFormat] ?? null; $timeFormatValue = self::DATE_FORMATS[$timeFormat] ?? null; if ($this->dateFormatterPrototype) { $dateFormatValue = $dateFormatValue ?: $this->dateFormatterPrototype->getDateType(); $timeFormatValue = $timeFormatValue ?: $this->dateFormatterPrototype->getTimeType(); $timezone = $timezone ?: $this->dateFormatterPrototype->getTimeType(); $calendar = $calendar ?: $this->dateFormatterPrototype->getCalendar(); $pattern = $pattern ?: $this->dateFormatterPrototype->getPattern(); } $hash = $locale.'|'.$dateFormatValue.'|'.$timeFormatValue.'|'.$timezone->getName().'|'.$calendar.'|'.$pattern; if (!isset($this->dateFormatters[$hash])) { $this->dateFormatters[$hash] = new \IntlDateFormatter($locale, $dateFormatValue, $timeFormatValue, $timezone, $calendar, $pattern); } return $this->dateFormatters[$hash]; } private function createNumberFormatter(?string $locale, string $style, array $attrs = []): \NumberFormatter { if (!isset(self::NUMBER_STYLES[$style])) { throw new RuntimeError(sprintf('The style "%s" does not exist, known styles are: "%s".', $style, implode('", "', array_keys(self::NUMBER_STYLES)))); } if (null === $locale) { $locale = \Locale::getDefault(); } // textAttrs and symbols can only be set on the prototype as there is probably no // use case for setting it on each call. $textAttrs = []; $symbols = []; if ($this->numberFormatterPrototype) { foreach (self::NUMBER_ATTRIBUTES as $name => $const) { if (!isset($attrs[$name])) { $value = $this->numberFormatterPrototype->getAttribute($const); if ('rounding_mode' === $name) { $value = array_flip(self::NUMBER_ROUNDING_ATTRIBUTES)[$value]; } elseif ('padding_position' === $name) { $value = array_flip(self::NUMBER_PADDING_ATTRIBUTES)[$value]; } $attrs[$name] = $value; } } foreach (self::NUMBER_TEXT_ATTRIBUTES as $name => $const) { $textAttrs[$name] = $this->numberFormatterPrototype->getTextAttribute($const); } foreach (self::NUMBER_SYMBOLS as $name => $const) { $symbols[$name] = $this->numberFormatterPrototype->getSymbol($const); } } ksort($attrs); $hash = $locale.'|'.$style.'|'.json_encode($attrs).'|'.json_encode($textAttrs).'|'.json_encode($symbols); if (!isset($this->numberFormatters[$hash])) { $this->numberFormatters[$hash] = new \NumberFormatter($locale, self::NUMBER_STYLES[$style]); } foreach ($attrs as $name => $value) { if (!isset(self::NUMBER_ATTRIBUTES[$name])) { throw new RuntimeError(sprintf('The number formatter attribute "%s" does not exist, known attributes are: "%s".', $name, implode('", "', array_keys(self::NUMBER_ATTRIBUTES)))); } if ('rounding_mode' === $name) { if (!isset(self::NUMBER_ROUNDING_ATTRIBUTES[$value])) { throw new RuntimeError(sprintf('The number formatter rounding mode "%s" does not exist, known modes are: "%s".', $value, implode('", "', array_keys(self::NUMBER_ROUNDING_ATTRIBUTES)))); } $value = self::NUMBER_ROUNDING_ATTRIBUTES[$value]; } elseif ('padding_position' === $name) { if (!isset(self::NUMBER_PADDING_ATTRIBUTES[$value])) { throw new RuntimeError(sprintf('The number formatter padding position "%s" does not exist, known positions are: "%s".', $value, implode('", "', array_keys(self::NUMBER_PADDING_ATTRIBUTES)))); } $value = self::NUMBER_PADDING_ATTRIBUTES[$value]; } $this->numberFormatters[$hash]->setAttribute(self::NUMBER_ATTRIBUTES[$name], $value); } foreach ($textAttrs as $name => $value) { $this->numberFormatters[$hash]->setTextAttribute(self::NUMBER_TEXT_ATTRIBUTES[$name], $value); } foreach ($symbols as $name => $value) { $this->numberFormatters[$hash]->setSymbol(self::NUMBER_SYMBOLS[$name], $value); } return $this->numberFormatters[$hash]; } } php-twig-2.12.5/extra/intl-extra/tests/000077500000000000000000000000001362457344700177335ustar00rootroot00000000000000php-twig-2.12.5/extra/intl-extra/tests/Fixtures/000077500000000000000000000000001362457344700215445ustar00rootroot00000000000000php-twig-2.12.5/extra/intl-extra/tests/Fixtures/country_name.test000066400000000000000000000004071362457344700251510ustar00rootroot00000000000000--TEST-- "country_name" filter --TEMPLATE-- {{ 'UNKNOWN'|country_name }} {{ 'FR'|country_name }} {{ 'US'|country_name }} {{ 'US'|country_name('fr') }} {{ 'CH'|country_name('fr_CA') }} --DATA-- return []; --EXPECT-- UNKNOWN France United States États-Unis Suisse php-twig-2.12.5/extra/intl-extra/tests/Fixtures/country_timezones.test000066400000000000000000000014771362457344700262560ustar00rootroot00000000000000--TEST-- "country_timezones" function --TEMPLATE-- {{ country_timezones('UNKNOWN')|length }} {{ country_timezones('FR')|join(', ') }} {{ country_timezones('US')|join(', ') }} --DATA-- return []; --EXPECT-- 0 Europe/Paris America/Adak, America/Anchorage, America/Boise, America/Chicago, America/Denver, America/Detroit, America/Indiana/Knox, America/Indiana/Marengo, America/Indiana/Petersburg, America/Indiana/Tell_City, America/Indiana/Vevay, America/Indiana/Vincennes, America/Indiana/Winamac, America/Indianapolis, America/Juneau, America/Kentucky/Monticello, America/Los_Angeles, America/Louisville, America/Menominee, America/Metlakatla, America/New_York, America/Nome, America/North_Dakota/Beulah, America/North_Dakota/Center, America/North_Dakota/New_Salem, America/Phoenix, America/Sitka, America/Yakutat, Pacific/Honolulu php-twig-2.12.5/extra/intl-extra/tests/Fixtures/currency_name.test000066400000000000000000000004151362457344700252770ustar00rootroot00000000000000--TEST-- "currency_name" filter --TEMPLATE-- {{ 'UNKNOWN'|currency_name }} {{ 'EUR'|currency_name }} {{ 'JPY'|currency_name }} {{ 'EUR'|currency_name('fr') }} {{ 'JPY'|currency_name('fr_FR') }} --DATA-- return []; --EXPECT-- UNKNOWN Euro Japanese Yen euro yen japonais php-twig-2.12.5/extra/intl-extra/tests/Fixtures/currency_symbol.test000066400000000000000000000002651362457344700256670ustar00rootroot00000000000000--TEST-- "currency_symbol" filter --TEMPLATE-- {{ 'UNKNOWN'|currency_symbol }} {{ 'EUR'|currency_symbol }} {{ 'JPY'|currency_symbol }} --DATA-- return []; --EXPECT-- UNKNOWN € ¥ php-twig-2.12.5/extra/intl-extra/tests/Fixtures/format_currency.test000066400000000000000000000006241362457344700256510ustar00rootroot00000000000000--TEST-- "format_currency" filter --TEMPLATE-- {{ '1000000'|format_currency('EUR') }} {{ '1000000'|format_currency('EUR', locale='de') }} {{ '1000000'|format_currency('EUR', {fraction_digit: 2}) }} {{ '12.345'|format_currency('EUR', {rounding_mode: 'floor'}) }} {{ '125000'|format_currency('YEN') }} --DATA-- return []; --EXPECT-- €1,000,000.00 1.000.000,00 € €1,000,000.00 €12.34 YEN125,000.00 php-twig-2.12.5/extra/intl-extra/tests/Fixtures/format_date.test000066400000000000000000000013721362457344700247350ustar00rootroot00000000000000--TEST-- "format_date" filter --TEMPLATE-- {{ '2019-08-07 23:39:12'|format_datetime() }} {{ '2019-08-07 23:39:12'|format_datetime(locale='fr') }} {{ '2019-08-07 23:39:12'|format_datetime('none', 'short', locale='fr') }} {{ '2019-08-07 23:39:12'|format_datetime('short', 'none', locale='fr') }} {{ '2019-08-07 23:39:12'|format_datetime('full', 'full', locale='fr') }} {{ '2019-08-07 23:39:12'|format_datetime(pattern="hh 'oclock' a, zzzz") }} {{ '2019-08-07 23:39:12'|format_date }} {{ '2019-08-07 23:39:12'|format_date(locale='fr') }} {{ '2019-08-07 23:39:12'|format_time }} --DATA-- return []; --EXPECT-- Aug 7, 2019, 11:39:12 PM 7 août 2019 23:39:12 23:39 07/08/2019 mercredi 7 août 2019 23:39:12 UTC 11 oclock PM, GMT Aug 7, 2019 7 août 2019 11:39:12 PM php-twig-2.12.5/extra/intl-extra/tests/Fixtures/format_number.test000066400000000000000000000013661362457344700253130ustar00rootroot00000000000000--TEST-- "format_number" filter --TEMPLATE-- {{ '12.345'|format_number }} {{ '12.345'|format_number(locale='fr') }} {{ '12.345'|format_number(style='percent') }} {{ '12.345'|format_number(style='spellout') }} {{ '12.345'|format_percent_number }} {{ '12.345'|format_spellout_number }} {{ '80.345'|format_spellout_number(locale='fr_FR') }} {{ '80.345'|format_spellout_number(locale='fr_CH') }} {{ '12'|format_duration_number }} {{ '0.12'|format_percent_number({fraction_digit: 1}) }} {{ '0.12345'|format_percent_number({rounding_mode: 'ceiling'}) }} --DATA-- return []; --EXPECT-- 12.345 12,345 1,234% twelve point three four five 1,234% twelve point three four five quatre-vingts virgule trois quatre cinq huitante virgule trois quatre cinq 12 sec. 12.0% 13% php-twig-2.12.5/extra/intl-extra/tests/Fixtures/language_name.test000066400000000000000000000004761362457344700252370ustar00rootroot00000000000000--TEST-- "language_name" filter --TEMPLATE-- {{ 'UNKNOWN'|language_name }} {{ 'de'|language_name }} {{ 'fr'|language_name }} {{ 'de'|language_name('fr') }} {{ 'fr'|language_name('fr_FR') }} {{ 'fr_CA'|language_name('fr_FR') }} --DATA-- return []; --EXPECT-- UNKNOWN German French allemand français français canadien php-twig-2.12.5/extra/intl-extra/tests/Fixtures/locale_name.test000066400000000000000000000004601362457344700247040ustar00rootroot00000000000000--TEST-- "locale_name" filter --TEMPLATE-- {{ 'UNKNOWN'|locale_name }} {{ 'de'|locale_name }} {{ 'fr'|locale_name }} {{ 'de'|locale_name('fr') }} {{ 'fr'|locale_name('fr_FR') }} {{ 'fr_CA'|locale_name('fr_FR') }} --DATA-- return []; --EXPECT-- UNKNOWN German French allemand français français (Canada) php-twig-2.12.5/extra/intl-extra/tests/Fixtures/timezone_name.test000066400000000000000000000005311362457344700252760ustar00rootroot00000000000000--TEST-- "timezone_name" filter --TEMPLATE-- {{ 'UNKNOWN'|timezone_name }} {{ 'Europe/Paris'|timezone_name }} {{ 'America/Los_Angeles'|timezone_name }} {{ 'America/Los_Angeles'|timezone_name('fr') }} --DATA-- return []; --EXPECT-- UNKNOWN Central European Time (Paris) Pacific Time (Los Angeles) heure du Pacifique nord-américain (Los Angeles) php-twig-2.12.5/extra/intl-extra/tests/IntegrationTest.php000066400000000000000000000010551362457344700235700ustar00rootroot00000000000000setTextAttribute(\NumberFormatter::POSITIVE_PREFIX, '++'); $numberFormatterProto->setAttribute(\NumberFormatter::FRACTION_DIGITS, 1); $ext = new IntlExtension($dateFormatterProto, $numberFormatterProto); $this->assertSame('++12,3', $ext->formatNumber('12.3456')); } } php-twig-2.12.5/extra/markdown-extra/000077500000000000000000000000001362457344700174455ustar00rootroot00000000000000php-twig-2.12.5/extra/markdown-extra/.gitignore000066400000000000000000000000701362457344700214320ustar00rootroot00000000000000vendor/ composer.lock phpunit.xml .phpunit.result.cache php-twig-2.12.5/extra/markdown-extra/LICENSE000066400000000000000000000020511362457344700204500ustar00rootroot00000000000000Copyright (c) 2019-2020 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. php-twig-2.12.5/extra/markdown-extra/README.md000066400000000000000000000005431362457344700207260ustar00rootroot00000000000000Twig Markdown Extension ======================= This package is a Twig extension that provides the following: * [`markdown_to_html`][1] filter: generates HTML from a Markdown block; * [`html_to_markdown`][2] filter: generates Markdown from an HTML block. [1]: https://twig.symfony.com/markdown_to_html [2]: https://twig.symfony.com/html_to_markdown php-twig-2.12.5/extra/markdown-extra/composer.json000066400000000000000000000020541362457344700221700ustar00rootroot00000000000000{ "name": "twig/markdown-extra", "type": "library", "description": "A Twig extension for Markdown", "keywords": ["twig", "html", "markdown"], "homepage": "https://twig.symfony.com", "license": "MIT", "authors": [ { "name": "Fabien Potencier", "email": "fabien@symfony.com", "homepage": "http://fabien.potencier.org", "role": "Lead Developer" } ], "require": { "php": "^7.1.3", "twig/twig": "^2.4|^3.0" }, "require-dev": { "symfony/phpunit-bridge": "^4.4|^5.0", "erusev/parsedown": "^1.7", "league/commonmark": "^1.0", "league/html-to-markdown": "^4.8", "michelf/php-markdown": "^1.8" }, "autoload": { "psr-4" : { "Twig\\Extra\\Markdown\\" : "src/" } }, "autoload-dev": { "psr-4" : { "Twig\\Extra\\Markdown\\Tests\\" : "tests/" } }, "extra": { "branch-alias": { "dev-master": "2.12-dev" } } } php-twig-2.12.5/extra/markdown-extra/phpunit.xml.dist000066400000000000000000000015001362457344700226140ustar00rootroot00000000000000 ./tests/ ./ ./tests ./vendor php-twig-2.12.5/extra/markdown-extra/src/000077500000000000000000000000001362457344700202345ustar00rootroot00000000000000php-twig-2.12.5/extra/markdown-extra/src/DefaultMarkdown.php000066400000000000000000000020721362457344700240350ustar00rootroot00000000000000converter = new ErusevMarkdown(); } elseif (class_exists(CommonMarkConverter::class)) { $this->converter = new LeagueMarkdown(); } elseif (class_exists(MarkdownExtra::class)) { $this->converter = new MichelfMarkdown(); } else { throw new \LogicException('You cannot use the "markdown_to_html" filter as no Markdown library is available; try running "composer require erusev/parsedown".'); } } public function convert(string $body): string { return $this->converter->convert($body); } } php-twig-2.12.5/extra/markdown-extra/src/ErusevMarkdown.php000066400000000000000000000010711362457344700237200ustar00rootroot00000000000000converter = $converter ?: new Parsedown(); } public function convert(string $body): string { return $this->converter->text($body); } } php-twig-2.12.5/extra/markdown-extra/src/LeagueMarkdown.php000066400000000000000000000011621362457344700236520ustar00rootroot00000000000000converter = $converter ?: new CommonMarkConverter(); } public function convert(string $body): string { return $this->converter->convertToHtml($body); } } php-twig-2.12.5/extra/markdown-extra/src/MarkdownExtension.php000066400000000000000000000025221362457344700244250ustar00rootroot00000000000000 ['all']]), new TwigFilter('html_to_markdown', 'Twig\\Extra\\Markdown\\twig_html_to_markdown', ['is_safe' => ['all']]), ]; } } function twig_html_to_markdown(string $body, array $options = []): string { static $converters; if (!class_exists(HtmlConverter::class)) { throw new \LogicException('You cannot use the "html_to_markdown" filter as league/html-to-markdown is not installed; try running "composer require league/html-to-markdown".'); } $options = $options + [ 'hard_break' => true, 'strip_tags' => true, 'remove_nodes' => 'head style', ]; if (!isset($converters[$key = serialize($options)])) { $converters[$key] = new HtmlConverter($options); } return $converters[$key]->convert($body); } php-twig-2.12.5/extra/markdown-extra/src/MarkdownInterface.php000066400000000000000000000004751362457344700243560ustar00rootroot00000000000000converter = $converter; } public function convert(string $body): string { // remove indentation if ($white = substr($body, 0, strspn($body, " \t\r\n\0\x0B"))) { $body = preg_replace("{^$white}m", '', $body); } return $this->converter->convert($body); } } php-twig-2.12.5/extra/markdown-extra/src/MichelfMarkdown.php000066400000000000000000000013111362457344700240130ustar00rootroot00000000000000hard_wrap = true; } $this->converter = $converter; } public function convert(string $body): string { return $this->converter->defaultTransform($body); } } php-twig-2.12.5/extra/markdown-extra/tests/000077500000000000000000000000001362457344700206075ustar00rootroot00000000000000php-twig-2.12.5/extra/markdown-extra/tests/Fixtures/000077500000000000000000000000001362457344700224205ustar00rootroot00000000000000php-twig-2.12.5/extra/markdown-extra/tests/Fixtures/html_to_markdown.test000066400000000000000000000007541362457344700266770ustar00rootroot00000000000000--TEST-- "html_to_markdown" filter --TEMPLATE-- {% apply html_to_markdown %}

    Hello

    Great!

    {% endapply %} {% apply html_to_markdown({hard_break: false}) %} Great
    Break {% endapply %} {{ include('html')|html_to_markdown }} --TEMPLATE(html)--

    Hello

    Great!

    --DATA-- return [] --EXPECT-- Hello ===== **Great!** Great Break Hello ===== **Great!** php-twig-2.12.5/extra/markdown-extra/tests/FunctionalTest.php000066400000000000000000000042231362457344700242630ustar00rootroot00000000000000 $template, 'html' => <<addExtension(new MarkdownExtension()); $twig->addRuntimeLoader(new class($class) implements RuntimeLoaderInterface { private $class; public function __construct(string $class) { $this->class = $class; } public function load($c) { if (MarkdownRuntime::class === $c) { return new $c(new $this->class()); } } }); $this->assertRegExp('{'.$expected.'}m', trim($twig->render('index'))); } } public function getMarkdownTests() { return [ [<<Hello\n+

    Great!

    "], [<<Hello\n+

    Great!

    "], ["{{ include('html')|markdown_to_html }}", "

    Hello

    \n+

    Great!

    "], ]; } } php-twig-2.12.5/extra/markdown-extra/tests/IntegrationTest.php000066400000000000000000000010751362457344700244460ustar00rootroot00000000000000 ./tests/ ./ ./tests ./vendor php-twig-2.12.5/extra/string-extra/src/000077500000000000000000000000001362457344700177205ustar00rootroot00000000000000php-twig-2.12.5/extra/string-extra/src/StringExtension.php000066400000000000000000000012261362457344700235750ustar00rootroot00000000000000 ./tests/ ./src/ php-twig-2.12.5/extra/twig-extra-bundle/src/000077500000000000000000000000001362457344700206335ustar00rootroot00000000000000php-twig-2.12.5/extra/twig-extra-bundle/src/DependencyInjection/000077500000000000000000000000001362457344700245545ustar00rootroot00000000000000php-twig-2.12.5/extra/twig-extra-bundle/src/DependencyInjection/Compiler/000077500000000000000000000000001362457344700263265ustar00rootroot00000000000000MissingExtensionSuggestorPass.php000066400000000000000000000020241362457344700350160ustar00rootroot00000000000000php-twig-2.12.5/extra/twig-extra-bundle/src/DependencyInjection/Compiler * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Twig\Extra\TwigExtraBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Reference; class MissingExtensionSuggestorPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { if ($container->getParameter('kernel.debug')) { $container->getDefinition('twig') ->addMethodCall('registerUndefinedFilterCallback', [[new Reference('twig.missing_extension_suggestor'), 'suggestFilter']]) ->addMethodCall('registerUndefinedFunctionCallback', [[new Reference('twig.missing_extension_suggestor'), 'suggestFunction']]) ; } } } php-twig-2.12.5/extra/twig-extra-bundle/src/DependencyInjection/Configuration.php000066400000000000000000000017411362457344700300770ustar00rootroot00000000000000getRootNode(); foreach (Extensions::getClasses() as $name => $class) { $rootNode ->children() ->arrayNode($name) ->{class_exists($class) ? 'canBeDisabled' : 'canBeEnabled'}() ->end() ->end() ; } return $treeBuilder; } } php-twig-2.12.5/extra/twig-extra-bundle/src/DependencyInjection/TwigExtraExtension.php000066400000000000000000000024271362457344700311050ustar00rootroot00000000000000 */ class TwigExtraExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { $loader = new XmlFileLoader($container, new FileLocator(\dirname(__DIR__).'/Resources/config')); $configuration = $this->getConfiguration($configs, $container); $config = $this->processConfiguration($configuration, $configs); if ($container->getParameter('kernel.debug')) { $loader->load('suggestor.xml'); } foreach (array_keys(Extensions::getClasses()) as $extension) { if ($this->isConfigEnabled($container, $config[$extension])) { $loader->load($extension.'.xml'); } } } } php-twig-2.12.5/extra/twig-extra-bundle/src/Extensions.php000066400000000000000000000065041362457344700235100ustar00rootroot00000000000000 [ 'name' => 'html', 'class' => HtmlExtension::class, 'class_name' => 'HtmlExtension', 'package' => 'twig/html-extra', 'filters' => ['data_uri'], 'functions' => ['html_classes'], ], 'markdown' => [ 'name' => 'markdown', 'class' => MarkdownExtension::class, 'class_name' => 'MarkdownExtension', 'package' => 'twig/markdown-extra', 'filters' => ['html_to_markdown', 'markdown_to_html'], 'functions' => [], ], 'intl' => [ 'name' => 'intl', 'class' => IntlExtension::class, 'class_name' => 'IntlExtension', 'package' => 'twig/intl-extra', 'filters' => ['country_name', 'currency_name', 'currency_symbol', 'language_name', 'locale_name', 'timezone_name', 'format_currency', 'format_number', 'format_decimal_number', 'format_currency_number', 'format_percent_number', 'format_scientific_number', 'format_spellout_number', 'format_ordinal_number', 'format_duration_number', 'format_date', 'format_datetime', 'format_time', ], 'functions' => ['country_timezones'], ], 'cssinliner' => [ 'name' => 'cssinliner', 'class' => CssInlinerExtension::class, 'class_name' => 'CssInlinerExtension', 'package' => 'twig/cssinliner-extra', 'filters' => ['inline_css'], 'functions' => [], ], 'inky' => [ 'name' => 'inky', 'class' => InkyExtension::class, 'class_name' => 'InkyExtension', 'package' => 'twig/inky-extra', 'filters' => ['inky_to_html'], 'functions' => [], ], 'string' => [ 'name' => 'string', 'class' => StringExtension::class, 'class_name' => 'StringExtension', 'package' => 'twig/string-extra', 'filters' => ['u'], 'functions' => [], ], ]; public static function getClasses(): array { return array_column(self::EXTENSIONS, 'class', 'name'); } public static function getFilter(string $name): array { foreach (self::EXTENSIONS as $extension) { if (\in_array($name, $extension['filters'])) { return [$extension['class_name'], $extension['package']]; } } return []; } public static function getFunction(string $name): array { foreach (self::EXTENSIONS as $extension) { if (\in_array($name, $extension['functions'])) { return [$extension['class_name'], $extension['package']]; } } return []; } } php-twig-2.12.5/extra/twig-extra-bundle/src/MissingExtensionSuggestor.php000066400000000000000000000017371362457344700265650ustar00rootroot00000000000000 php-twig-2.12.5/extra/twig-extra-bundle/src/Resources/config/html.xml000066400000000000000000000007661362457344700255510ustar00rootroot00000000000000 php-twig-2.12.5/extra/twig-extra-bundle/src/Resources/config/inky.xml000066400000000000000000000007661362457344700255570ustar00rootroot00000000000000 php-twig-2.12.5/extra/twig-extra-bundle/src/Resources/config/intl.xml000066400000000000000000000007661362457344700255530ustar00rootroot00000000000000 php-twig-2.12.5/extra/twig-extra-bundle/src/Resources/config/markdown.xml000066400000000000000000000014661362457344700264250ustar00rootroot00000000000000 php-twig-2.12.5/extra/twig-extra-bundle/src/Resources/config/string.xml000066400000000000000000000007741362457344700261120ustar00rootroot00000000000000 php-twig-2.12.5/extra/twig-extra-bundle/src/Resources/config/suggestor.xml000066400000000000000000000007371362457344700266250ustar00rootroot00000000000000 php-twig-2.12.5/extra/twig-extra-bundle/src/TwigExtraBundle.php000066400000000000000000000012231362457344700244120ustar00rootroot00000000000000addCompilerPass(new MissingExtensionSuggestorPass()); } } php-twig-2.12.5/lib/000077500000000000000000000000001362457344700141255ustar00rootroot00000000000000php-twig-2.12.5/lib/Twig/000077500000000000000000000000001362457344700150375ustar00rootroot00000000000000php-twig-2.12.5/lib/Twig/BaseNodeVisitor.php000066400000000000000000000007131362457344700206110ustar00rootroot00000000000000 ./tests/ ./src/ php-twig-2.12.5/src/000077500000000000000000000000001362457344700141465ustar00rootroot00000000000000php-twig-2.12.5/src/Cache/000077500000000000000000000000001362457344700151515ustar00rootroot00000000000000php-twig-2.12.5/src/Cache/CacheInterface.php000066400000000000000000000026761362457344700205210ustar00rootroot00000000000000 */ interface CacheInterface { /** * Generates a cache key for the given template class name. * * @param string $name The template name * @param string $className The template class name * * @return string */ public function generateKey($name, $className); /** * Writes the compiled template to cache. * * @param string $key The cache key * @param string $content The template representation as a PHP class */ public function write($key, $content); /** * Loads a template from the cache. * * @param string $key The cache key */ public function load($key); /** * Returns the modification timestamp of a key. * * @param string $key The cache key * * @return int */ public function getTimestamp($key); } class_alias('Twig\Cache\CacheInterface', 'Twig_CacheInterface'); php-twig-2.12.5/src/Cache/FilesystemCache.php000066400000000000000000000050601362457344700207330ustar00rootroot00000000000000 */ class FilesystemCache implements CacheInterface { const FORCE_BYTECODE_INVALIDATION = 1; private $directory; private $options; /** * @param string $directory The root cache directory * @param int $options A set of options */ public function __construct($directory, $options = 0) { $this->directory = rtrim($directory, '\/').'/'; $this->options = $options; } public function generateKey($name, $className) { $hash = hash('sha256', $className); return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php'; } public function load($key) { if (file_exists($key)) { @include_once $key; } } public function write($key, $content) { $dir = \dirname($key); if (!is_dir($dir)) { if (false === @mkdir($dir, 0777, true)) { clearstatcache(true, $dir); if (!is_dir($dir)) { throw new \RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir)); } } } elseif (!is_writable($dir)) { throw new \RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir)); } $tmpFile = tempnam($dir, basename($key)); if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) { @chmod($key, 0666 & ~umask()); if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) { // Compile cached file into bytecode cache if (\function_exists('opcache_invalidate') && filter_var(ini_get('opcache.enable'), FILTER_VALIDATE_BOOLEAN)) { @opcache_invalidate($key, true); } elseif (\function_exists('apc_compile_file')) { apc_compile_file($key); } } return; } throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $key)); } public function getTimestamp($key) { if (!file_exists($key)) { return 0; } return (int) @filemtime($key); } } class_alias('Twig\Cache\FilesystemCache', 'Twig_Cache_Filesystem'); php-twig-2.12.5/src/Cache/NullCache.php000066400000000000000000000012501362457344700175160ustar00rootroot00000000000000 */ final class NullCache implements CacheInterface { public function generateKey($name, $className) { return ''; } public function write($key, $content) { } public function load($key) { } public function getTimestamp($key) { return 0; } } class_alias('Twig\Cache\NullCache', 'Twig_Cache_Null'); php-twig-2.12.5/src/Compiler.php000066400000000000000000000127621362457344700164410ustar00rootroot00000000000000 */ class Compiler { private $lastLine; private $source; private $indentation; private $env; private $debugInfo = []; private $sourceOffset; private $sourceLine; private $varNameSalt = 0; public function __construct(Environment $env) { $this->env = $env; } /** * Returns the environment instance related to this compiler. * * @return 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 int $indentation The current indentation * * @return $this */ public function compile(Node $node, $indentation = 0) { $this->lastLine = null; $this->source = ''; $this->debugInfo = []; $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(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(var_export($value, true)); 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(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'); php-twig-2.12.5/src/Environment.php000066400000000000000000000675511362457344700172010ustar00rootroot00000000000000 */ class Environment { const VERSION = '2.12.5'; const VERSION_ID = 21205; const MAJOR_VERSION = 2; const MINOR_VERSION = 12; 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 = []; private $resolvedGlobals; private $loadedTemplates; private $strictVariables; private $templateClassPrefix = '__TwigTemplate_'; private $originalCache; private $extensionSet; private $runtimeLoaders = []; private $runtimes = []; private $optionsHash; /** * 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\CacheInterface 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). */ public function __construct(LoaderInterface $loader, $options = []) { $this->setLoader($loader); $options = array_merge([ 'debug' => false, 'charset' => 'UTF-8', 'base_template_class' => Template::class, 'strict_variables' => false, 'autoescape' => 'html', 'cache' => false, 'auto_reload' => null, 'optimizations' => -1, ], $options); $this->debug = (bool) $options['debug']; $this->setCharset($options['charset']); $this->baseTemplateClass = '\\'.ltrim($options['base_template_class'], '\\'); if ('\\'.Template::class !== $this->baseTemplateClass && '\Twig_Template' !== $this->baseTemplateClass) { @trigger_error('The "base_template_class" option on '.__CLASS__.' is deprecated since Twig 2.7.0.', E_USER_DEPRECATED); } $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 ExtensionSet(); $this->addExtension(new CoreExtension()); $this->addExtension(new EscaperExtension($options['autoescape'])); $this->addExtension(new OptimizerExtension($options['optimizations'])); } /** * Gets the base template class for compiled templates. * * @return string The base template class name */ public function getBaseTemplateClass() { if (1 > \func_num_args() || \func_get_arg(0)) { @trigger_error('The '.__METHOD__.' is deprecated since Twig 2.7.0.', E_USER_DEPRECATED); } return $this->baseTemplateClass; } /** * Sets the base template class for compiled templates. * * @param string $class The base template class name */ public function setBaseTemplateClass($class) { @trigger_error('The '.__METHOD__.' is deprecated since Twig 2.7.0.', E_USER_DEPRECATED); $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 CacheInterface|string|false A Twig\Cache\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 CacheInterface|string|false $cache A Twig\Cache\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 FilesystemCache($cache); } elseif (false === $cache) { $this->originalCache = $cache; $this->cache = new NullCache(); } elseif ($cache instanceof CacheInterface) { $this->originalCache = $this->cache = $cache; } else { throw new \LogicException(sprintf('Cache can only be a string, false, or a \Twig\Cache\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 * * @internal */ 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|TemplateWrapper $name The template name * @param array $context An array of parameters to pass to the template * * @return string The rendered template * * @throws LoaderError When the template cannot be found * @throws SyntaxError When an error occurred during compilation * @throws RuntimeError When an error occurred during rendering */ public function render($name, array $context = []) { return $this->load($name)->render($context); } /** * Displays a template. * * @param string|TemplateWrapper $name The template name * @param array $context An array of parameters to pass to the template * * @throws LoaderError When the template cannot be found * @throws SyntaxError When an error occurred during compilation * @throws RuntimeError When an error occurred during rendering */ public function display($name, array $context = []) { $this->load($name)->display($context); } /** * Loads a template. * * @param string|TemplateWrapper $name The template name * * @throws LoaderError When the template cannot be found * @throws RuntimeError When a previously generated cache is corrupted * @throws SyntaxError When an error occurred during compilation * * @return TemplateWrapper */ public function load($name) { if ($name instanceof TemplateWrapper) { return $name; } if ($name instanceof Template) { @trigger_error('Passing a \Twig\Template instance to '.__METHOD__.' is deprecated since Twig 2.7.0, use \Twig\TemplateWrapper instead.', E_USER_DEPRECATED); return new TemplateWrapper($this, $name); } return new 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 Template A template instance representing the given template name * * @throws LoaderError When the template cannot be found * @throws RuntimeError When a previously generated cache is corrupted * @throws SyntaxError When an error occurred during compilation * * @internal */ public function loadTemplate($name, $index = null) { return $this->loadClass($this->getTemplateClass($name), $name, $index); } /** * @internal */ public function loadClass($cls, $name, $index = null) { $mainCls = $cls; if (null !== $index) { $cls .= '___'.$index; } 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); } $source = null; 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 RuntimeError(sprintf('Failed to load Twig template "%s", index "%s": cache might be corrupted.', $name, $index), -1, $source); } } } // to be removed in 3.0 $this->extensionSet->initRuntime($this); return $this->loadedTemplates[$cls] = new $cls($this); } /** * Creates a template from source. * * This method should not be used as a generic way to load templates. * * @param string $template The template source * @param string $name An optional name of the template to be used in error messages * * @return TemplateWrapper A template instance representing the given template name * * @throws LoaderError When the template cannot be found * @throws SyntaxError When an error occurred during compilation */ public function createTemplate($template, string $name = null) { $hash = hash('sha256', $template, false); if (null !== $name) { $name = sprintf('%s (string template %s)', $name, $hash); } else { $name = sprintf('__string_template__%s', $hash); } $loader = new ChainLoader([ new ArrayLoader([$name => $template]), $current = $this->getLoader(), ]); $this->setLoader($loader); try { return new TemplateWrapper($this, $this->loadTemplate($name)); } finally { $this->setLoader($current); } } /** * 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 load() 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|TemplateWrapper|array $names A template or an array of templates to try consecutively * * @return TemplateWrapper|Template * * @throws LoaderError When none of the templates can be found * @throws SyntaxError When an error occurred during compilation */ public function resolveTemplate($names) { if (!\is_array($names)) { $names = [$names]; } foreach ($names as $name) { if ($name instanceof Template) { return $name; } if ($name instanceof TemplateWrapper) { return $name; } try { return $this->loadTemplate($name); } catch (LoaderError $e) { if (1 === \count($names)) { throw $e; } } } throw new LoaderError(sprintf('Unable to find one of the following templates: "%s".', implode('", "', $names))); } public function setLexer(Lexer $lexer) { $this->lexer = $lexer; } /** * Tokenizes a source code. * * @return TokenStream * * @throws SyntaxError When the code is syntactically wrong */ public function tokenize(Source $source) { if (null === $this->lexer) { $this->lexer = new Lexer($this); } return $this->lexer->tokenize($source); } public function setParser(Parser $parser) { $this->parser = $parser; } /** * Converts a token stream to a node tree. * * @return ModuleNode * * @throws SyntaxError When the token stream is syntactically or semantically wrong */ public function parse(TokenStream $stream) { if (null === $this->parser) { $this->parser = new Parser($this); } return $this->parser->parse($stream); } public function setCompiler(Compiler $compiler) { $this->compiler = $compiler; } /** * Compiles a node and returns the PHP code. * * @return string The compiled PHP source code */ public function compile(Node $node) { if (null === $this->compiler) { $this->compiler = new Compiler($this); } return $this->compiler->compile($node)->getSource(); } /** * Compiles a template source code. * * @return string The compiled PHP source code * * @throws SyntaxError When there was an error during tokenizing, parsing or compiling */ public function compileSource(Source $source) { try { return $this->compile($this->parse($this->tokenize($source))); } catch (Error $e) { $e->setSourceContext($source); throw $e; } catch (\Exception $e) { throw new SyntaxError(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $source, $e); } } public function setLoader(LoaderInterface $loader) { $this->loader = $loader; } /** * Gets the Loader instance. * * @return 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(RuntimeLoaderInterface $loader) { $this->runtimeLoaders[] = $loader; } /** * Gets an extension by class name. * * @param string $class The extension class name * * @return 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 RuntimeError 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 RuntimeError(sprintf('Unable to load the "%s" runtime.', $class)); } public function addExtension(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 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(TokenParserInterface $parser) { $this->extensionSet->addTokenParser($parser); } /** * Gets the registered Token Parsers. * * @return TokenParserInterface[] * * @internal */ public function getTokenParsers() { return $this->extensionSet->getTokenParsers(); } /** * Gets registered tags. * * @return TokenParserInterface[] * * @internal */ public function getTags() { $tags = []; foreach ($this->getTokenParsers() as $parser) { $tags[$parser->getTag()] = $parser; } return $tags; } public function addNodeVisitor(NodeVisitorInterface $visitor) { $this->extensionSet->addNodeVisitor($visitor); } /** * Gets the registered Node Visitors. * * @return NodeVisitorInterface[] * * @internal */ public function getNodeVisitors() { return $this->extensionSet->getNodeVisitors(); } public function addFilter(TwigFilter $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 TwigFilter|false * * @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 TwigFilter[] * * @see registerUndefinedFilterCallback * * @internal */ public function getFilters() { return $this->extensionSet->getFilters(); } public function addTest(TwigTest $test) { $this->extensionSet->addTest($test); } /** * Gets the registered Tests. * * @return TwigTest[] * * @internal */ public function getTests() { return $this->extensionSet->getTests(); } /** * Gets a test by name. * * @param string $name The test name * * @return TwigTest|false * * @internal */ public function getTest($name) { return $this->extensionSet->getTest($name); } public function addFunction(TwigFunction $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 TwigFunction|false * * @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 TwigFunction[] * * @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(':', [ $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'); php-twig-2.12.5/src/Error/000077500000000000000000000000001362457344700152375ustar00rootroot00000000000000php-twig-2.12.5/src/Error/Error.php000066400000000000000000000173171362457344700170520ustar00rootroot00000000000000 */ class Error extends \Exception { private $lineno; private $name; private $rawMessage; private $sourcePath; private $sourceCode; /** * Constructor. * * Set the line number to -1 to enable its automatic guessing. * Set the name to null to enable its automatic guessing. * * @param string $message The error message * @param int $lineno The template line where the error occurred * @param Source|string|null $source The source context where the error occurred * @param \Exception $previous The previous exception */ public function __construct(string $message, int $lineno = -1, $source = null, \Exception $previous = null) { parent::__construct('', 0, $previous); if (null === $source) { $name = null; } elseif (!$source instanceof Source && !$source instanceof \Twig_Source) { @trigger_error(sprintf('Passing a string as a source to %s is deprecated since Twig 2.6.1; pass a Twig\Source instance instead.', __CLASS__), E_USER_DEPRECATED); $name = $source; } else { $name = $source->getName(); $this->sourceCode = $source->getCode(); $this->sourcePath = $source->getPath(); } $this->lineno = $lineno; $this->name = $name; $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 Source|null */ public function getSourceContext() { return $this->name ? new Source($this->sourceCode, $this->name, $this->sourcePath) : null; } /** * Sets the source context of the Twig template where the error occurred. */ public function setSourceContext(Source $source = null) { if (null === $source) { $this->sourceCode = $this->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 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 = [$e = $this]; while ($e = $e->getPrevious()) { $exceptions[] = $e; } while ($e = array_pop($exceptions)) { $traces = $e->getTrace(); array_unshift($traces, ['file' => $e->getFile(), 'line' => $e->getLine()]); while ($trace = array_shift($traces)) { if (!isset($trace['file']) || !isset($trace['line']) || $file != $trace['file']) { continue; } foreach ($template->getDebugInfo() as $codeLine => $templateLine) { if ($codeLine <= $trace['line']) { // update template line $this->lineno = $templateLine; return; } } } } } } class_alias('Twig\Error\Error', 'Twig_Error'); php-twig-2.12.5/src/Error/LoaderError.php000066400000000000000000000007001362457344700201650ustar00rootroot00000000000000 */ class LoaderError extends Error { } class_alias('Twig\Error\LoaderError', 'Twig_Error_Loader'); php-twig-2.12.5/src/Error/RuntimeError.php000066400000000000000000000007141362457344700204070ustar00rootroot00000000000000 */ class RuntimeError extends Error { } class_alias('Twig\Error\RuntimeError', 'Twig_Error_Runtime'); php-twig-2.12.5/src/Error/SyntaxError.php000066400000000000000000000023161362457344700202520ustar00rootroot00000000000000 */ class SyntaxError extends Error { /** * Tweaks the error message to include suggestions. * * @param string $name The original name of the item that does not exist * @param array $items An array of possible items */ public function addSuggestions($name, array $items) { $alternatives = []; 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\SyntaxError', 'Twig_Error_Syntax'); php-twig-2.12.5/src/ExpressionParser.php000066400000000000000000000772171362457344700202110ustar00rootroot00000000000000 * * @internal */ class ExpressionParser { const OPERATOR_LEFT = 1; const OPERATOR_RIGHT = 2; private $parser; private $env; private $unaryOperators; private $binaryOperators; public function __construct(Parser $parser, Environment $env) { $this->parser = $parser; $this->env = $env; $this->unaryOperators = $env->getUnaryOperators(); $this->binaryOperators = $env->getBinaryOperators(); } public function parseExpression($precedence = 0, $allowArrow = false) { if ($allowArrow && $arrow = $this->parseArrow()) { return $arrow; } $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; } /** * @return ArrowFunctionExpression|null */ private function parseArrow() { $stream = $this->parser->getStream(); // short array syntax (one argument, no parentheses)? if ($stream->look(1)->test(/* Token::ARROW_TYPE */ 12)) { $line = $stream->getCurrent()->getLine(); $token = $stream->expect(/* Token::NAME_TYPE */ 5); $names = [new AssignNameExpression($token->getValue(), $token->getLine())]; $stream->expect(/* Token::ARROW_TYPE */ 12); return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line); } // first, determine if we are parsing an arrow function by finding => (long form) $i = 0; if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { return null; } ++$i; while (true) { // variable name ++$i; if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ',')) { break; } ++$i; } if (!$stream->look($i)->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) { return null; } ++$i; if (!$stream->look($i)->test(/* Token::ARROW_TYPE */ 12)) { return null; } // yes, let's parse it properly $token = $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '('); $line = $token->getLine(); $names = []; while (true) { $token = $stream->expect(/* Token::NAME_TYPE */ 5); $names[] = new AssignNameExpression($token->getValue(), $token->getLine()); if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { break; } } $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')'); $stream->expect(/* Token::ARROW_TYPE */ 12); return new ArrowFunctionExpression($this->parseExpression(0), new Node($names), $line); } private function getPrimary(): AbstractExpression { $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(/* Token::PUNCTUATION_TYPE */ 9, '(')) { $this->parser->getStream()->next(); $expr = $this->parseExpression(); $this->parser->getStream()->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'An opened parenthesis is not properly closed'); return $this->parsePostfixExpression($expr); } return $this->parsePrimaryExpression(); } private function parseConditionalExpression($expr): AbstractExpression { while ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, '?')) { if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) { $expr2 = $this->parseExpression(); if ($this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) { $expr3 = $this->parseExpression(); } else { $expr3 = new ConstantExpression('', $this->parser->getCurrentToken()->getLine()); } } else { $expr2 = $expr; $expr3 = $this->parseExpression(); } $expr = new ConditionalExpression($expr, $expr2, $expr3, $this->parser->getCurrentToken()->getLine()); } return $expr; } private function isUnary(Token $token): bool { return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->unaryOperators[$token->getValue()]); } private function isBinary(Token $token): bool { return $token->test(/* Token::OPERATOR_TYPE */ 8) && isset($this->binaryOperators[$token->getValue()]); } public function parsePrimaryExpression() { $token = $this->parser->getCurrentToken(); switch ($token->getType()) { case /* Token::NAME_TYPE */ 5: $this->parser->getStream()->next(); switch ($token->getValue()) { case 'true': case 'TRUE': $node = new ConstantExpression(true, $token->getLine()); break; case 'false': case 'FALSE': $node = new ConstantExpression(false, $token->getLine()); break; case 'none': case 'NONE': case 'null': case 'NULL': $node = new ConstantExpression(null, $token->getLine()); break; default: if ('(' === $this->parser->getCurrentToken()->getValue()) { $node = $this->getFunctionNode($token->getValue(), $token->getLine()); } else { $node = new NameExpression($token->getValue(), $token->getLine()); } } break; case /* Token::NUMBER_TYPE */ 6: $this->parser->getStream()->next(); $node = new ConstantExpression($token->getValue(), $token->getLine()); break; case /* Token::STRING_TYPE */ 7: case /* Token::INTERPOLATION_START_TYPE */ 10: $node = $this->parseStringExpression(); break; case /* Token::OPERATOR_TYPE */ 8: if (preg_match(Lexer::REGEX_NAME, $token->getValue(), $matches) && $matches[0] == $token->getValue()) { // in this context, string operators are variable names $this->parser->getStream()->next(); $node = new NameExpression($token->getValue(), $token->getLine()); break; } elseif (isset($this->unaryOperators[$token->getValue()])) { $class = $this->unaryOperators[$token->getValue()]['class']; $ref = new \ReflectionClass($class); if (!(\in_array($ref->getName(), [NegUnary::class, PosUnary::class, 'Twig_Node_Expression_Unary_Neg', 'Twig_Node_Expression_Unary_Pos']) || $ref->isSubclassOf(NegUnary::class) || $ref->isSubclassOf(PosUnary::class) || $ref->isSubclassOf('Twig_Node_Expression_Unary_Neg') || $ref->isSubclassOf('Twig_Node_Expression_Unary_Pos')) ) { throw new SyntaxError(sprintf('Unexpected unary operator "%s".', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); } $this->parser->getStream()->next(); $expr = $this->parsePrimaryExpression(); $node = new $class($expr, $token->getLine()); break; } // no break default: if ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '[')) { $node = $this->parseArrayExpression(); } elseif ($token->test(/* Token::PUNCTUATION_TYPE */ 9, '{')) { $node = $this->parseHashExpression(); } elseif ($token->test(/* Token::OPERATOR_TYPE */ 8, '=') && ('==' === $this->parser->getStream()->look(-1)->getValue() || '!=' === $this->parser->getStream()->look(-1)->getValue())) { throw new SyntaxError(sprintf('Unexpected operator of value "%s". Did you try to use "===" or "!==" for strict comparison? Use "is same as(value)" instead.', $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); } else { throw new SyntaxError(sprintf('Unexpected token "%s" of value "%s".', Token::typeToEnglish($token->getType()), $token->getValue()), $token->getLine(), $this->parser->getStream()->getSourceContext()); } } return $this->parsePostfixExpression($node); } public function parseStringExpression() { $stream = $this->parser->getStream(); $nodes = []; // a string cannot be followed by another string in a single expression $nextCanBeString = true; while (true) { if ($nextCanBeString && $token = $stream->nextIf(/* Token::STRING_TYPE */ 7)) { $nodes[] = new ConstantExpression($token->getValue(), $token->getLine()); $nextCanBeString = false; } elseif ($stream->nextIf(/* Token::INTERPOLATION_START_TYPE */ 10)) { $nodes[] = $this->parseExpression(); $stream->expect(/* Token::INTERPOLATION_END_TYPE */ 11); $nextCanBeString = true; } else { break; } } $expr = array_shift($nodes); foreach ($nodes as $node) { $expr = new ConcatBinary($expr, $node, $node->getTemplateLine()); } return $expr; } public function parseArrayExpression() { $stream = $this->parser->getStream(); $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '[', 'An array element was expected'); $node = new ArrayExpression([], $stream->getCurrent()->getLine()); $first = true; while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) { if (!$first) { $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'An array element must be followed by a comma'); // trailing ,? if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) { break; } } $first = false; $node->addElement($this->parseExpression()); } $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']', 'An opened array is not properly closed'); return $node; } public function parseHashExpression() { $stream = $this->parser->getStream(); $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '{', 'A hash element was expected'); $node = new ArrayExpression([], $stream->getCurrent()->getLine()); $first = true; while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) { if (!$first) { $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'A hash value must be followed by a comma'); // trailing ,? if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '}')) { 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(/* Token::STRING_TYPE */ 7)) || ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) || $token = $stream->nextIf(/* Token::NUMBER_TYPE */ 6)) { $key = new ConstantExpression($token->getValue(), $token->getLine()); } elseif ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { $key = $this->parseExpression(); } else { $current = $stream->getCurrent(); throw new SyntaxError(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s".', Token::typeToEnglish($current->getType()), $current->getValue()), $current->getLine(), $stream->getSourceContext()); } $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ':', 'A hash key must be followed by a colon (:)'); $value = $this->parseExpression(); $node->addElement($value, $key); } $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '}', 'An opened hash is not properly closed'); return $node; } public function parsePostfixExpression($node) { while (true) { $token = $this->parser->getCurrentToken(); if (/* Token::PUNCTUATION_TYPE */ 9 == $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 SyntaxError('Calling "parent" outside a block is forbidden.', $line, $this->parser->getStream()->getSourceContext()); } if (!$this->parser->getParent() && !$this->parser->hasTraits()) { throw new SyntaxError('Calling "parent" on a template that does not extend nor "use" another template is forbidden.', $line, $this->parser->getStream()->getSourceContext()); } return new ParentExpression($this->parser->peekBlockStack(), $line); case 'block': $args = $this->parseArguments(); if (\count($args) < 1) { throw new SyntaxError('The "block" function takes one argument (the block name).', $line, $this->parser->getStream()->getSourceContext()); } return new BlockReferenceExpression($args->getNode(0), \count($args) > 1 ? $args->getNode(1) : null, $line); case 'attribute': $args = $this->parseArguments(); if (\count($args) < 2) { throw new SyntaxError('The "attribute" function takes at least two arguments (the variable and the attributes).', $line, $this->parser->getStream()->getSourceContext()); } return new GetAttrExpression($args->getNode(0), $args->getNode(1), \count($args) > 2 ? $args->getNode(2) : null, Template::ANY_CALL, $line); default: if (null !== $alias = $this->parser->getImportedSymbol('function', $name)) { $arguments = new ArrayExpression([], $line); foreach ($this->parseArguments() as $n) { $arguments->addElement($n); } $node = new MethodCallExpression($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 ArrayExpression([], $lineno); $type = Template::ANY_CALL; if ('.' == $token->getValue()) { $token = $stream->next(); if ( /* Token::NAME_TYPE */ 5 == $token->getType() || /* Token::NUMBER_TYPE */ 6 == $token->getType() || (/* Token::OPERATOR_TYPE */ 8 == $token->getType() && preg_match(Lexer::REGEX_NAME, $token->getValue())) ) { $arg = new ConstantExpression($token->getValue(), $lineno); if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { $type = Template::METHOD_CALL; foreach ($this->parseArguments() as $n) { $arguments->addElement($n); } } } else { throw new SyntaxError('Expected name or number.', $lineno, $stream->getSourceContext()); } if ($node instanceof NameExpression && null !== $this->parser->getImportedSymbol('template', $node->getAttribute('name'))) { if (!$arg instanceof ConstantExpression) { throw new SyntaxError(sprintf('Dynamic macro names are not supported (called on "%s").', $node->getAttribute('name')), $token->getLine(), $stream->getSourceContext()); } $name = $arg->getAttribute('value'); $node = new MethodCallExpression($node, 'macro_'.$name, $arguments, $lineno); $node->setAttribute('safe', true); return $node; } } else { $type = Template::ARRAY_CALL; // slice? $slice = false; if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ':')) { $slice = true; $arg = new ConstantExpression(0, $token->getLine()); } else { $arg = $this->parseExpression(); } if ($stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ':')) { $slice = true; } if ($slice) { if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, ']')) { $length = new ConstantExpression(null, $token->getLine()); } else { $length = $this->parseExpression(); } $class = $this->getFilterNodeClass('slice', $token->getLine()); $arguments = new Node([$arg, $length]); $filter = new $class($node, new ConstantExpression('slice', $token->getLine()), $arguments, $token->getLine()); $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']'); return $filter; } $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ']'); } return new GetAttrExpression($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(/* Token::NAME_TYPE */ 5); $name = new ConstantExpression($token->getValue(), $token->getLine()); if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { $arguments = new Node(); } else { $arguments = $this->parseArguments(true, false, true); } $class = $this->getFilterNodeClass($name->getAttribute('value'), $token->getLine()); $node = new $class($node, $name, $arguments, $token->getLine(), $tag); if (!$this->parser->getStream()->test(/* Token::PUNCTUATION_TYPE */ 9, '|')) { 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 Node * * @throws SyntaxError */ public function parseArguments($namedArguments = false, $definition = false, $allowArrow = false) { $args = []; $stream = $this->parser->getStream(); $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, '(', 'A list of arguments must begin with an opening parenthesis'); while (!$stream->test(/* Token::PUNCTUATION_TYPE */ 9, ')')) { if (!empty($args)) { $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ',', 'Arguments must be separated by a comma'); } if ($definition) { $token = $stream->expect(/* Token::NAME_TYPE */ 5, null, 'An argument must be a name'); $value = new NameExpression($token->getValue(), $this->parser->getCurrentToken()->getLine()); } else { $value = $this->parseExpression(0, $allowArrow); } $name = null; if ($namedArguments && $token = $stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) { if (!$value instanceof NameExpression) { throw new SyntaxError(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 SyntaxError(sprintf('A default value for an argument must be a constant (a boolean, a string, a number, or an array).'), $token->getLine(), $stream->getSourceContext()); } } else { $value = $this->parseExpression(0, $allowArrow); } } if ($definition) { if (null === $name) { $name = $value->getAttribute('name'); $value = new ConstantExpression(null, $this->parser->getCurrentToken()->getLine()); } $args[$name] = $value; } else { if (null === $name) { $args[] = $value; } else { $args[$name] = $value; } } } $stream->expect(/* Token::PUNCTUATION_TYPE */ 9, ')', 'A list of arguments must be closed by a parenthesis'); return new Node($args); } public function parseAssignmentExpression() { $stream = $this->parser->getStream(); $targets = []; while (true) { $token = $this->parser->getCurrentToken(); if ($stream->test(/* Token::OPERATOR_TYPE */ 8) && preg_match(Lexer::REGEX_NAME, $token->getValue())) { // in this context, string operators are variable names $this->parser->getStream()->next(); } else { $stream->expect(/* Token::NAME_TYPE */ 5, null, 'Only variables can be assigned to'); } $value = $token->getValue(); if (\in_array(strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ['true', 'false', 'none', 'null'])) { throw new SyntaxError(sprintf('You cannot assign a value to "%s".', $value), $token->getLine(), $stream->getSourceContext()); } $targets[] = new AssignNameExpression($value, $token->getLine()); if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { break; } } return new Node($targets); } public function parseMultitargetExpression() { $targets = []; while (true) { $targets[] = $this->parseExpression(); if (!$this->parser->getStream()->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { break; } } return new Node($targets); } private function parseNotTestExpression(Node $node): NotUnary { return new NotUnary($this->parseTestExpression($node), $this->parser->getCurrentToken()->getLine()); } private function parseTestExpression(Node $node): TestExpression { $stream = $this->parser->getStream(); list($name, $test) = $this->getTest($node->getTemplateLine()); $class = $this->getTestNodeClass($test); $arguments = null; if ($stream->test(/* Token::PUNCTUATION_TYPE */ 9, '(')) { $arguments = $this->parseArguments(true); } if ('defined' === $name && $node instanceof NameExpression && null !== $alias = $this->parser->getImportedSymbol('function', $node->getAttribute('name'))) { $node = new MethodCallExpression($alias['node'], $alias['name'], new ArrayExpression([], $node->getTemplateLine()), $node->getTemplateLine()); $node->setAttribute('safe', true); } return new $class($node, $name, $arguments, $this->parser->getCurrentToken()->getLine()); } private function getTest(int $line): array { $stream = $this->parser->getStream(); $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); if ($test = $this->env->getTest($name)) { return [$name, $test]; } if ($stream->test(/* Token::NAME_TYPE */ 5)) { // try 2-words tests $name = $name.' '.$this->parser->getCurrentToken()->getValue(); if ($test = $this->env->getTest($name)) { $stream->next(); return [$name, $test]; } } $e = new SyntaxError(sprintf('Unknown "%s" test.', $name), $line, $stream->getSourceContext()); $e->addSuggestions($name, array_keys($this->env->getTests())); throw $e; } private function getTestNodeClass(TwigTest $test): string { 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(string $name, int $line): string { if (false === $function = $this->env->getFunction($name)) { $e = new SyntaxError(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(string $name, int $line): string { if (false === $filter = $this->env->getFilter($name)) { $e = new SyntaxError(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(Node $node): bool { if (!($node instanceof ConstantExpression || $node instanceof ArrayExpression || $node instanceof NegUnary || $node instanceof PosUnary )) { return false; } foreach ($node as $n) { if (!$this->checkConstantExpression($n)) { return false; } } return true; } } class_alias('Twig\ExpressionParser', 'Twig_ExpressionParser'); php-twig-2.12.5/src/Extension/000077500000000000000000000000001362457344700161225ustar00rootroot00000000000000php-twig-2.12.5/src/Extension/AbstractExtension.php000066400000000000000000000013751362457344700223010ustar00rootroot00000000000000escapers[$strategy] = $callable; } /** * Gets all defined escapers. * * @return callable[] An array of escapers * * @deprecated since Twig 2.11, to be removed in 3.0; use the same method on EscaperExtension instead */ public function getEscapers(/* $triggerDeprecation = true */) { if (0 === \func_num_args() || func_get_arg(0)) { @trigger_error(sprintf('The "%s" method is deprecated since Twig 2.11; use "%s::getEscapers" instead.', __METHOD__, EscaperExtension::class), E_USER_DEPRECATED); } return $this->escapers; } /** * Sets the default format to be used by the date filter. * * @param string $format The default date format string * @param string $dateIntervalFormat The default date interval format string */ public function setDateFormat($format = null, $dateIntervalFormat = null) { if (null !== $format) { $this->dateFormats[0] = $format; } if (null !== $dateIntervalFormat) { $this->dateFormats[1] = $dateIntervalFormat; } } /** * Gets the default format to be used by the date filter. * * @return array The default date format string and the default date interval format string */ public function getDateFormat() { return $this->dateFormats; } /** * Sets the default timezone to be used by the date filter. * * @param \DateTimeZone|string $timezone The default timezone string or a \DateTimeZone object */ public function setTimezone($timezone) { $this->timezone = $timezone instanceof \DateTimeZone ? $timezone : new \DateTimeZone($timezone); } /** * Gets the default timezone to be used by the date filter. * * @return \DateTimeZone The default timezone currently in use */ public function getTimezone() { if (null === $this->timezone) { $this->timezone = new \DateTimeZone(date_default_timezone_get()); } return $this->timezone; } /** * Sets the default format to be used by the number_format filter. * * @param int $decimal the number of decimal places to use * @param string $decimalPoint the character(s) to use for the decimal point * @param string $thousandSep the character(s) to use for the thousands separator */ public function setNumberFormat($decimal, $decimalPoint, $thousandSep) { $this->numberFormat = [$decimal, $decimalPoint, $thousandSep]; } /** * Get the default format used by the number_format filter. * * @return array The arguments for number_format() */ public function getNumberFormat() { return $this->numberFormat; } public function getTokenParsers() { return [ new ApplyTokenParser(), new ForTokenParser(), new IfTokenParser(), new ExtendsTokenParser(), new IncludeTokenParser(), new BlockTokenParser(), new UseTokenParser(), new FilterTokenParser(), new MacroTokenParser(), new ImportTokenParser(), new FromTokenParser(), new SetTokenParser(), new SpacelessTokenParser(), new FlushTokenParser(), new DoTokenParser(), new EmbedTokenParser(), new WithTokenParser(), new DeprecatedTokenParser(), ]; } public function getFilters() { return [ // formatting filters new TwigFilter('date', 'twig_date_format_filter', ['needs_environment' => true]), new TwigFilter('date_modify', 'twig_date_modify_filter', ['needs_environment' => true]), new TwigFilter('format', 'sprintf'), new TwigFilter('replace', 'twig_replace_filter'), new TwigFilter('number_format', 'twig_number_format_filter', ['needs_environment' => true]), new TwigFilter('abs', 'abs'), new TwigFilter('round', 'twig_round'), // encoding new TwigFilter('url_encode', 'twig_urlencode_filter'), new TwigFilter('json_encode', 'json_encode'), new TwigFilter('convert_encoding', 'twig_convert_encoding'), // string filters new TwigFilter('title', 'twig_title_string_filter', ['needs_environment' => true]), new TwigFilter('capitalize', 'twig_capitalize_string_filter', ['needs_environment' => true]), new TwigFilter('upper', 'twig_upper_filter', ['needs_environment' => true]), new TwigFilter('lower', 'twig_lower_filter', ['needs_environment' => true]), new TwigFilter('striptags', 'strip_tags'), new TwigFilter('trim', 'twig_trim_filter'), new TwigFilter('nl2br', 'nl2br', ['pre_escape' => 'html', 'is_safe' => ['html']]), new TwigFilter('spaceless', 'twig_spaceless', ['is_safe' => ['html']]), // array helpers new TwigFilter('join', 'twig_join_filter'), new TwigFilter('split', 'twig_split_filter', ['needs_environment' => true]), new TwigFilter('sort', 'twig_sort_filter'), new TwigFilter('merge', 'twig_array_merge'), new TwigFilter('batch', 'twig_array_batch'), new TwigFilter('column', 'twig_array_column'), new TwigFilter('filter', 'twig_array_filter'), new TwigFilter('map', 'twig_array_map'), new TwigFilter('reduce', 'twig_array_reduce'), // string/array filters new TwigFilter('reverse', 'twig_reverse_filter', ['needs_environment' => true]), new TwigFilter('length', 'twig_length_filter', ['needs_environment' => true]), new TwigFilter('slice', 'twig_slice', ['needs_environment' => true]), new TwigFilter('first', 'twig_first', ['needs_environment' => true]), new TwigFilter('last', 'twig_last', ['needs_environment' => true]), // iteration and runtime new TwigFilter('default', '_twig_default_filter', ['node_class' => DefaultFilter::class]), new TwigFilter('keys', 'twig_get_array_keys_filter'), ]; } public function getFunctions() { return [ new TwigFunction('max', 'max'), new TwigFunction('min', 'min'), new TwigFunction('range', 'range'), new TwigFunction('constant', 'twig_constant'), new TwigFunction('cycle', 'twig_cycle'), new TwigFunction('random', 'twig_random', ['needs_environment' => true]), new TwigFunction('date', 'twig_date_converter', ['needs_environment' => true]), new TwigFunction('include', 'twig_include', ['needs_environment' => true, 'needs_context' => true, 'is_safe' => ['all']]), new TwigFunction('source', 'twig_source', ['needs_environment' => true, 'is_safe' => ['all']]), ]; } public function getTests() { return [ new TwigTest('even', null, ['node_class' => EvenTest::class]), new TwigTest('odd', null, ['node_class' => OddTest::class]), new TwigTest('defined', null, ['node_class' => DefinedTest::class]), new TwigTest('same as', null, ['node_class' => SameasTest::class]), new TwigTest('none', null, ['node_class' => NullTest::class]), new TwigTest('null', null, ['node_class' => NullTest::class]), new TwigTest('divisible by', null, ['node_class' => DivisiblebyTest::class]), new TwigTest('constant', null, ['node_class' => ConstantTest::class]), new TwigTest('empty', 'twig_test_empty'), new TwigTest('iterable', 'twig_test_iterable'), ]; } public function getNodeVisitors() { return [new MacroAutoImportNodeVisitor()]; } public function getOperators() { return [ [ 'not' => ['precedence' => 50, 'class' => NotUnary::class], '-' => ['precedence' => 500, 'class' => NegUnary::class], '+' => ['precedence' => 500, 'class' => PosUnary::class], ], [ 'or' => ['precedence' => 10, 'class' => OrBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'and' => ['precedence' => 15, 'class' => AndBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'b-or' => ['precedence' => 16, 'class' => BitwiseOrBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'b-xor' => ['precedence' => 17, 'class' => BitwiseXorBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'b-and' => ['precedence' => 18, 'class' => BitwiseAndBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '==' => ['precedence' => 20, 'class' => EqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '!=' => ['precedence' => 20, 'class' => NotEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '<=>' => ['precedence' => 20, 'class' => SpaceshipBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '<' => ['precedence' => 20, 'class' => LessBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '>' => ['precedence' => 20, 'class' => GreaterBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '>=' => ['precedence' => 20, 'class' => GreaterEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '<=' => ['precedence' => 20, 'class' => LessEqualBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'not in' => ['precedence' => 20, 'class' => NotInBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'in' => ['precedence' => 20, 'class' => InBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'matches' => ['precedence' => 20, 'class' => MatchesBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'starts with' => ['precedence' => 20, 'class' => StartsWithBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'ends with' => ['precedence' => 20, 'class' => EndsWithBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '..' => ['precedence' => 25, 'class' => RangeBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '+' => ['precedence' => 30, 'class' => AddBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '-' => ['precedence' => 30, 'class' => SubBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '~' => ['precedence' => 40, 'class' => ConcatBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '*' => ['precedence' => 60, 'class' => MulBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '/' => ['precedence' => 60, 'class' => DivBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '//' => ['precedence' => 60, 'class' => FloorDivBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], '%' => ['precedence' => 60, 'class' => ModBinary::class, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'is' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT], 'is not' => ['precedence' => 100, 'associativity' => ExpressionParser::OPERATOR_LEFT], '**' => ['precedence' => 200, 'class' => PowerBinary::class, 'associativity' => ExpressionParser::OPERATOR_RIGHT], '??' => ['precedence' => 300, 'class' => NullCoalesceExpression::class, 'associativity' => ExpressionParser::OPERATOR_RIGHT], ], ]; } } class_alias('Twig\Extension\CoreExtension', 'Twig_Extension_Core'); } namespace { use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Extension\CoreExtension; use Twig\Extension\SandboxExtension; use Twig\Markup; use Twig\Source; use Twig\Template; /** * Cycles over a value. * * @param \ArrayAccess|array $values * @param int $position The cycle position * * @return string The next value in the cycle */ function twig_cycle($values, $position) { if (!\is_array($values) && !$values instanceof \ArrayAccess) { return $values; } return $values[$position % \count($values)]; } /** * Returns a random value depending on the supplied parameter type: * - a random item from a \Traversable or array * - a random character from a string * - a random integer between 0 and the integer parameter. * * @param \Traversable|array|int|float|string $values The values to pick a random item from * @param int|null $max Maximum value used when $values is an int * * @throws RuntimeError when $values is an empty array (does not apply to an empty string which is returned as is) * * @return mixed A random value from the given sequence */ function twig_random(Environment $env, $values = null, $max = null) { if (null === $values) { return null === $max ? mt_rand() : mt_rand(0, $max); } if (\is_int($values) || \is_float($values)) { if (null === $max) { if ($values < 0) { $max = 0; $min = $values; } else { $max = $values; $min = 0; } } else { $min = $values; $max = $max; } return mt_rand($min, $max); } if (\is_string($values)) { if ('' === $values) { return ''; } $charset = $env->getCharset(); if ('UTF-8' !== $charset) { $values = twig_convert_encoding($values, 'UTF-8', $charset); } // unicode version of str_split() // split at all positions, but not after the start and not before the end $values = preg_split('/(? $value) { $values[$i] = twig_convert_encoding($value, $charset, 'UTF-8'); } } } if (!twig_test_iterable($values)) { return $values; } $values = twig_to_array($values); if (0 === \count($values)) { throw new RuntimeError('The random function cannot pick from an empty array.'); } return $values[array_rand($values, 1)]; } /** * Converts a date to the given format. * * {{ post.published_at|date("m/d/Y") }} * * @param \DateTimeInterface|\DateInterval|string $date A date * @param string|null $format The target format, null to use the default * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged * * @return string The formatted date */ function twig_date_format_filter(Environment $env, $date, $format = null, $timezone = null) { if (null === $format) { $formats = $env->getExtension(CoreExtension::class)->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 \DateTimeInterface|string $date A date * @param string $modifier A modifier string * * @return \DateTimeInterface */ function twig_date_modify_filter(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 \DateTimeInterface|string|null $date A date or null to use the current time * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged * * @return \DateTimeInterface */ function twig_date_converter(Environment $env, $date = null, $timezone = null) { // determine the timezone if (false !== $timezone) { if (null === $timezone) { $timezone = $env->getExtension(CoreExtension::class)->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(CoreExtension::class)->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(CoreExtension::class)->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 (!twig_test_iterable($from)) { throw new RuntimeError(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".', \is_object($from) ? \get_class($from) : \gettype($from))); } return strtr($str, twig_to_array($from)); } /** * Rounds a number. * * @param int|float $value The value to round * @param int|float $precision The rounding precision * @param string $method The method to use for rounding * * @return int|float The rounded number */ function twig_round($value, $precision = 0, $method = 'common') { if ('common' == $method) { return round($value, $precision); } if ('ceil' != $method && 'floor' != $method) { throw new RuntimeError('The round filter only supports the "common", "ceil", and "floor" methods.'); } return $method($value * pow(10, $precision)) / pow(10, $precision); } /** * Number format filter. * * All of the formatting options can be left null, in that case the defaults will * be used. Supplying any of the parameters will override the defaults set in the * environment object. * * @param mixed $number A float/int/string of the number to format * @param int $decimal the number of decimal points to display * @param string $decimalPoint the character(s) to use for the decimal point * @param string $thousandSep the character(s) to use for the thousands separator * * @return string The formatted number */ function twig_number_format_filter(Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null) { $defaults = $env->getExtension(CoreExtension::class)->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 (!twig_test_iterable($arr1)) { throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($arr1))); } if (!twig_test_iterable($arr2)) { throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', \gettype($arr2))); } return array_merge(twig_to_array($arr1), twig_to_array($arr2)); } /** * Slices a variable. * * @param mixed $item A variable * @param int $start Start of the slice * @param int $length Size of the slice * @param bool $preserveKeys Whether to preserve key or not (when the input is an array) * * @return mixed The sliced variable */ function twig_slice(Environment $env, $item, $start, $length = null, $preserveKeys = false) { if ($item instanceof \Traversable) { while ($item instanceof \IteratorAggregate) { $item = $item->getIterator(); } if ($start >= 0 && $length >= 0 && $item instanceof \Iterator) { try { return iterator_to_array(new \LimitIterator($item, $start, null === $length ? -1 : $length), $preserveKeys); } catch (\OutOfBoundsException $e) { return []; } } $item = iterator_to_array($item, $preserveKeys); } if (\is_array($item)) { return \array_slice($item, $start, $length, $preserveKeys); } $item = (string) $item; return (string) mb_substr($item, $start, $length, $env->getCharset()); } /** * Returns the first element of the item. * * @param mixed $item A variable * * @return mixed The first element of the item */ function twig_first(Environment $env, $item) { $elements = twig_slice($env, $item, 0, 1, false); return \is_string($elements) ? $elements : current($elements); } /** * Returns the last element of the item. * * @param mixed $item A variable * * @return mixed The last element of the item */ function twig_last(Environment $env, $item) { $elements = twig_slice($env, $item, -1, 1, false); return \is_string($elements) ? $elements : current($elements); } /** * Joins the values to a string. * * The separators between elements are empty strings per default, you can define them with the optional parameters. * * {{ [1, 2, 3]|join(', ', ' and ') }} * {# returns 1, 2 and 3 #} * * {{ [1, 2, 3]|join('|') }} * {# returns 1|2|3 #} * * {{ [1, 2, 3]|join }} * {# returns 123 #} * * @param array $value An array * @param string $glue The separator * @param string|null $and The separator for the last pair * * @return string The concatenated string */ function twig_join_filter($value, $glue = '', $and = null) { if (!twig_test_iterable($value)) { $value = (array) $value; } $value = twig_to_array($value, false); if (0 === \count($value)) { return ''; } if (null === $and || $and === $glue) { return implode($glue, $value); } if (1 === \count($value)) { return $value[0]; } return implode($glue, \array_slice($value, 0, -1)).$and.$value[\count($value) - 1]; } /** * Splits the string into an array. * * {{ "one,two,three"|split(',') }} * {# returns [one, two, three] #} * * {{ "one,two,three,four,five"|split(',', 3) }} * {# returns [one, two, "three,four,five"] #} * * {{ "123"|split('') }} * {# returns [1, 2, 3] #} * * {{ "aabbcc"|split('', 2) }} * {# returns [aa, bb, cc] #} * * @param string $value A string * @param string $delimiter The delimiter * @param int $limit The limit * * @return array The split string as an array */ function twig_split_filter(Environment $env, $value, $delimiter, $limit = null) { if (\strlen($delimiter) > 0) { return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit); } if ($limit <= 1) { return preg_split('/(?getCharset()); if ($length < $limit) { return [$value]; } $r = []; 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->rewind(); while ($array->valid()) { $keys[] = $array->key(); $array->next(); } return $keys; } $keys = []; foreach ($array as $key => $item) { $keys[] = $key; } return $keys; } if (!\is_array($array)) { return []; } return array_keys($array); } /** * Reverses a variable. * * @param array|\Traversable|string $item An array, a \Traversable instance, or a string * @param bool $preserveKeys Whether to preserve key or not * * @return mixed The reversed input */ function twig_reverse_filter(Environment $env, $item, $preserveKeys = false) { if ($item instanceof \Traversable) { return array_reverse(iterator_to_array($item), $preserveKeys); } if (\is_array($item)) { return array_reverse($item, $preserveKeys); } $string = (string) $item; $charset = $env->getCharset(); if ('UTF-8' !== $charset) { $item = twig_convert_encoding($string, 'UTF-8', $charset); } preg_match_all('/./us', $item, $matches); $string = implode('', array_reverse($matches[0])); if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, $charset, 'UTF-8'); } return $string; } /** * Sorts an array. * * @param array|\Traversable $array * * @return array */ function twig_sort_filter($array, $arrow = null) { if ($array instanceof \Traversable) { $array = iterator_to_array($array); } elseif (!\is_array($array)) { throw new RuntimeError(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', \gettype($array))); } if (null !== $arrow) { uasort($array, $arrow); } else { asort($array); } return $array; } /** * @internal */ function twig_in_filter($value, $compare) { if ($value instanceof Markup) { $value = (string) $value; } if ($compare instanceof Markup) { $compare = (string) $compare; } if (\is_array($compare)) { return \in_array($value, $compare, \is_object($value) || \is_resource($value)); } elseif (\is_string($compare) && (\is_string($value) || \is_int($value) || \is_float($value))) { return '' === $value || false !== strpos($compare, (string) $value); } elseif ($compare instanceof \Traversable) { if (\is_object($value) || \is_resource($value)) { foreach ($compare as $item) { if ($item === $value) { return true; } } } else { foreach ($compare as $item) { if ($item == $value) { return true; } } } return false; } return false; } /** * Returns a trimmed string. * * @return string * * @throws RuntimeError When an invalid trimming side is used (not a string or not 'left', 'right', or 'both') */ function twig_trim_filter($string, $characterMask = null, $side = 'both') { if (null === $characterMask) { $characterMask = " \t\n\r\0\x0B"; } switch ($side) { case 'both': return trim($string, $characterMask); case 'left': return ltrim($string, $characterMask); case 'right': return rtrim($string, $characterMask); default: throw new RuntimeError('Trimming side must be "left", "right" or "both".'); } } /** * Removes whitespaces between HTML tags. * * @return string */ function twig_spaceless($content) { return trim(preg_replace('/>\s+<', $content)); } function twig_convert_encoding($string, $to, $from) { if (!function_exists('iconv')) { throw new RuntimeError('Unable to convert encoding: required function iconv() does not exist. You should install ext-iconv or symfony/polyfill-iconv.'); } return iconv($from, $to, $string); } /** * Returns the length of a variable. * * @param mixed $thing A variable * * @return int The length of the value */ function twig_length_filter(Environment $env, $thing) { if (null === $thing) { return 0; } if (is_scalar($thing)) { return mb_strlen($thing, $env->getCharset()); } if ($thing instanceof \Countable || \is_array($thing) || $thing instanceof \SimpleXMLElement) { return \count($thing); } if ($thing instanceof \Traversable) { return iterator_count($thing); } if (method_exists($thing, '__toString') && !$thing instanceof \Countable) { return mb_strlen((string) $thing, $env->getCharset()); } return 1; } /** * Converts a string to uppercase. * * @param string $string A string * * @return string The uppercased string */ function twig_upper_filter(Environment $env, $string) { return mb_strtoupper($string, $env->getCharset()); } /** * Converts a string to lowercase. * * @param string $string A string * * @return string The lowercased string */ function twig_lower_filter(Environment $env, $string) { return mb_strtolower($string, $env->getCharset()); } /** * Returns a titlecased string. * * @param string $string A string * * @return string The titlecased string */ function twig_title_string_filter(Environment $env, $string) { if (null !== $charset = $env->getCharset()) { return mb_convert_case($string, MB_CASE_TITLE, $charset); } return ucwords(strtolower($string)); } /** * Returns a capitalized string. * * @param string $string A string * * @return string The capitalized string */ function twig_capitalize_string_filter(Environment $env, $string) { $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_call_macro(Template $template, string $method, array $args, int $lineno, array $context, Source $source) { if (!method_exists($template, $method)) { $parent = $template; while ($parent = $parent->getParent($context)) { if (method_exists($parent, $method)) { return $parent->$method(...$args); } } throw new RuntimeError(sprintf('Macro "%s" is not defined in template "%s".', substr($method, \strlen('macro_')), $template->getTemplateName()), $lineno, $source); } return $template->$method(...$args); } /** * @internal */ function twig_ensure_traversable($seq) { if ($seq instanceof \Traversable || \is_array($seq)) { return $seq; } return []; } /** * @internal */ function twig_to_array($seq, $preserveKeys = true) { if ($seq instanceof \Traversable) { return iterator_to_array($seq, $preserveKeys); } if (!\is_array($seq)) { return $seq; } return $preserveKeys ? $seq : array_values($seq); } /** * Checks if a variable is empty. * * {# evaluates to true if the foo variable is null, false, or the empty string #} * {% if foo is empty %} * {# ... #} * {% endif %} * * @param mixed $value A variable * * @return bool true if the value is empty, false otherwise */ function twig_test_empty($value) { if ($value instanceof \Countable) { return 0 == \count($value); } if ($value instanceof \Traversable) { return !iterator_count($value); } if (\is_object($value) && method_exists($value, '__toString')) { return '' === (string) $value; } return '' === $value || false === $value || null === $value || [] === $value; } /** * Checks if a variable is traversable. * * {# evaluates to true if the foo variable is an array or a traversable object #} * {% if foo is iterable %} * {# ... #} * {% endif %} * * @param mixed $value A variable * * @return bool true if the value is traversable */ function twig_test_iterable($value) { return $value instanceof \Traversable || \is_array($value); } /** * Renders a template. * * @param array $context * @param string|array $template The template to render or an array of templates to try consecutively * @param array $variables The variables to pass to the template * @param bool $withContext * @param bool $ignoreMissing Whether to ignore missing templates or not * @param bool $sandboxed Whether to sandbox the template or not * * @return string The rendered template */ function twig_include(Environment $env, $context, $template, $variables = [], $withContext = true, $ignoreMissing = false, $sandboxed = false) { $alreadySandboxed = false; $sandbox = null; if ($withContext) { $variables = array_merge($context, $variables); } if ($isSandboxed = $sandboxed && $env->hasExtension(SandboxExtension::class)) { $sandbox = $env->getExtension(SandboxExtension::class); if (!$alreadySandboxed = $sandbox->isSandboxed()) { $sandbox->enableSandbox(); } } try { $loaded = null; try { $loaded = $env->resolveTemplate($template); } catch (LoaderError $e) { if (!$ignoreMissing) { throw $e; } } return $loaded ? $loaded->render($variables) : ''; } finally { if ($isSandboxed && !$alreadySandboxed) { $sandbox->disableSandbox(); } } } /** * Returns a template content without rendering it. * * @param string $name The template name * @param bool $ignoreMissing Whether to ignore missing templates or not * * @return string The template source */ function twig_source(Environment $env, $name, $ignoreMissing = false) { $loader = $env->getLoader(); try { return $loader->getSourceContext($name)->getCode(); } catch (LoaderError $e) { if (!$ignoreMissing) { throw $e; } } } /** * Provides the ability to get constants from instances as well as class/global constants. * * @param string $constant The name of the constant * @param object|null $object The object to get the constant from * * @return string */ function twig_constant($constant, $object = null) { if (null !== $object) { $constant = \get_class($object).'::'.$constant; } return \constant($constant); } /** * Checks if a constant exists. * * @param string $constant The name of the constant * @param object|null $object The object to get the constant from * * @return bool */ function twig_constant_is_defined($constant, $object = null) { if (null !== $object) { $constant = \get_class($object).'::'.$constant; } return \defined($constant); } /** * Batches item. * * @param array $items An array of items * @param int $size The size of the batch * @param mixed $fill A value used to fill missing items * * @return array */ function twig_array_batch($items, $size, $fill = null, $preserveKeys = true) { if (!twig_test_iterable($items)) { throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', \is_object($items) ? \get_class($items) : \gettype($items))); } $size = ceil($size); $result = array_chunk(twig_to_array($items, $preserveKeys), $size, $preserveKeys); if (null !== $fill && $result) { $last = \count($result) - 1; if ($fillCount = $size - \count($result[$last])) { for ($i = 0; $i < $fillCount; ++$i) { $result[$last][] = $fill; } } } return $result; } /** * 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 * @param int $lineno The template line where the attribute was called * * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true * * @throws RuntimeError if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false * * @internal */ function twig_get_attribute(Environment $env, Source $source, $object, $item, array $arguments = [], $type = /* Template::ANY_CALL */ 'any', $isDefinedTest = false, $ignoreStrictCheck = false, $sandboxed = false, int $lineno = -1) { // array if (/* Template::METHOD_CALL */ 'method' !== $type) { $arrayItem = \is_bool($item) || \is_float($item) ? (int) $item : $item; if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, (array) $object))) || ($object instanceof ArrayAccess && isset($object[$arrayItem])) ) { if ($isDefinedTest) { return true; } return $object[$arrayItem]; } if (/* 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 (/* 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 RuntimeError($message, $lineno, $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 RuntimeError($message, $lineno, $source); } if ($object instanceof Template) { throw new RuntimeError('Accessing \Twig\Template attributes is forbidden.', $lineno, $source); } // object property if (/* Template::METHOD_CALL */ 'method' !== $type) { if (isset($object->$item) || \array_key_exists((string) $item, (array) $object)) { if ($isDefinedTest) { return true; } if ($sandboxed) { $env->getExtension(SandboxExtension::class)->checkPropertyAllowed($object, $item, $lineno, $source); } return $object->$item; } } static $cache = []; $class = \get_class($object); // object method // precedence: getXxx() > isXxx() > hasXxx() if (!isset($cache[$class])) { $methods = get_class_methods($object); sort($methods); $lcMethods = array_map(function ($value) { return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }, $methods); $classCache = []; 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 = strtr($item, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')])) { $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 RuntimeError(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), $lineno, $source); } if ($isDefinedTest) { return true; } if ($sandboxed) { $env->getExtension(SandboxExtension::class)->checkMethodAllowed($object, $method, $lineno, $source); } // 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; } /** * Returns the values from a single column in the input array. * *
     *  {% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}
     *
     *  {% set fruits = items|column('fruit') %}
     *
     *  {# fruits now contains ['apple', 'orange'] #}
     * 
    * * @param array|Traversable $array An array * @param mixed $name The column name * @param mixed $index The column to use as the index/keys for the returned array * * @return array The array of values */ function twig_array_column($array, $name, $index = null): array { if ($array instanceof Traversable) { $array = iterator_to_array($array); } elseif (!\is_array($array)) { throw new RuntimeError(sprintf('The column filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array))); } return array_column($array, $name, $index); } function twig_array_filter($array, $arrow) { if (\is_array($array)) { return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH); } // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow); } function twig_array_map($array, $arrow) { $r = []; foreach ($array as $k => $v) { $r[$k] = $arrow($v, $k); } return $r; } function twig_array_reduce($array, $arrow, $initial = null) { if (!\is_array($array)) { $array = iterator_to_array($array); } return array_reduce($array, $arrow, $initial); } } php-twig-2.12.5/src/Extension/DebugExtension.php000066400000000000000000000034351362457344700215630ustar00rootroot00000000000000 $isDumpOutputHtmlSafe ? ['html'] : [], 'needs_context' => true, 'needs_environment' => true, 'is_variadic' => true]), ]; } } class_alias('Twig\Extension\DebugExtension', 'Twig_Extension_Debug'); } namespace { use Twig\Environment; use Twig\Template; use Twig\TemplateWrapper; function twig_var_dump(Environment $env, $context, ...$vars) { if (!$env->isDebug()) { return; } ob_start(); if (!$vars) { $vars = []; foreach ($context as $key => $value) { if (!$value instanceof Template && !$value instanceof TemplateWrapper) { $vars[$key] = $value; } } var_dump($vars); } else { var_dump(...$vars); } return ob_get_clean(); } } php-twig-2.12.5/src/Extension/EscaperExtension.php000066400000000000000000000343041362457344700221160ustar00rootroot00000000000000setDefaultStrategy($defaultStrategy); } public function getTokenParsers() { return [new AutoEscapeTokenParser()]; } public function getNodeVisitors() { return [new EscaperNodeVisitor()]; } public function getFilters() { return [ new TwigFilter('escape', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']), new TwigFilter('e', 'twig_escape_filter', ['needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe']), new TwigFilter('raw', 'twig_raw_filter', ['is_safe' => ['all']]), ]; } /** * Sets the default strategy to use when not defined by the user. * * The strategy can be a valid PHP callback that takes the template * name as an argument and returns the strategy to use. * * @param string|false|callable $defaultStrategy An escaping strategy */ public function setDefaultStrategy($defaultStrategy) { if ('name' === $defaultStrategy) { $defaultStrategy = [FileExtensionEscapingStrategy::class, '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; } /** * Defines a new escaper to be used via the escape filter. * * @param string $strategy The strategy name that should be used as a strategy in the escape call * @param callable $callable A valid PHP callable */ public function setEscaper($strategy, callable $callable) { $this->escapers[$strategy] = $callable; } /** * Gets all defined escapers. * * @return callable[] An array of escapers */ public function getEscapers() { return $this->escapers; } public function setSafeClasses(array $safeClasses = []) { $this->safeClasses = []; $this->safeLookup = []; foreach ($safeClasses as $class => $strategies) { $this->addSafeClass($class, $strategies); } } public function addSafeClass(string $class, array $strategies) { $class = ltrim($class, '\\'); if (!isset($this->safeClasses[$class])) { $this->safeClasses[$class] = []; } $this->safeClasses[$class] = array_merge($this->safeClasses[$class], $strategies); foreach ($strategies as $strategy) { $this->safeLookup[$strategy][$class] = true; } } } class_alias('Twig\Extension\EscaperExtension', 'Twig_Extension_Escaper'); } namespace { use Twig\Environment; use Twig\Error\RuntimeError; use Twig\Extension\CoreExtension; use Twig\Extension\EscaperExtension; use Twig\Markup; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Node; /** * Marks a variable as being safe. * * @param string $string A PHP variable * * @return string */ function twig_raw_filter($string) { return $string; } /** * Escapes a string. * * @param mixed $string The value to be escaped * @param string $strategy The escaping strategy * @param string $charset The charset * @param bool $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false) * * @return string */ function twig_escape_filter(Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false) { if ($autoescape && $string instanceof Markup) { return $string; } if (!\is_string($string)) { if (\is_object($string) && method_exists($string, '__toString')) { if ($autoescape) { $c = \get_class($string); $ext = $env->getExtension(EscaperExtension::class); if (!isset($ext->safeClasses[$c])) { $ext->safeClasses[$c] = []; foreach (class_parents($string) + class_implements($string) as $class) { if (isset($ext->safeClasses[$class])) { $ext->safeClasses[$c] = array_unique(array_merge($ext->safeClasses[$c], $ext->safeClasses[$class])); foreach ($ext->safeClasses[$class] as $s) { $ext->safeLookup[$s][$c] = true; } } } } if (isset($ext->safeLookup[$strategy][$c]) || isset($ext->safeLookup['all'][$c])) { return (string) $string; } } $string = (string) $string; } elseif (\in_array($strategy, ['html', 'js', 'css', 'html_attr', 'url'])) { return $string; } } if ('' === $string) { return ''; } if (null === $charset) { $charset = $env->getCharset(); } switch ($strategy) { case 'html': // see https://secure.php.net/htmlspecialchars // Using a static variable to avoid initializing the array // each time the function is called. Moving the declaration on the // top of the function slow downs other escaping strategies. static $htmlspecialcharsCharsets = [ 'ISO-8859-1' => true, 'ISO8859-1' => true, 'ISO-8859-15' => true, 'ISO8859-15' => true, 'utf-8' => true, 'UTF-8' => true, 'CP866' => true, 'IBM866' => true, '866' => true, 'CP1251' => true, 'WINDOWS-1251' => true, 'WIN-1251' => true, '1251' => true, 'CP1252' => true, 'WINDOWS-1252' => true, '1252' => true, 'KOI8-R' => true, 'KOI8-RU' => true, 'KOI8R' => true, 'BIG5' => true, '950' => true, 'GB2312' => true, '936' => true, 'BIG5-HKSCS' => true, 'SHIFT_JIS' => true, 'SJIS' => true, '932' => true, 'EUC-JP' => true, 'EUCJP' => true, 'ISO8859-5' => true, 'ISO-8859-5' => true, 'MACROMAN' => true, ]; if (isset($htmlspecialcharsCharsets[$charset])) { return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset); } if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) { // cache the lowercase variant for future iterations $htmlspecialcharsCharsets[$charset] = true; return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset); } $string = twig_convert_encoding($string, 'UTF-8', $charset); $string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); return iconv('UTF-8', $charset, $string); case 'js': // escape all non-alphanumeric characters // into their \x or \uHHHH representations if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, 'UTF-8', $charset); } if (!preg_match('//u', $string)) { throw new RuntimeError('The string to escape is not a valid UTF-8 string.'); } $string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', function ($matches) { $char = $matches[0]; /* * A few characters have short escape sequences in JSON and JavaScript. * Escape sequences supported only by JavaScript, not JSON, are ommitted. * \" is also supported but omitted, because the resulting string is not HTML safe. */ static $shortMap = [ '\\' => '\\\\', '/' => '\\/', "\x08" => '\b', "\x0C" => '\f', "\x0A" => '\n', "\x0D" => '\r', "\x09" => '\t', ]; if (isset($shortMap[$char])) { return $shortMap[$char]; } // \uHHHH $char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8'); $char = strtoupper(bin2hex($char)); if (4 >= \strlen($char)) { return sprintf('\u%04s', $char); } return sprintf('\u%04s\u%04s', substr($char, 0, -4), substr($char, -4)); }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'css': if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, 'UTF-8', $charset); } if (!preg_match('//u', $string)) { throw new RuntimeError('The string to escape is not a valid UTF-8 string.'); } $string = preg_replace_callback('#[^a-zA-Z0-9]#Su', function ($matches) { $char = $matches[0]; return sprintf('\\%X ', 1 === \strlen($char) ? \ord($char) : mb_ord($char, 'UTF-8')); }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'html_attr': if ('UTF-8' !== $charset) { $string = twig_convert_encoding($string, 'UTF-8', $charset); } if (!preg_match('//u', $string)) { throw new RuntimeError('The string to escape is not a valid UTF-8 string.'); } $string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', function ($matches) { /** * This function is adapted from code coming from Zend Framework. * * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (https://www.zend.com) * @license https://framework.zend.com/license/new-bsd New BSD License */ $chr = $matches[0]; $ord = \ord($chr); /* * The following replaces characters undefined in HTML with the * hex entity for the Unicode replacement character. */ if (($ord <= 0x1f && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($ord >= 0x7f && $ord <= 0x9f)) { return '�'; } /* * Check if the current character to escape has a name entity we should * replace it with while grabbing the hex value of the character. */ if (1 === \strlen($chr)) { /* * While HTML supports far more named entities, the lowest common denominator * has become HTML5's XML Serialisation which is restricted to the those named * entities that XML supports. Using HTML entities would result in this error: * XML Parsing Error: undefined entity */ static $entityMap = [ 34 => '"', /* quotation mark */ 38 => '&', /* ampersand */ 60 => '<', /* less-than sign */ 62 => '>', /* greater-than sign */ ]; if (isset($entityMap[$ord])) { return $entityMap[$ord]; } return sprintf('&#x%02X;', $ord); } /* * Per OWASP recommendations, we'll use hex entities for any other * characters where a named entity does not exist. */ return sprintf('&#x%04X;', mb_ord($chr, 'UTF-8')); }, $string); if ('UTF-8' !== $charset) { $string = iconv('UTF-8', $charset, $string); } return $string; case 'url': return rawurlencode($string); default: static $escapers; if (null === $escapers) { // merge the ones set on CoreExtension for BC (to be removed in 3.0) $escapers = array_merge( $env->getExtension(CoreExtension::class)->getEscapers(false), $env->getExtension(EscaperExtension::class)->getEscapers() ); } if (isset($escapers[$strategy])) { return $escapers[$strategy]($env, $string, $charset); } $validStrategies = implode(', ', array_merge(['html', 'js', 'url', 'css', 'html_attr'], array_keys($escapers))); throw new RuntimeError(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies)); } } /** * @internal */ function twig_escape_filter_is_safe(Node $filterArgs) { foreach ($filterArgs as $arg) { if ($arg instanceof ConstantExpression) { return [$arg->getAttribute('value')]; } return []; } return ['html']; } } php-twig-2.12.5/src/Extension/ExtensionInterface.php000066400000000000000000000033321362457344700224310ustar00rootroot00000000000000 */ interface ExtensionInterface { /** * Returns the token parser instances to add to the existing list. * * @return TokenParserInterface[] */ public function getTokenParsers(); /** * Returns the node visitor instances to add to the existing list. * * @return NodeVisitorInterface[] */ public function getNodeVisitors(); /** * Returns a list of filters to add to the existing list. * * @return TwigFilter[] */ public function getFilters(); /** * Returns a list of tests to add to the existing list. * * @return TwigTest[] */ public function getTests(); /** * Returns a list of functions to add to the existing list. * * @return TwigFunction[] */ public function getFunctions(); /** * Returns a list of operators to add to the existing list. * * @return array First array of unary operators, second array of binary operators */ public function getOperators(); } class_alias('Twig\Extension\ExtensionInterface', 'Twig_ExtensionInterface'); // Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. class_exists('Twig\Environment'); php-twig-2.12.5/src/Extension/GlobalsInterface.php000066400000000000000000000014441362457344700220420ustar00rootroot00000000000000 */ interface 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'); php-twig-2.12.5/src/Extension/InitRuntimeInterface.php000066400000000000000000000016451362457344700227310ustar00rootroot00000000000000 * * @deprecated since Twig 2.7, to be removed in 3.0 */ interface InitRuntimeInterface { /** * Initializes the runtime environment. * * This is where you can load some file that contains filter functions for instance. */ public function initRuntime(Environment $environment); } class_alias('Twig\Extension\InitRuntimeInterface', 'Twig_Extension_InitRuntimeInterface'); php-twig-2.12.5/src/Extension/OptimizerExtension.php000066400000000000000000000012171362457344700225130ustar00rootroot00000000000000optimizers = $optimizers; } public function getNodeVisitors() { return [new OptimizerNodeVisitor($this->optimizers)]; } } class_alias('Twig\Extension\OptimizerExtension', 'Twig_Extension_Optimizer'); php-twig-2.12.5/src/Extension/ProfilerExtension.php000066400000000000000000000020311362457344700223060ustar00rootroot00000000000000actives[] = $profile; } public function enter(Profile $profile) { $this->actives[0]->addProfile($profile); array_unshift($this->actives, $profile); } public function leave(Profile $profile) { $profile->leave(); array_shift($this->actives); if (1 === \count($this->actives)) { $this->actives[0]->leave(); } } public function getNodeVisitors() { return [new ProfilerNodeVisitor(\get_class($this))]; } } class_alias('Twig\Extension\ProfilerExtension', 'Twig_Extension_Profiler'); php-twig-2.12.5/src/Extension/RuntimeExtensionInterface.php000066400000000000000000000005061362457344700237750ustar00rootroot00000000000000 */ interface RuntimeExtensionInterface { } php-twig-2.12.5/src/Extension/SandboxExtension.php000066400000000000000000000061541362457344700221340ustar00rootroot00000000000000policy = $policy; $this->sandboxedGlobally = $sandboxed; } public function getTokenParsers() { return [new SandboxTokenParser()]; } public function getNodeVisitors() { return [new SandboxNodeVisitor()]; } public function enableSandbox() { $this->sandboxed = true; } public function disableSandbox() { $this->sandboxed = false; } public function isSandboxed() { return $this->sandboxedGlobally || $this->sandboxed; } public function isSandboxedGlobally() { return $this->sandboxedGlobally; } public function setSecurityPolicy(SecurityPolicyInterface $policy) { $this->policy = $policy; } public function getSecurityPolicy() { return $this->policy; } public function checkSecurity($tags, $filters, $functions) { if ($this->isSandboxed()) { $this->policy->checkSecurity($tags, $filters, $functions); } } public function checkMethodAllowed($obj, $method, int $lineno = -1, Source $source = null) { if ($this->isSandboxed()) { try { $this->policy->checkMethodAllowed($obj, $method); } catch (SecurityNotAllowedMethodError $e) { $e->setSourceContext($source); $e->setTemplateLine($lineno); throw $e; } } } public function checkPropertyAllowed($obj, $method, int $lineno = -1, Source $source = null) { if ($this->isSandboxed()) { try { $this->policy->checkPropertyAllowed($obj, $method); } catch (SecurityNotAllowedPropertyError $e) { $e->setSourceContext($source); $e->setTemplateLine($lineno); throw $e; } } } public function ensureToStringAllowed($obj, int $lineno = -1, Source $source = null) { if ($this->isSandboxed() && \is_object($obj) && method_exists($obj, '__toString')) { try { $this->policy->checkMethodAllowed($obj, '__toString'); } catch (SecurityNotAllowedMethodError $e) { $e->setSourceContext($source); $e->setTemplateLine($lineno); throw $e; } } return $obj; } } class_alias('Twig\Extension\SandboxExtension', 'Twig_Extension_Sandbox'); php-twig-2.12.5/src/Extension/StagingExtension.php000066400000000000000000000046571362457344700221400ustar00rootroot00000000000000 * * @internal */ final class StagingExtension extends AbstractExtension { private $functions = []; private $filters = []; private $visitors = []; private $tokenParsers = []; private $tests = []; public function addFunction(TwigFunction $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(TwigFilter $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(NodeVisitorInterface $visitor) { $this->visitors[] = $visitor; } public function getNodeVisitors() { return $this->visitors; } public function addTokenParser(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(TwigTest $test) { if (isset($this->tests[$test->getName()])) { throw new \LogicException(sprintf('Test "%s" is already registered.', $test->getName())); } $this->tests[$test->getName()] = $test; } public function getTests() { return $this->tests; } } class_alias('Twig\Extension\StagingExtension', 'Twig_Extension_Staging'); php-twig-2.12.5/src/Extension/StringLoaderExtension.php000066400000000000000000000021431362457344700231250ustar00rootroot00000000000000 true]), ]; } } class_alias('Twig\Extension\StringLoaderExtension', 'Twig_Extension_StringLoader'); } namespace { use Twig\Environment; use Twig\TemplateWrapper; /** * Loads a template from a string. * * {{ include(template_from_string("Hello {{ name }}")) }} * * @param string $template A template as a string or object implementing __toString() * @param string $name An optional name of the template to be used in error messages * * @return TemplateWrapper */ function twig_template_from_string(Environment $env, $template, string $name = null) { return $env->createTemplate((string) $template, $name); } } php-twig-2.12.5/src/ExtensionSet.php000066400000000000000000000312721362457344700173140ustar00rootroot00000000000000 * * @internal */ final class 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 = []; private $filterCallbacks = []; private $lastModified = 0; public function __construct() { $this->staging = new StagingExtension(); } /** * Initializes the runtime environment. * * @deprecated since Twig 2.7 */ public function initRuntime(Environment $env) { if ($this->runtimeInitialized) { return; } $this->runtimeInitialized = true; foreach ($this->extensions as $extension) { if ($extension instanceof InitRuntimeInterface) { $extension->initRuntime($env); } } } public function hasExtension(string $class): bool { $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]); } public function getExtension(string $class): ExtensionInterface { $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 RuntimeError(sprintf('The "%s" extension is not enabled.', $class)); } return $this->extensions[$class]; } /** * @param ExtensionInterface[] $extensions */ public function setExtensions(array $extensions) { foreach ($extensions as $extension) { $this->addExtension($extension); } } /** * @return ExtensionInterface[] */ public function getExtensions(): array { return $this->extensions; } public function getSignature(): string { return json_encode(array_keys($this->extensions)); } public function isInitialized(): bool { return $this->initialized || $this->runtimeInitialized; } public function getLastModified(): int { 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; } public function addExtension(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)); } // For BC/FC with namespaced aliases $class = (new \ReflectionClass($class))->name; $this->extensions[$class] = $extension; } public function addFunction(TwigFunction $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); } /** * @return TwigFunction[] */ public function getFunctions(): array { if (!$this->initialized) { $this->initExtensions(); } return $this->functions; } /** * @return TwigFunction|false */ public function getFunction(string $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(TwigFilter $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); } /** * @return TwigFilter[] */ public function getFilters(): array { if (!$this->initialized) { $this->initExtensions(); } return $this->filters; } /** * @return TwigFilter|false */ public function getFilter(string $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(NodeVisitorInterface $visitor) { if ($this->initialized) { throw new \LogicException('Unable to add a node visitor as extensions have already been initialized.'); } $this->staging->addNodeVisitor($visitor); } /** * @return NodeVisitorInterface[] */ public function getNodeVisitors(): array { if (!$this->initialized) { $this->initExtensions(); } return $this->visitors; } public function addTokenParser(TokenParserInterface $parser) { if ($this->initialized) { throw new \LogicException('Unable to add a token parser as extensions have already been initialized.'); } $this->staging->addTokenParser($parser); } /** * @return TokenParserInterface[] */ public function getTokenParsers(): array { if (!$this->initialized) { $this->initExtensions(); } return $this->parsers; } public function getGlobals(): array { if (null !== $this->globals) { return $this->globals; } $globals = []; foreach ($this->extensions as $extension) { if (!$extension instanceof 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(TwigTest $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); } /** * @return TwigTest[] */ public function getTests(): array { if (!$this->initialized) { $this->initExtensions(); } return $this->tests; } /** * @return TwigTest|false */ public function getTest(string $name) { if (!$this->initialized) { $this->initExtensions(); } if (isset($this->tests[$name])) { return $this->tests[$name]; } foreach ($this->tests as $pattern => $test) { $pattern = str_replace('\\*', '(.*?)', preg_quote($pattern, '#'), $count); if ($count) { if (preg_match('#^'.$pattern.'$#', $name, $matches)) { array_shift($matches); $test->setArguments($matches); return $test; } } } return false; } public function getUnaryOperators(): array { if (!$this->initialized) { $this->initExtensions(); } return $this->unaryOperators; } public function getBinaryOperators(): array { if (!$this->initialized) { $this->initExtensions(); } return $this->binaryOperators; } private function initExtensions() { $this->parsers = []; $this->filters = []; $this->functions = []; $this->tests = []; $this->visitors = []; $this->unaryOperators = []; $this->binaryOperators = []; 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(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 TokenParserInterface) { throw new \LogicException('getTokenParsers() must return an array of \Twig\TokenParser\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'); php-twig-2.12.5/src/FileExtensionEscapingStrategy.php000066400000000000000000000027611362457344700226360ustar00rootroot00000000000000 */ class 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), ['/', '\\'])) { 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'); php-twig-2.12.5/src/Lexer.php000066400000000000000000000453671362457344700157550ustar00rootroot00000000000000 */ class 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]+)?([Ee][\+\-][0-9]+)?/A'; const REGEX_STRING = '/"([^#"\\\\]*(?:\\\\.[^#"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\'/As'; const REGEX_DQ_STRING_DELIM = '/"/A'; const REGEX_DQ_STRING_PART = '/[^#"\\\\]*(?:(?:\\\\.|#(?!\{))[^#"\\\\]*)*/As'; const PUNCTUATION = '()[]{}?:.,|'; public function __construct(Environment $env, array $options = []) { $this->env = $env; $this->options = array_merge([ 'tag_comment' => ['{#', '#}'], 'tag_block' => ['{%', '%}'], 'tag_variable' => ['{{', '}}'], 'whitespace_trim' => '-', 'whitespace_line_trim' => '~', 'whitespace_line_chars' => ' \t\0\x0B', 'interpolation' => ['#{', '}'], ], $options); // when PHP 7.3 is the min version, we will be able to remove the '#' part in preg_quote as it's part of the default $this->regexes = [ // }} 'lex_var' => '{ \s* (?:'. preg_quote($this->options['whitespace_trim'].$this->options['tag_variable'][1], '#').'\s*'. // -}}\s* '|'. preg_quote($this->options['whitespace_line_trim'].$this->options['tag_variable'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~}}[ \t\0\x0B]* '|'. preg_quote($this->options['tag_variable'][1], '#'). // }} ') }Ax', // %} 'lex_block' => '{ \s* (?:'. preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*\n?'. // -%}\s*\n? '|'. preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* '|'. preg_quote($this->options['tag_block'][1], '#').'\n?'. // %}\n? ') }Ax', // {% endverbatim %} 'lex_raw_data' => '{'. preg_quote($this->options['tag_block'][0], '#'). // {% '('. $this->options['whitespace_trim']. // - '|'. $this->options['whitespace_line_trim']. // ~ ')?\s*endverbatim\s*'. '(?:'. preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%} '|'. preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* '|'. preg_quote($this->options['tag_block'][1], '#'). // %} ') }sx', 'operator' => $this->getOperatorRegex(), // #} 'lex_comment' => '{ (?:'. preg_quote($this->options['whitespace_trim']).preg_quote($this->options['tag_comment'][1], '#').'\s*\n?'. // -#}\s*\n? '|'. preg_quote($this->options['whitespace_line_trim'].$this->options['tag_comment'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~#}[ \t\0\x0B]* '|'. preg_quote($this->options['tag_comment'][1], '#').'\n?'. // #}\n? ') }sx', // verbatim %} 'lex_block_raw' => '{ \s*verbatim\s* (?:'. preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1], '#').'\s*'. // -%}\s* '|'. preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1], '#').'['.$this->options['whitespace_line_chars'].']*'. // ~%}[ \t\0\x0B]* '|'. preg_quote($this->options['tag_block'][1], '#'). // %} ') }Asx', 'lex_block_line' => '{\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1], '#').'}As', // {{ or {% or {# 'lex_tokens_start' => '{ ('. preg_quote($this->options['tag_variable'][0], '#'). // {{ '|'. preg_quote($this->options['tag_block'][0], '#'). // {% '|'. preg_quote($this->options['tag_comment'][0], '#'). // {# ')('. preg_quote($this->options['whitespace_trim'], '#'). // - '|'. preg_quote($this->options['whitespace_line_trim'], '#'). // ~ ')? }sx', 'interpolation_start' => '{'.preg_quote($this->options['interpolation'][0], '#').'\s*}A', 'interpolation_end' => '{\s*'.preg_quote($this->options['interpolation'][1], '#').'}A', ]; } public function tokenize(Source $source) { $this->source = $source; $this->code = str_replace(["\r\n", "\r"], "\n", $source->getCode()); $this->cursor = 0; $this->lineno = 1; $this->end = \strlen($this->code); $this->tokens = []; $this->state = self::STATE_DATA; $this->states = []; $this->brackets = []; $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(/* Token::EOF_TYPE */ -1); if (!empty($this->brackets)) { list($expect, $lineno) = array_pop($this->brackets); throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); } return new 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(/* Token::TEXT_TYPE */ 0, 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); // trim? if (isset($this->positions[2][$this->position][0])) { if ($this->options['whitespace_trim'] === $this->positions[2][$this->position][0]) { // whitespace_trim detected ({%-, {{- or {#-) $text = rtrim($text); } elseif ($this->options['whitespace_line_trim'] === $this->positions[2][$this->position][0]) { // whitespace_line_trim detected ({%~, {{~ or {#~) // don't trim \r and \n $text = rtrim($text, " \t\0\x0B"); } } $this->pushToken(/* Token::TEXT_TYPE */ 0, $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, 0, $this->cursor)) { $this->moveCursor($match[0]); $this->lexRawData(); // {% line \d+ %} } elseif (preg_match($this->regexes['lex_block_line'], $this->code, $match, 0, $this->cursor)) { $this->moveCursor($match[0]); $this->lineno = (int) $match[1]; } else { $this->pushToken(/* Token::BLOCK_START_TYPE */ 1); $this->pushState(self::STATE_BLOCK); $this->currentVarBlockLine = $this->lineno; } break; case $this->options['tag_variable'][0]: $this->pushToken(/* Token::VAR_START_TYPE */ 2); $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, 0, $this->cursor)) { $this->pushToken(/* Token::BLOCK_END_TYPE */ 3); $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, 0, $this->cursor)) { $this->pushToken(/* Token::VAR_END_TYPE */ 4); $this->moveCursor($match[0]); $this->popState(); } else { $this->lexExpression(); } } private function lexExpression() { // whitespace if (preg_match('/\s+/A', $this->code, $match, 0, $this->cursor)) { $this->moveCursor($match[0]); if ($this->cursor >= $this->end) { throw new SyntaxError(sprintf('Unclosed "%s".', self::STATE_BLOCK === $this->state ? 'block' : 'variable'), $this->currentVarBlockLine, $this->source); } } // arrow function if ('=' === $this->code[$this->cursor] && '>' === $this->code[$this->cursor + 1]) { $this->pushToken(Token::ARROW_TYPE, '=>'); $this->moveCursor('=>'); } // operators elseif (preg_match($this->regexes['operator'], $this->code, $match, 0, $this->cursor)) { $this->pushToken(/* Token::OPERATOR_TYPE */ 8, preg_replace('/\s+/', ' ', $match[0])); $this->moveCursor($match[0]); } // names elseif (preg_match(self::REGEX_NAME, $this->code, $match, 0, $this->cursor)) { $this->pushToken(/* Token::NAME_TYPE */ 5, $match[0]); $this->moveCursor($match[0]); } // numbers elseif (preg_match(self::REGEX_NUMBER, $this->code, $match, 0, $this->cursor)) { $number = (float) $match[0]; // floats if (ctype_digit($match[0]) && $number <= PHP_INT_MAX) { $number = (int) $match[0]; // integers lower than the maximum } $this->pushToken(/* Token::NUMBER_TYPE */ 6, $number); $this->moveCursor($match[0]); } // punctuation elseif (false !== strpos(self::PUNCTUATION, $this->code[$this->cursor])) { // opening bracket if (false !== strpos('([{', $this->code[$this->cursor])) { $this->brackets[] = [$this->code[$this->cursor], $this->lineno]; } // closing bracket elseif (false !== strpos(')]}', $this->code[$this->cursor])) { if (empty($this->brackets)) { throw new SyntaxError(sprintf('Unexpected "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); } list($expect, $lineno) = array_pop($this->brackets); if ($this->code[$this->cursor] != strtr($expect, '([{', ')]}')) { throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); } } $this->pushToken(/* Token::PUNCTUATION_TYPE */ 9, $this->code[$this->cursor]); ++$this->cursor; } // strings elseif (preg_match(self::REGEX_STRING, $this->code, $match, 0, $this->cursor)) { $this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes(substr($match[0], 1, -1))); $this->moveCursor($match[0]); } // opening double quoted string elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) { $this->brackets[] = ['"', $this->lineno]; $this->pushState(self::STATE_STRING); $this->moveCursor($match[0]); } // unlexable else { throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); } } private function lexRawData() { if (!preg_match($this->regexes['lex_raw_data'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { throw new SyntaxError('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]); // trim? if (isset($match[1][0])) { if ($this->options['whitespace_trim'] === $match[1][0]) { // whitespace_trim detected ({%-, {{- or {#-) $text = rtrim($text); } else { // whitespace_line_trim detected ({%~, {{~ or {#~) // don't trim \r and \n $text = rtrim($text, " \t\0\x0B"); } } $this->pushToken(/* Token::TEXT_TYPE */ 0, $text); } private function lexComment() { if (!preg_match($this->regexes['lex_comment'], $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) { throw new SyntaxError('Unclosed comment.', $this->lineno, $this->source); } $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, 0, $this->cursor)) { $this->brackets[] = [$this->options['interpolation'][0], $this->lineno]; $this->pushToken(/* Token::INTERPOLATION_START_TYPE */ 10); $this->moveCursor($match[0]); $this->pushState(self::STATE_INTERPOLATION); } elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code, $match, 0, $this->cursor) && \strlen($match[0]) > 0) { $this->pushToken(/* Token::STRING_TYPE */ 7, stripcslashes($match[0])); $this->moveCursor($match[0]); } elseif (preg_match(self::REGEX_DQ_STRING_DELIM, $this->code, $match, 0, $this->cursor)) { list($expect, $lineno) = array_pop($this->brackets); if ('"' != $this->code[$this->cursor]) { throw new SyntaxError(sprintf('Unclosed "%s".', $expect), $lineno, $this->source); } $this->popState(); ++$this->cursor; } else { // unlexable throw new SyntaxError(sprintf('Unexpected character "%s".', $this->code[$this->cursor]), $this->lineno, $this->source); } } private function lexInterpolation() { $bracket = end($this->brackets); if ($this->options['interpolation'][0] === $bracket[0] && preg_match($this->regexes['interpolation_end'], $this->code, $match, 0, $this->cursor)) { array_pop($this->brackets); $this->pushToken(/* Token::INTERPOLATION_END_TYPE */ 11); $this->moveCursor($match[0]); $this->popState(); } else { $this->lexExpression(); } } private function pushToken($type, $value = '') { // do not push empty text tokens if (/* Token::TEXT_TYPE */ 0 === $type && '' === $value) { return; } $this->tokens[] = new 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_keys($this->env->getUnaryOperators()), array_keys($this->env->getBinaryOperators()) ); $operators = array_combine($operators, array_map('strlen', $operators)); arsort($operators); $regex = []; 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'); php-twig-2.12.5/src/Loader/000077500000000000000000000000001362457344700153545ustar00rootroot00000000000000php-twig-2.12.5/src/Loader/ArrayLoader.php000066400000000000000000000043671362457344700203040ustar00rootroot00000000000000 */ final class ArrayLoader implements LoaderInterface, ExistsLoaderInterface, SourceContextLoaderInterface { private $templates = []; /** * @param array $templates An array of templates (keys are the names, and values are the source code) */ public function __construct(array $templates = []) { $this->templates = $templates; } /** * Adds or overrides a template. * * @param string $name The template name * @param string $template The template source */ public function setTemplate($name, $template) { $this->templates[$name] = $template; } public function getSourceContext($name) { $name = (string) $name; if (!isset($this->templates[$name])) { throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); } return new Source($this->templates[$name], $name); } public function exists($name) { return isset($this->templates[$name]); } public function getCacheKey($name) { if (!isset($this->templates[$name])) { throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); } return $name.':'.$this->templates[$name]; } public function isFresh($name, $time) { if (!isset($this->templates[$name])) { throw new LoaderError(sprintf('Template "%s" is not defined.', $name)); } return true; } } class_alias('Twig\Loader\ArrayLoader', 'Twig_Loader_Array'); php-twig-2.12.5/src/Loader/ChainLoader.php000066400000000000000000000060371362457344700202440ustar00rootroot00000000000000 */ final class ChainLoader implements LoaderInterface, ExistsLoaderInterface, SourceContextLoaderInterface { private $hasSourceCache = []; private $loaders = []; /** * @param LoaderInterface[] $loaders */ public function __construct(array $loaders = []) { foreach ($loaders as $loader) { $this->addLoader($loader); } } public function addLoader(LoaderInterface $loader) { $this->loaders[] = $loader; $this->hasSourceCache = []; } /** * @return LoaderInterface[] */ public function getLoaders() { return $this->loaders; } public function getSourceContext($name) { $exceptions = []; foreach ($this->loaders as $loader) { if (!$loader->exists($name)) { continue; } try { return $loader->getSourceContext($name); } catch (LoaderError $e) { $exceptions[] = $e->getMessage(); } } throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); } public function exists($name) { 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 = []; foreach ($this->loaders as $loader) { if (!$loader->exists($name)) { continue; } try { return $loader->getCacheKey($name); } catch (LoaderError $e) { $exceptions[] = \get_class($loader).': '.$e->getMessage(); } } throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); } public function isFresh($name, $time) { $exceptions = []; foreach ($this->loaders as $loader) { if (!$loader->exists($name)) { continue; } try { return $loader->isFresh($name, $time); } catch (LoaderError $e) { $exceptions[] = \get_class($loader).': '.$e->getMessage(); } } throw new LoaderError(sprintf('Template "%s" is not defined%s.', $name, $exceptions ? ' ('.implode(', ', $exceptions).')' : '')); } } class_alias('Twig\Loader\ChainLoader', 'Twig_Loader_Chain'); php-twig-2.12.5/src/Loader/ExistsLoaderInterface.php000066400000000000000000000007351362457344700223210ustar00rootroot00000000000000 */ class FilesystemLoader implements LoaderInterface, ExistsLoaderInterface, SourceContextLoaderInterface { /** Identifier of the main namespace. */ const MAIN_NAMESPACE = '__main__'; protected $paths = []; protected $cache = []; protected $errorCache = []; private $rootPath; /** * @param string|array $paths A path or an array of paths where to look for templates * @param string|null $rootPath The root path common to all relative paths (null for getcwd()) */ public function __construct($paths = [], string $rootPath = null) { $this->rootPath = (null === $rootPath ? getcwd() : $rootPath).\DIRECTORY_SEPARATOR; if (false !== $realPath = realpath($rootPath)) { $this->rootPath = $realPath.\DIRECTORY_SEPARATOR; } if ($paths) { $this->setPaths($paths); } } /** * Returns the paths to the templates. * * @param string $namespace A path namespace * * @return array The array of paths where to look for templates */ public function getPaths($namespace = self::MAIN_NAMESPACE) { return isset($this->paths[$namespace]) ? $this->paths[$namespace] : []; } /** * Returns the path namespaces. * * The main namespace is always defined. * * @return array The array of defined namespaces */ public function getNamespaces() { return array_keys($this->paths); } /** * Sets the paths where templates are stored. * * @param string|array $paths A path or an array of paths where to look for templates * @param string $namespace A path namespace */ public function setPaths($paths, $namespace = self::MAIN_NAMESPACE) { if (!\is_array($paths)) { $paths = [$paths]; } $this->paths[$namespace] = []; foreach ($paths as $path) { $this->addPath($path, $namespace); } } /** * Adds a path where templates are stored. * * @param string $path A path where to look for templates * @param string $namespace A path namespace * * @throws LoaderError */ public function addPath($path, $namespace = self::MAIN_NAMESPACE) { // invalidate the cache $this->cache = $this->errorCache = []; $checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path; if (!is_dir($checkPath)) { throw new LoaderError(sprintf('The "%s" directory does not exist ("%s").', $path, $checkPath)); } $this->paths[$namespace][] = rtrim($path, '/\\'); } /** * Prepends a path where templates are stored. * * @param string $path A path where to look for templates * @param string $namespace A path namespace * * @throws LoaderError */ public function prependPath($path, $namespace = self::MAIN_NAMESPACE) { // invalidate the cache $this->cache = $this->errorCache = []; $checkPath = $this->isAbsolutePath($path) ? $path : $this->rootPath.$path; if (!is_dir($checkPath)) { throw new LoaderError(sprintf('The "%s" directory does not exist ("%s").', $path, $checkPath)); } $path = rtrim($path, '/\\'); if (!isset($this->paths[$namespace])) { $this->paths[$namespace][] = $path; } else { array_unshift($this->paths[$namespace], $path); } } public function getSourceContext($name) { if (null === ($path = $this->findTemplate($name)) || false === $path) { return new Source('', $name, ''); } return new Source(file_get_contents($path), $name, $path); } public function getCacheKey($name) { if (null === ($path = $this->findTemplate($name)) || false === $path) { return ''; } $len = \strlen($this->rootPath); if (0 === strncmp($this->rootPath, $path, $len)) { return substr($path, $len); } return $path; } public function exists($name) { $name = $this->normalizeName($name); if (isset($this->cache[$name])) { return true; } return null !== ($path = $this->findTemplate($name, false)) && false !== $path; } public function isFresh($name, $time) { // false support to be removed in 3.0 if (null === ($path = $this->findTemplate($name)) || false === $path) { return false; } return filemtime($path) < $time; } /** * Checks if the template can be found. * * In Twig 3.0, findTemplate must return a string or null (returning false won't work anymore). * * @param string $name The template name * @param bool $throw Whether to throw an exception when an error occurs * * @return string|false|null The template name or false/null */ 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 LoaderError($this->errorCache[$name]); } try { $this->validateName($name); list($namespace, $shortname) = $this->parseName($name); } catch (LoaderError $e) { if (!$throw) { return false; } throw $e; } if (!isset($this->paths[$namespace])) { $this->errorCache[$name] = sprintf('There are no registered paths for namespace "%s".', $namespace); if (!$throw) { return false; } throw new LoaderError($this->errorCache[$name]); } foreach ($this->paths[$namespace] as $path) { if (!$this->isAbsolutePath($path)) { $path = $this->rootPath.$path; } if (is_file($path.'/'.$shortname)) { if (false !== $realpath = realpath($path.'/'.$shortname)) { return $this->cache[$name] = $realpath; } return $this->cache[$name] = $path.'/'.$shortname; } } $this->errorCache[$name] = sprintf('Unable to find template "%s" (looked into: %s).', $name, implode(', ', $this->paths[$namespace])); if (!$throw) { return false; } throw new LoaderError($this->errorCache[$name]); } 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 LoaderError(sprintf('Malformed namespaced template name "%s" (expecting "@namespace/template_name").', $name)); } $namespace = substr($name, 1, $pos - 1); $shortname = substr($name, $pos + 1); return [$namespace, $shortname]; } return [$default, $name]; } private function validateName($name) { if (false !== strpos($name, "\0")) { throw new LoaderError('A template name cannot contain NUL bytes.'); } $name = ltrim($name, '/'); $parts = explode('/', $name); $level = 0; foreach ($parts as $part) { if ('..' === $part) { --$level; } elseif ('.' !== $part) { ++$level; } if ($level < 0) { throw new LoaderError(sprintf('Looks like you try to load a template outside configured directories (%s).', $name)); } } } private function isAbsolutePath($file) { return strspn($file, '/\\', 0, 1) || (\strlen($file) > 3 && ctype_alpha($file[0]) && ':' === $file[1] && strspn($file, '/\\', 2, 1) ) || null !== parse_url($file, PHP_URL_SCHEME) ; } } class_alias('Twig\Loader\FilesystemLoader', 'Twig_Loader_Filesystem'); php-twig-2.12.5/src/Loader/LoaderInterface.php000066400000000000000000000033331362457344700211160ustar00rootroot00000000000000 */ interface LoaderInterface { /** * Returns the source context for a given template logical name. * * @param string $name The template logical name * * @return Source * * @throws LoaderError When $name is not found */ public function getSourceContext($name); /** * Gets the cache key to use for the cache for a given template name. * * @param string $name The name of the template to load * * @return string The cache key * * @throws LoaderError When $name is not found */ public function getCacheKey($name); /** * Returns true if the template is still fresh. * * @param string $name The template name * @param int $time Timestamp of the last modification time of the * cached template * * @return bool true if the template is fresh, false otherwise * * @throws LoaderError When $name is not found */ public function isFresh($name, $time); /** * Check if we have the source code of a template, given its name. * * @param string $name The name of the template to check if we can load * * @return bool If the template source code is handled by this loader or not */ public function exists($name); } class_alias('Twig\Loader\LoaderInterface', 'Twig_LoaderInterface'); php-twig-2.12.5/src/Loader/SourceContextLoaderInterface.php000066400000000000000000000006731362457344700236500ustar00rootroot00000000000000 */ class 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'); php-twig-2.12.5/src/Node/000077500000000000000000000000001362457344700150335ustar00rootroot00000000000000php-twig-2.12.5/src/Node/AutoEscapeNode.php000066400000000000000000000016231362457344700204050ustar00rootroot00000000000000 */ class AutoEscapeNode extends Node { public function __construct($value, Node $body, int $lineno, string $tag = 'autoescape') { parent::__construct(['body' => $body], ['value' => $value], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler->subcompile($this->getNode('body')); } } class_alias('Twig\Node\AutoEscapeNode', 'Twig_Node_AutoEscape'); php-twig-2.12.5/src/Node/BlockNode.php000066400000000000000000000020741362457344700174070ustar00rootroot00000000000000 */ class BlockNode extends Node { public function __construct(string $name, Node $body, int $lineno, string $tag = null) { parent::__construct(['body' => $body], ['name' => $name], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write(sprintf("public function block_%s(\$context, array \$blocks = [])\n", $this->getAttribute('name')), "{\n") ->indent() ->write("\$macros = \$this->macros;\n") ; $compiler ->subcompile($this->getNode('body')) ->outdent() ->write("}\n\n") ; } } class_alias('Twig\Node\BlockNode', 'Twig_Node_Block'); php-twig-2.12.5/src/Node/BlockReferenceNode.php000066400000000000000000000016031362457344700212230ustar00rootroot00000000000000 */ class BlockReferenceNode extends Node implements NodeOutputInterface { public function __construct(string $name, int $lineno, string $tag = null) { parent::__construct([], ['name' => $name], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write(sprintf("\$this->displayBlock('%s', \$context, \$blocks);\n", $this->getAttribute('name'))) ; } } class_alias('Twig\Node\BlockReferenceNode', 'Twig_Node_BlockReference'); php-twig-2.12.5/src/Node/BodyNode.php000066400000000000000000000006151362457344700172510ustar00rootroot00000000000000 */ class BodyNode extends Node { } class_alias('Twig\Node\BodyNode', 'Twig_Node_Body'); php-twig-2.12.5/src/Node/CheckSecurityNode.php000066400000000000000000000060031362457344700211160ustar00rootroot00000000000000 */ class CheckSecurityNode extends 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(Compiler $compiler) { $tags = $filters = $functions = []; foreach (['tags', 'filters', 'functions'] as $type) { foreach ($this->{'used'.ucfirst($type)} as $name => $node) { if ($node instanceof Node) { ${$type}[$name] = $node->getTemplateLine(); } else { ${$type}[$node] = null; } } } $compiler ->write("\$this->sandbox = \$this->env->getExtension('\Twig\Extension\SandboxExtension');\n") ->write('$tags = ')->repr(array_filter($tags))->raw(";\n") ->write('$filters = ')->repr(array_filter($filters))->raw(";\n") ->write('$functions = ')->repr(array_filter($functions))->raw(";\n\n") ->write("try {\n") ->indent() ->write("\$this->sandbox->checkSecurity(\n") ->indent() ->write(!$tags ? "[],\n" : "['".implode("', '", array_keys($tags))."'],\n") ->write(!$filters ? "[],\n" : "['".implode("', '", array_keys($filters))."'],\n") ->write(!$functions ? "[]\n" : "['".implode("', '", array_keys($functions))."']\n") ->outdent() ->write(");\n") ->outdent() ->write("} catch (SecurityError \$e) {\n") ->indent() ->write("\$e->setSourceContext(\$this->source);\n\n") ->write("if (\$e instanceof SecurityNotAllowedTagError && isset(\$tags[\$e->getTagName()])) {\n") ->indent() ->write("\$e->setTemplateLine(\$tags[\$e->getTagName()]);\n") ->outdent() ->write("} elseif (\$e instanceof SecurityNotAllowedFilterError && isset(\$filters[\$e->getFilterName()])) {\n") ->indent() ->write("\$e->setTemplateLine(\$filters[\$e->getFilterName()]);\n") ->outdent() ->write("} elseif (\$e instanceof SecurityNotAllowedFunctionError && isset(\$functions[\$e->getFunctionName()])) {\n") ->indent() ->write("\$e->setTemplateLine(\$functions[\$e->getFunctionName()]);\n") ->outdent() ->write("}\n\n") ->write("throw \$e;\n") ->outdent() ->write("}\n\n") ; } } class_alias('Twig\Node\CheckSecurityNode', 'Twig_Node_CheckSecurity'); php-twig-2.12.5/src/Node/CheckToStringNode.php000066400000000000000000000023361362457344700210650ustar00rootroot00000000000000 */ class CheckToStringNode extends AbstractExpression { public function __construct(AbstractExpression $expr) { parent::__construct(['expr' => $expr], [], $expr->getTemplateLine(), $expr->getNodeTag()); } public function compile(Compiler $compiler) { $expr = $this->getNode('expr'); $compiler ->raw('$this->sandbox->ensureToStringAllowed(') ->subcompile($expr) ->raw(', ') ->repr($expr->getTemplateLine()) ->raw(', $this->source)') ; } } php-twig-2.12.5/src/Node/DeprecatedNode.php000066400000000000000000000026451362457344700204210ustar00rootroot00000000000000 */ class DeprecatedNode extends Node { public function __construct(AbstractExpression $expr, int $lineno, string $tag = null) { parent::__construct(['expr' => $expr], [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); $expr = $this->getNode('expr'); if ($expr instanceof ConstantExpression) { $compiler->write('@trigger_error(') ->subcompile($expr); } else { $varName = $compiler->getVarName(); $compiler->write(sprintf('$%s = ', $varName)) ->subcompile($expr) ->raw(";\n") ->write(sprintf('@trigger_error($%s', $varName)); } $compiler ->raw('.') ->string(sprintf(' ("%s" at line %d).', $this->getTemplateName(), $this->getTemplateLine())) ->raw(", E_USER_DEPRECATED);\n") ; } } class_alias('Twig\Node\DeprecatedNode', 'Twig_Node_Deprecated'); php-twig-2.12.5/src/Node/DoNode.php000066400000000000000000000015151362457344700167160ustar00rootroot00000000000000 */ class DoNode extends Node { public function __construct(AbstractExpression $expr, int $lineno, string $tag = null) { parent::__construct(['expr' => $expr], [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('') ->subcompile($this->getNode('expr')) ->raw(";\n") ; } } class_alias('Twig\Node\DoNode', 'Twig_Node_Do'); php-twig-2.12.5/src/Node/EmbedNode.php000066400000000000000000000027121362457344700173700ustar00rootroot00000000000000 */ class EmbedNode extends IncludeNode { // we don't inject the module to avoid node visitors to traverse it twice (as it will be already visited in the main module) public function __construct(string $name, int $index, AbstractExpression $variables = null, bool $only = false, bool $ignoreMissing = false, int $lineno, string $tag = null) { parent::__construct(new ConstantExpression('not_used', $lineno), $variables, $only, $ignoreMissing, $lineno, $tag); $this->setAttribute('name', $name); $this->setAttribute('index', $index); } protected function addGetTemplate(Compiler $compiler) { $compiler ->write('$this->loadTemplate(') ->string($this->getAttribute('name')) ->raw(', ') ->repr($this->getTemplateName()) ->raw(', ') ->repr($this->getTemplateLine()) ->raw(', ') ->string($this->getAttribute('index')) ->raw(')') ; } } class_alias('Twig\Node\EmbedNode', 'Twig_Node_Embed'); php-twig-2.12.5/src/Node/Expression/000077500000000000000000000000001362457344700171725ustar00rootroot00000000000000php-twig-2.12.5/src/Node/Expression/AbstractExpression.php000066400000000000000000000010251362457344700235240ustar00rootroot00000000000000 */ abstract class AbstractExpression extends Node { } class_alias('Twig\Node\Expression\AbstractExpression', 'Twig_Node_Expression'); php-twig-2.12.5/src/Node/Expression/ArrayExpression.php000066400000000000000000000044171362457344700230470ustar00rootroot00000000000000index = -1; foreach ($this->getKeyValuePairs() as $pair) { if ($pair['key'] instanceof ConstantExpression && ctype_digit((string) $pair['key']->getAttribute('value')) && $pair['key']->getAttribute('value') > $this->index) { $this->index = $pair['key']->getAttribute('value'); } } } public function getKeyValuePairs() { $pairs = []; foreach (array_chunk($this->nodes, 2) as $pair) { $pairs[] = [ 'key' => $pair[0], 'value' => $pair[1], ]; } return $pairs; } public function hasElement(AbstractExpression $key) { foreach ($this->getKeyValuePairs() as $pair) { // we compare the string representation of the keys // to avoid comparing the line numbers which are not relevant here. if ((string) $key === (string) $pair['key']) { return true; } } return false; } public function addElement(AbstractExpression $value, AbstractExpression $key = null) { if (null === $key) { $key = new ConstantExpression(++$this->index, $value->getTemplateLine()); } array_push($this->nodes, $key, $value); } public function compile(Compiler $compiler) { $compiler->raw('['); $first = true; foreach ($this->getKeyValuePairs() as $pair) { if (!$first) { $compiler->raw(', '); } $first = false; $compiler ->subcompile($pair['key']) ->raw(' => ') ->subcompile($pair['value']) ; } $compiler->raw(']'); } } class_alias('Twig\Node\Expression\ArrayExpression', 'Twig_Node_Expression_Array'); php-twig-2.12.5/src/Node/Expression/ArrowFunctionExpression.php000066400000000000000000000030451362457344700245650ustar00rootroot00000000000000 */ class ArrowFunctionExpression extends AbstractExpression { public function __construct(AbstractExpression $expr, Node $names, $lineno, $tag = null) { parent::__construct(['expr' => $expr, 'names' => $names], [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->raw('function (') ; foreach ($this->getNode('names') as $i => $name) { if ($i) { $compiler->raw(', '); } $compiler ->raw('$__') ->raw($name->getAttribute('name')) ->raw('__') ; } $compiler ->raw(') use ($context, $macros) { ') ; foreach ($this->getNode('names') as $name) { $compiler ->raw('$context["') ->raw($name->getAttribute('name')) ->raw('"] = $__') ->raw($name->getAttribute('name')) ->raw('__; ') ; } $compiler ->raw('return ') ->subcompile($this->getNode('expr')) ->raw('; }') ; } } php-twig-2.12.5/src/Node/Expression/AssignNameExpression.php000066400000000000000000000011511362457344700240060ustar00rootroot00000000000000raw('$context[') ->string($this->getAttribute('name')) ->raw(']') ; } } class_alias('Twig\Node\Expression\AssignNameExpression', 'Twig_Node_Expression_AssignName'); php-twig-2.12.5/src/Node/Expression/Binary/000077500000000000000000000000001362457344700204165ustar00rootroot00000000000000php-twig-2.12.5/src/Node/Expression/Binary/AbstractBinary.php000066400000000000000000000020531362457344700240370ustar00rootroot00000000000000 $left, 'right' => $right], [], $lineno); } public function compile(Compiler $compiler) { $compiler ->raw('(') ->subcompile($this->getNode('left')) ->raw(' ') ; $this->operator($compiler); $compiler ->raw(' ') ->subcompile($this->getNode('right')) ->raw(')') ; } abstract public function operator(Compiler $compiler); } class_alias('Twig\Node\Expression\Binary\AbstractBinary', 'Twig_Node_Expression_Binary'); php-twig-2.12.5/src/Node/Expression/Binary/AddBinary.php000066400000000000000000000010021362457344700227550ustar00rootroot00000000000000raw('+'); } } class_alias('Twig\Node\Expression\Binary\AddBinary', 'Twig_Node_Expression_Binary_Add'); php-twig-2.12.5/src/Node/Expression/Binary/AndBinary.php000066400000000000000000000010031362457344700227700ustar00rootroot00000000000000raw('&&'); } } class_alias('Twig\Node\Expression\Binary\AndBinary', 'Twig_Node_Expression_Binary_And'); php-twig-2.12.5/src/Node/Expression/Binary/BitwiseAndBinary.php000066400000000000000000000010271362457344700243250ustar00rootroot00000000000000raw('&'); } } class_alias('Twig\Node\Expression\Binary\BitwiseAndBinary', 'Twig_Node_Expression_Binary_BitwiseAnd'); php-twig-2.12.5/src/Node/Expression/Binary/BitwiseOrBinary.php000066400000000000000000000010241362457344700242000ustar00rootroot00000000000000raw('|'); } } class_alias('Twig\Node\Expression\Binary\BitwiseOrBinary', 'Twig_Node_Expression_Binary_BitwiseOr'); php-twig-2.12.5/src/Node/Expression/Binary/BitwiseXorBinary.php000066400000000000000000000010271362457344700243730ustar00rootroot00000000000000raw('^'); } } class_alias('Twig\Node\Expression\Binary\BitwiseXorBinary', 'Twig_Node_Expression_Binary_BitwiseXor'); php-twig-2.12.5/src/Node/Expression/Binary/ConcatBinary.php000066400000000000000000000010131362457344700234760ustar00rootroot00000000000000raw('.'); } } class_alias('Twig\Node\Expression\Binary\ConcatBinary', 'Twig_Node_Expression_Binary_Concat'); php-twig-2.12.5/src/Node/Expression/Binary/DivBinary.php000066400000000000000000000010021362457344700230070ustar00rootroot00000000000000raw('/'); } } class_alias('Twig\Node\Expression\Binary\DivBinary', 'Twig_Node_Expression_Binary_Div'); php-twig-2.12.5/src/Node/Expression/Binary/EndsWithBinary.php000066400000000000000000000017531362457344700240270ustar00rootroot00000000000000getVarName(); $right = $compiler->getVarName(); $compiler ->raw(sprintf('(is_string($%s = ', $left)) ->subcompile($this->getNode('left')) ->raw(sprintf(') && is_string($%s = ', $right)) ->subcompile($this->getNode('right')) ->raw(sprintf(') && (\'\' === $%2$s || $%2$s === substr($%1$s, -strlen($%2$s))))', $left, $right)) ; } public function operator(Compiler $compiler) { return $compiler->raw(''); } } class_alias('Twig\Node\Expression\Binary\EndsWithBinary', 'Twig_Node_Expression_Binary_EndsWith'); php-twig-2.12.5/src/Node/Expression/Binary/EqualBinary.php000066400000000000000000000007631362457344700233510ustar00rootroot00000000000000raw('=='); } } class_alias('Twig\Node\Expression\Binary\EqualBinary', 'Twig_Node_Expression_Binary_Equal'); php-twig-2.12.5/src/Node/Expression/Binary/FloorDivBinary.php000066400000000000000000000012411362457344700240160ustar00rootroot00000000000000raw('(int) floor('); parent::compile($compiler); $compiler->raw(')'); } public function operator(Compiler $compiler) { return $compiler->raw('/'); } } class_alias('Twig\Node\Expression\Binary\FloorDivBinary', 'Twig_Node_Expression_Binary_FloorDiv'); php-twig-2.12.5/src/Node/Expression/Binary/GreaterBinary.php000066400000000000000000000007701362457344700236710ustar00rootroot00000000000000raw('>'); } } class_alias('Twig\Node\Expression\Binary\GreaterBinary', 'Twig_Node_Expression_Binary_Greater'); php-twig-2.12.5/src/Node/Expression/Binary/GreaterEqualBinary.php000066400000000000000000000010101362457344700246450ustar00rootroot00000000000000raw('>='); } } class_alias('Twig\Node\Expression\Binary\GreaterEqualBinary', 'Twig_Node_Expression_Binary_GreaterEqual'); php-twig-2.12.5/src/Node/Expression/Binary/InBinary.php000066400000000000000000000013721362457344700226450ustar00rootroot00000000000000raw('twig_in_filter(') ->subcompile($this->getNode('left')) ->raw(', ') ->subcompile($this->getNode('right')) ->raw(')') ; } public function operator(Compiler $compiler) { return $compiler->raw('in'); } } class_alias('Twig\Node\Expression\Binary\InBinary', 'Twig_Node_Expression_Binary_In'); php-twig-2.12.5/src/Node/Expression/Binary/LessBinary.php000066400000000000000000000007571362457344700232130ustar00rootroot00000000000000raw('<'); } } class_alias('Twig\Node\Expression\Binary\LessBinary', 'Twig_Node_Expression_Binary_Less'); php-twig-2.12.5/src/Node/Expression/Binary/LessEqualBinary.php000066400000000000000000000007771362457344700242050ustar00rootroot00000000000000raw('<='); } } class_alias('Twig\Node\Expression\Binary\LessEqualBinary', 'Twig_Node_Expression_Binary_LessEqual'); php-twig-2.12.5/src/Node/Expression/Binary/MatchesBinary.php000066400000000000000000000014031362457344700236560ustar00rootroot00000000000000raw('preg_match(') ->subcompile($this->getNode('right')) ->raw(', ') ->subcompile($this->getNode('left')) ->raw(')') ; } public function operator(Compiler $compiler) { return $compiler->raw(''); } } class_alias('Twig\Node\Expression\Binary\MatchesBinary', 'Twig_Node_Expression_Binary_Matches'); php-twig-2.12.5/src/Node/Expression/Binary/ModBinary.php000066400000000000000000000010021362457344700230040ustar00rootroot00000000000000raw('%'); } } class_alias('Twig\Node\Expression\Binary\ModBinary', 'Twig_Node_Expression_Binary_Mod'); php-twig-2.12.5/src/Node/Expression/Binary/MulBinary.php000066400000000000000000000010021362457344700230220ustar00rootroot00000000000000raw('*'); } } class_alias('Twig\Node\Expression\Binary\MulBinary', 'Twig_Node_Expression_Binary_Mul'); php-twig-2.12.5/src/Node/Expression/Binary/NotEqualBinary.php000066400000000000000000000007741362457344700240340ustar00rootroot00000000000000raw('!='); } } class_alias('Twig\Node\Expression\Binary\NotEqualBinary', 'Twig_Node_Expression_Binary_NotEqual'); php-twig-2.12.5/src/Node/Expression/Binary/NotInBinary.php000066400000000000000000000014101362457344700233170ustar00rootroot00000000000000raw('!twig_in_filter(') ->subcompile($this->getNode('left')) ->raw(', ') ->subcompile($this->getNode('right')) ->raw(')') ; } public function operator(Compiler $compiler) { return $compiler->raw('not in'); } } class_alias('Twig\Node\Expression\Binary\NotInBinary', 'Twig_Node_Expression_Binary_NotIn'); php-twig-2.12.5/src/Node/Expression/Binary/OrBinary.php000066400000000000000000000010001362457344700226430ustar00rootroot00000000000000raw('||'); } } class_alias('Twig\Node\Expression\Binary\OrBinary', 'Twig_Node_Expression_Binary_Or'); php-twig-2.12.5/src/Node/Expression/Binary/PowerBinary.php000066400000000000000000000007631362457344700233760ustar00rootroot00000000000000raw('**'); } } class_alias('Twig\Node\Expression\Binary\PowerBinary', 'Twig_Node_Expression_Binary_Power'); php-twig-2.12.5/src/Node/Expression/Binary/RangeBinary.php000066400000000000000000000013721362457344700233330ustar00rootroot00000000000000raw('range(') ->subcompile($this->getNode('left')) ->raw(', ') ->subcompile($this->getNode('right')) ->raw(')') ; } public function operator(Compiler $compiler) { return $compiler->raw('..'); } } class_alias('Twig\Node\Expression\Binary\RangeBinary', 'Twig_Node_Expression_Binary_Range'); php-twig-2.12.5/src/Node/Expression/Binary/SpaceshipBinary.php000066400000000000000000000006321362457344700242140ustar00rootroot00000000000000raw('<=>'); } } php-twig-2.12.5/src/Node/Expression/Binary/StartsWithBinary.php000066400000000000000000000017441362457344700244160ustar00rootroot00000000000000getVarName(); $right = $compiler->getVarName(); $compiler ->raw(sprintf('(is_string($%s = ', $left)) ->subcompile($this->getNode('left')) ->raw(sprintf(') && is_string($%s = ', $right)) ->subcompile($this->getNode('right')) ->raw(sprintf(') && (\'\' === $%2$s || 0 === strpos($%1$s, $%2$s)))', $left, $right)) ; } public function operator(Compiler $compiler) { return $compiler->raw(''); } } class_alias('Twig\Node\Expression\Binary\StartsWithBinary', 'Twig_Node_Expression_Binary_StartsWith'); php-twig-2.12.5/src/Node/Expression/Binary/SubBinary.php000066400000000000000000000010021362457344700230160ustar00rootroot00000000000000raw('-'); } } class_alias('Twig\Node\Expression\Binary\SubBinary', 'Twig_Node_Expression_Binary_Sub'); php-twig-2.12.5/src/Node/Expression/BlockReferenceExpression.php000066400000000000000000000045451362457344700246440ustar00rootroot00000000000000 */ class BlockReferenceExpression extends AbstractExpression { public function __construct(Node $name, Node $template = null, int $lineno, string $tag = null) { $nodes = ['name' => $name]; if (null !== $template) { $nodes['template'] = $template; } parent::__construct($nodes, ['is_defined_test' => false, 'output' => false], $lineno, $tag); } public function compile(Compiler $compiler) { if ($this->getAttribute('is_defined_test')) { $this->compileTemplateCall($compiler, 'hasBlock'); } else { if ($this->getAttribute('output')) { $compiler->addDebugInfo($this); $this ->compileTemplateCall($compiler, 'displayBlock') ->raw(";\n"); } else { $this->compileTemplateCall($compiler, 'renderBlock'); } } } private function compileTemplateCall(Compiler $compiler, string $method): Compiler { 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)); return $this->compileBlockArguments($compiler); } private function compileBlockArguments(Compiler $compiler): Compiler { $compiler ->raw('(') ->subcompile($this->getNode('name')) ->raw(', $context'); if (!$this->hasNode('template')) { $compiler->raw(', $blocks'); } return $compiler->raw(')'); } } class_alias('Twig\Node\Expression\BlockReferenceExpression', 'Twig_Node_Expression_BlockReference'); php-twig-2.12.5/src/Node/Expression/CallExpression.php000066400000000000000000000277471362457344700226570ustar00rootroot00000000000000getAttribute('callable'); $closingParenthesis = false; $isArray = 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 ExtensionInterface) { // For BC/FC with namespaced aliases $class = (new \ReflectionClass(\get_class($callable[0])))->name; if (!$compiler->getEnvironment()->hasExtension($class)) { // Compile a non-optimized call to trigger a \Twig\Error\RuntimeError, which cannot be a compile-time error $compiler->raw(sprintf('$this->env->getExtension(\'%s\')', $class)); } else { $compiler->raw(sprintf('$this->extensions[\'%s\']', ltrim($class, '\\'))); } $compiler->raw(sprintf('->%s', $callable[1])); } else { $closingParenthesis = true; $isArray = true; $compiler->raw(sprintf('call_user_func_array($this->env->get%s(\'%s\')->getCallable(), ', ucfirst($this->getAttribute('type')), $this->getAttribute('name'))); } } $this->compileArguments($compiler, $isArray); if ($closingParenthesis) { $compiler->raw(')'); } } protected function compileArguments(Compiler $compiler, $isArray = false) { $compiler->raw($isArray ? '[' : '('); $first = true; if ($this->hasAttribute('needs_environment') && $this->getAttribute('needs_environment')) { $compiler->raw('$this->env'); $first = false; } if ($this->hasAttribute('needs_context') && $this->getAttribute('needs_context')) { if (!$first) { $compiler->raw(', '); } $compiler->raw('$context'); $first = false; } if ($this->hasAttribute('arguments')) { foreach ($this->getAttribute('arguments') as $argument) { if (!$first) { $compiler->raw(', '); } $compiler->string($argument); $first = false; } } if ($this->hasNode('node')) { if (!$first) { $compiler->raw(', '); } $compiler->subcompile($this->getNode('node')); $first = false; } if ($this->hasNode('arguments')) { $callable = $this->getAttribute('callable'); $arguments = $this->getArguments($callable, $this->getNode('arguments')); foreach ($arguments as $node) { if (!$first) { $compiler->raw(', '); } $compiler->subcompile($node); $first = false; } } $compiler->raw($isArray ? ']' : ')'); } protected function getArguments($callable = null, $arguments) { $callType = $this->getAttribute('type'); $callName = $this->getAttribute('name'); $parameters = []; $named = false; foreach ($arguments as $name => $node) { if (!\is_int($name)) { $named = true; $name = $this->normalizeName($name); } elseif ($named) { throw new SyntaxError(sprintf('Positional arguments cannot be used after named arguments for %s "%s".', $callType, $callName), $this->getTemplateLine(), $this->getSourceContext()); } $parameters[$name] = $node; } $isVariadic = $this->hasAttribute('is_variadic') && $this->getAttribute('is_variadic'); if (!$named && !$isVariadic) { return $parameters; } if (!$callable) { if ($named) { $message = sprintf('Named arguments are not supported for %s "%s".', $callType, $callName); } else { $message = sprintf('Arbitrary positional arguments are not supported for %s "%s".', $callType, $callName); } throw new \LogicException($message); } list($callableParameters, $isPhpVariadic) = $this->getCallableParameters($callable, $isVariadic); $arguments = []; $names = []; $missingArguments = []; $optionalArguments = []; $pos = 0; foreach ($callableParameters as $callableParameter) { $names[] = $name = $this->normalizeName($callableParameter->name); if (\array_key_exists($name, $parameters)) { if (\array_key_exists($pos, $parameters)) { throw new SyntaxError(sprintf('Argument "%s" is defined twice for %s "%s".', $name, $callType, $callName), $this->getTemplateLine(), $this->getSourceContext()); } if (\count($missingArguments)) { throw new SyntaxError(sprintf( 'Argument "%s" could not be assigned for %s "%s(%s)" because it is mapped to an internal PHP function which cannot determine default value for optional argument%s "%s".', $name, $callType, $callName, implode(', ', $names), \count($missingArguments) > 1 ? 's' : '', implode('", "', $missingArguments) ), $this->getTemplateLine(), $this->getSourceContext()); } $arguments = array_merge($arguments, $optionalArguments); $arguments[] = $parameters[$name]; unset($parameters[$name]); $optionalArguments = []; } elseif (\array_key_exists($pos, $parameters)) { $arguments = array_merge($arguments, $optionalArguments); $arguments[] = $parameters[$pos]; unset($parameters[$pos]); $optionalArguments = []; ++$pos; } elseif ($callableParameter->isDefaultValueAvailable()) { $optionalArguments[] = new ConstantExpression($callableParameter->getDefaultValue(), -1); } elseif ($callableParameter->isOptional()) { if (empty($parameters)) { break; } else { $missingArguments[] = $name; } } else { throw new SyntaxError(sprintf('Value for argument "%s" is required for %s "%s".', $name, $callType, $callName), $this->getTemplateLine(), $this->getSourceContext()); } } if ($isVariadic) { $arbitraryArguments = $isPhpVariadic ? new VariadicExpression([], -1) : new ArrayExpression([], -1); foreach ($parameters as $key => $value) { if (\is_int($key)) { $arbitraryArguments->addElement($value); } else { $arbitraryArguments->addElement($value, new ConstantExpression($key, -1)); } unset($parameters[$key]); } if ($arbitraryArguments->count()) { $arguments = array_merge($arguments, $optionalArguments); $arguments[] = $arbitraryArguments; } } if (!empty($parameters)) { $unknownParameter = null; foreach ($parameters as $parameter) { if ($parameter instanceof Node) { $unknownParameter = $parameter; break; } } throw new SyntaxError( sprintf( 'Unknown argument%s "%s" for %s "%s(%s)".', \count($parameters) > 1 ? 's' : '', implode('", "', array_keys($parameters)), $callType, $callName, implode(', ', $names) ), $unknownParameter ? $unknownParameter->getTemplateLine() : $this->getTemplateLine(), $unknownParameter ? $unknownParameter->getSourceContext() : $this->getSourceContext() ); } return $arguments; } protected function normalizeName($name) { return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/', '/([a-z\d])([A-Z])/'], ['\\1_\\2', '\\1_\\2'], $name)); } private function getCallableParameters($callable, bool $isVariadic): array { list($r) = $this->reflectCallable($callable); if (null === $r) { return [[], false]; } $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); } } $isPhpVariadic = false; if ($isVariadic) { $argument = end($parameters); if ($argument && $argument->isArray() && $argument->isDefaultValueAvailable() && [] === $argument->getDefaultValue()) { array_pop($parameters); } elseif ($argument && $argument->isVariadic()) { array_pop($parameters); $isPhpVariadic = true; } else { $callableName = $r->name; if ($r instanceof \ReflectionMethod) { $callableName = $r->getDeclaringClass()->name.'::'.$callableName; } throw new \LogicException(sprintf('The last parameter of "%s" for %s "%s" must be an array with default value, eg. "array $arg = []".', $callableName, $this->getAttribute('type'), $this->getAttribute('name'))); } } return [$parameters, $isPhpVariadic]; } private function reflectCallable($callable) { if (null !== $this->reflector) { return $this->reflector; } if (\is_array($callable)) { if (!method_exists($callable[0], $callable[1])) { // __call() return [null, []]; } $r = new \ReflectionMethod($callable[0], $callable[1]); } elseif (\is_object($callable) && !$callable instanceof \Closure) { $r = new \ReflectionObject($callable); $r = $r->getMethod('__invoke'); $callable = [$callable, '__invoke']; } elseif (\is_string($callable) && false !== $pos = strpos($callable, '::')) { $class = substr($callable, 0, $pos); $method = substr($callable, $pos + 2); if (!method_exists($class, $method)) { // __staticCall() return [null, []]; } $r = new \ReflectionMethod($callable); $callable = [$class, $method]; } else { $r = new \ReflectionFunction($callable); } return $this->reflector = [$r, $callable]; } } class_alias('Twig\Node\Expression\CallExpression', 'Twig_Node_Expression_Call'); php-twig-2.12.5/src/Node/Expression/ConditionalExpression.php000066400000000000000000000017641362457344700242360ustar00rootroot00000000000000 $expr1, 'expr2' => $expr2, 'expr3' => $expr3], [], $lineno); } public function compile(Compiler $compiler) { $compiler ->raw('((') ->subcompile($this->getNode('expr1')) ->raw(') ? (') ->subcompile($this->getNode('expr2')) ->raw(') : (') ->subcompile($this->getNode('expr3')) ->raw('))') ; } } class_alias('Twig\Node\Expression\ConditionalExpression', 'Twig_Node_Expression_Conditional'); php-twig-2.12.5/src/Node/Expression/ConstantExpression.php000066400000000000000000000012331362457344700235530ustar00rootroot00000000000000 $value], $lineno); } public function compile(Compiler $compiler) { $compiler->repr($this->getAttribute('value')); } } class_alias('Twig\Node\Expression\ConstantExpression', 'Twig_Node_Expression_Constant'); php-twig-2.12.5/src/Node/Expression/Filter/000077500000000000000000000000001362457344700204175ustar00rootroot00000000000000php-twig-2.12.5/src/Node/Expression/Filter/DefaultFilter.php000066400000000000000000000035331362457344700236660ustar00rootroot00000000000000 */ class DefaultFilter extends FilterExpression { public function __construct(Node $node, ConstantExpression $filterName, Node $arguments, int $lineno, string $tag = null) { $default = new FilterExpression($node, new ConstantExpression('default', $node->getTemplateLine()), $arguments, $node->getTemplateLine()); if ('default' === $filterName->getAttribute('value') && ($node instanceof NameExpression || $node instanceof GetAttrExpression)) { $test = new DefinedTest(clone $node, 'defined', new Node(), $node->getTemplateLine()); $false = \count($arguments) ? $arguments->getNode(0) : new ConstantExpression('', $node->getTemplateLine()); $node = new ConditionalExpression($test, $default, $false, $node->getTemplateLine()); } else { $node = $default; } parent::__construct($node, $filterName, $arguments, $lineno, $tag); } public function compile(Compiler $compiler) { $compiler->subcompile($this->getNode('node')); } } class_alias('Twig\Node\Expression\Filter\DefaultFilter', 'Twig_Node_Expression_Filter_Default'); php-twig-2.12.5/src/Node/Expression/FilterExpression.php000066400000000000000000000025261362457344700232150ustar00rootroot00000000000000 $node, 'filter' => $filterName, 'arguments' => $arguments], [], $lineno, $tag); } public function compile(Compiler $compiler) { $name = $this->getNode('filter')->getAttribute('value'); $filter = $compiler->getEnvironment()->getFilter($name); $this->setAttribute('name', $name); $this->setAttribute('type', 'filter'); $this->setAttribute('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\FilterExpression', 'Twig_Node_Expression_Filter'); php-twig-2.12.5/src/Node/Expression/FunctionExpression.php000066400000000000000000000026661362457344700235620ustar00rootroot00000000000000 $arguments], ['name' => $name, 'is_defined_test' => false], $lineno); } public function compile(Compiler $compiler) { $name = $this->getAttribute('name'); $function = $compiler->getEnvironment()->getFunction($name); $this->setAttribute('name', $name); $this->setAttribute('type', 'function'); $this->setAttribute('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\FunctionExpression', 'Twig_Node_Expression_Function'); php-twig-2.12.5/src/Node/Expression/GetAttrExpression.php000066400000000000000000000054741362457344700233470ustar00rootroot00000000000000 $node, 'attribute' => $attribute]; if (null !== $arguments) { $nodes['arguments'] = $arguments; } parent::__construct($nodes, ['type' => $type, 'is_defined_test' => false, 'ignore_strict_check' => false, 'optimizable' => true], $lineno); } public function compile(Compiler $compiler) { $env = $compiler->getEnvironment(); // optimize array calls if ( $this->getAttribute('optimizable') && (!$env->isStrictVariables() || $this->getAttribute('ignore_strict_check')) && !$this->getAttribute('is_defined_test') && 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')) ->raw(', ') ->subcompile($this->getNode('attribute')) ; if ($this->hasNode('arguments')) { $compiler->raw(', ')->subcompile($this->getNode('arguments')); } else { $compiler->raw(', []'); } $compiler->raw(', ') ->repr($this->getAttribute('type')) ->raw(', ')->repr($this->getAttribute('is_defined_test')) ->raw(', ')->repr($this->getAttribute('ignore_strict_check')) ->raw(', ')->repr($env->hasExtension(SandboxExtension::class)) ->raw(', ')->repr($this->getNode('node')->getTemplateLine()) ->raw(')') ; } } class_alias('Twig\Node\Expression\GetAttrExpression', 'Twig_Node_Expression_GetAttr'); php-twig-2.12.5/src/Node/Expression/InlinePrint.php000066400000000000000000000012331362457344700221350ustar00rootroot00000000000000 $node], [], $lineno); } public function compile(Compiler $compiler) { $compiler ->raw('print (') ->subcompile($this->getNode('node')) ->raw(')') ; } } php-twig-2.12.5/src/Node/Expression/MethodCallExpression.php000066400000000000000000000035141362457344700240020ustar00rootroot00000000000000 $node, 'arguments' => $arguments], ['method' => $method, 'safe' => false, 'is_defined_test' => false], $lineno); if ($node instanceof NameExpression) { $node->setAttribute('always_defined', true); } } public function compile(Compiler $compiler) { if ($this->getAttribute('is_defined_test')) { $compiler ->raw('method_exists($macros[') ->repr($this->getNode('node')->getAttribute('name')) ->raw('], ') ->repr($this->getAttribute('method')) ->raw(')') ; return; } $compiler ->raw('twig_call_macro($macros[') ->repr($this->getNode('node')->getAttribute('name')) ->raw('], ') ->repr($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('], ') ->repr($this->getTemplateLine()) ->raw(', $context, $this->getSourceContext())'); } } class_alias('Twig\Node\Expression\MethodCallExpression', 'Twig_Node_Expression_MethodCall'); php-twig-2.12.5/src/Node/Expression/NameExpression.php000066400000000000000000000057461362457344700226570ustar00rootroot00000000000000 '$this->getTemplateName()', '_context' => '$context', '_charset' => '$this->env->getCharset()', ]; public function __construct(string $name, int $lineno) { parent::__construct([], ['name' => $name, 'is_defined_test' => false, 'ignore_strict_check' => false, 'always_defined' => false], $lineno); } public function compile(Compiler $compiler) { $name = $this->getAttribute('name'); $compiler->addDebugInfo($this); if ($this->getAttribute('is_defined_test')) { if ($this->isSpecial()) { $compiler->repr(true); } elseif (\PHP_VERSION_ID >= 700400) { $compiler ->raw('array_key_exists(') ->string($name) ->raw(', $context)') ; } else { $compiler ->raw('(isset($context[') ->string($name) ->raw(']) || array_key_exists(') ->string($name) ->raw(', $context))') ; } } elseif ($this->isSpecial()) { $compiler->raw($this->specialVars[$name]); } elseif ($this->getAttribute('always_defined')) { $compiler ->raw('$context[') ->string($name) ->raw(']') ; } else { if ($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 RuntimeError(\'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\NameExpression', 'Twig_Node_Expression_Name'); php-twig-2.12.5/src/Node/Expression/NullCoalesceExpression.php000066400000000000000000000042221362457344700243340ustar00rootroot00000000000000getTemplateLine()); // for "block()", we don't need the null test as the return value is always a string if (!$left instanceof BlockReferenceExpression) { $test = new AndBinary( $test, new NotUnary(new NullTest($left, 'null', new Node(), $left->getTemplateLine()), $left->getTemplateLine()), $left->getTemplateLine() ); } parent::__construct($test, $left, $right, $lineno); } public function compile(Compiler $compiler) { /* * This optimizes only one case. PHP 7 also supports more complex expressions * that can return null. So, for instance, if log is defined, log("foo") ?? "..." works, * but log($a["foo"]) ?? "..." does not if $a["foo"] is not defined. More advanced * cases might be implemented as an optimizer node visitor, but has not been done * as benefits are probably not worth the added complexity. */ if ($this->getNode('expr2') instanceof NameExpression) { $this->getNode('expr2')->setAttribute('always_defined', true); $compiler ->raw('((') ->subcompile($this->getNode('expr2')) ->raw(') ?? (') ->subcompile($this->getNode('expr3')) ->raw('))') ; } else { parent::compile($compiler); } } } class_alias('Twig\Node\Expression\NullCoalesceExpression', 'Twig_Node_Expression_NullCoalesce'); php-twig-2.12.5/src/Node/Expression/ParentExpression.php000066400000000000000000000023241362457344700232150ustar00rootroot00000000000000 */ class ParentExpression extends AbstractExpression { public function __construct(string $name, int $lineno, string $tag = null) { parent::__construct([], ['output' => false, 'name' => $name], $lineno, $tag); } public function compile(Compiler $compiler) { if ($this->getAttribute('output')) { $compiler ->addDebugInfo($this) ->write('$this->displayParentBlock(') ->string($this->getAttribute('name')) ->raw(", \$context, \$blocks);\n") ; } else { $compiler ->raw('$this->renderParentBlock(') ->string($this->getAttribute('name')) ->raw(', $context, $blocks)') ; } } } class_alias('Twig\Node\Expression\ParentExpression', 'Twig_Node_Expression_Parent'); php-twig-2.12.5/src/Node/Expression/TempNameExpression.php000066400000000000000000000013141362457344700234700ustar00rootroot00000000000000 $name], $lineno); } public function compile(Compiler $compiler) { $compiler ->raw('$_') ->raw($this->getAttribute('name')) ->raw('_') ; } } class_alias('Twig\Node\Expression\TempNameExpression', 'Twig_Node_Expression_TempName'); php-twig-2.12.5/src/Node/Expression/Test/000077500000000000000000000000001362457344700201115ustar00rootroot00000000000000php-twig-2.12.5/src/Node/Expression/Test/ConstantTest.php000066400000000000000000000023631362457344700232570ustar00rootroot00000000000000 */ class ConstantTest extends TestExpression { public function compile(Compiler $compiler) { $compiler ->raw('(') ->subcompile($this->getNode('node')) ->raw(' === constant(') ; if ($this->getNode('arguments')->hasNode(1)) { $compiler ->raw('get_class(') ->subcompile($this->getNode('arguments')->getNode(1)) ->raw(')."::".') ; } $compiler ->subcompile($this->getNode('arguments')->getNode(0)) ->raw('))') ; } } class_alias('Twig\Node\Expression\Test\ConstantTest', 'Twig_Node_Expression_Test_Constant'); php-twig-2.12.5/src/Node/Expression/Test/DefinedTest.php000066400000000000000000000051341362457344700230230ustar00rootroot00000000000000 */ class DefinedTest extends TestExpression { public function __construct(Node $node, string $name, Node $arguments = null, int $lineno) { if ($node instanceof NameExpression) { $node->setAttribute('is_defined_test', true); } elseif ($node instanceof GetAttrExpression) { $node->setAttribute('is_defined_test', true); $this->changeIgnoreStrictCheck($node); } elseif ($node instanceof BlockReferenceExpression) { $node->setAttribute('is_defined_test', true); } elseif ($node instanceof FunctionExpression && 'constant' === $node->getAttribute('name')) { $node->setAttribute('is_defined_test', true); } elseif ($node instanceof ConstantExpression || $node instanceof ArrayExpression) { $node = new ConstantExpression(true, $node->getTemplateLine()); } elseif ($node instanceof MethodCallExpression) { $node->setAttribute('is_defined_test', true); } else { throw new SyntaxError('The "defined" test only works with simple variables.', $lineno); } parent::__construct($node, $name, $arguments, $lineno); } private function changeIgnoreStrictCheck(GetAttrExpression $node) { $node->setAttribute('optimizable', false); $node->setAttribute('ignore_strict_check', true); if ($node->getNode('node') instanceof GetAttrExpression) { $this->changeIgnoreStrictCheck($node->getNode('node')); } } public function compile(Compiler $compiler) { $compiler->subcompile($this->getNode('node')); } } class_alias('Twig\Node\Expression\Test\DefinedTest', 'Twig_Node_Expression_Test_Defined'); php-twig-2.12.5/src/Node/Expression/Test/DivisiblebyTest.php000066400000000000000000000015651362457344700237360ustar00rootroot00000000000000 */ class DivisiblebyTest extends TestExpression { public function compile(Compiler $compiler) { $compiler ->raw('(0 == ') ->subcompile($this->getNode('node')) ->raw(' % ') ->subcompile($this->getNode('arguments')->getNode(0)) ->raw(')') ; } } class_alias('Twig\Node\Expression\Test\DivisiblebyTest', 'Twig_Node_Expression_Test_Divisibleby'); php-twig-2.12.5/src/Node/Expression/Test/EvenTest.php000066400000000000000000000013671362457344700223660ustar00rootroot00000000000000 */ class EvenTest extends TestExpression { public function compile(Compiler $compiler) { $compiler ->raw('(') ->subcompile($this->getNode('node')) ->raw(' % 2 == 0') ->raw(')') ; } } class_alias('Twig\Node\Expression\Test\EvenTest', 'Twig_Node_Expression_Test_Even'); php-twig-2.12.5/src/Node/Expression/Test/NullTest.php000066400000000000000000000013451362457344700223770ustar00rootroot00000000000000 */ class NullTest extends TestExpression { public function compile(Compiler $compiler) { $compiler ->raw('(null === ') ->subcompile($this->getNode('node')) ->raw(')') ; } } class_alias('Twig\Node\Expression\Test\NullTest', 'Twig_Node_Expression_Test_Null'); php-twig-2.12.5/src/Node/Expression/Test/OddTest.php000066400000000000000000000013621362457344700221720ustar00rootroot00000000000000 */ class OddTest extends TestExpression { public function compile(Compiler $compiler) { $compiler ->raw('(') ->subcompile($this->getNode('node')) ->raw(' % 2 == 1') ->raw(')') ; } } class_alias('Twig\Node\Expression\Test\OddTest', 'Twig_Node_Expression_Test_Odd'); php-twig-2.12.5/src/Node/Expression/Test/SameasTest.php000066400000000000000000000015041362457344700226730ustar00rootroot00000000000000 */ class SameasTest extends TestExpression { public function compile(Compiler $compiler) { $compiler ->raw('(') ->subcompile($this->getNode('node')) ->raw(' === ') ->subcompile($this->getNode('arguments')->getNode(0)) ->raw(')') ; } } class_alias('Twig\Node\Expression\Test\SameasTest', 'Twig_Node_Expression_Test_Sameas'); php-twig-2.12.5/src/Node/Expression/TestExpression.php000066400000000000000000000022571362457344700227100ustar00rootroot00000000000000 $node]; if (null !== $arguments) { $nodes['arguments'] = $arguments; } parent::__construct($nodes, ['name' => $name], $lineno); } public function compile(Compiler $compiler) { $name = $this->getAttribute('name'); $test = $compiler->getEnvironment()->getTest($name); $this->setAttribute('name', $name); $this->setAttribute('type', 'test'); $this->setAttribute('arguments', $test->getArguments()); $this->setAttribute('callable', $test->getCallable()); $this->setAttribute('is_variadic', $test->isVariadic()); $this->compileCallable($compiler); } } class_alias('Twig\Node\Expression\TestExpression', 'Twig_Node_Expression_Test'); php-twig-2.12.5/src/Node/Expression/Unary/000077500000000000000000000000001362457344700202705ustar00rootroot00000000000000php-twig-2.12.5/src/Node/Expression/Unary/AbstractUnary.php000066400000000000000000000015431362457344700235660ustar00rootroot00000000000000 $node], [], $lineno); } public function compile(Compiler $compiler) { $compiler->raw(' '); $this->operator($compiler); $compiler->subcompile($this->getNode('node')); } abstract public function operator(Compiler $compiler); } class_alias('Twig\Node\Expression\Unary\AbstractUnary', 'Twig_Node_Expression_Unary'); php-twig-2.12.5/src/Node/Expression/Unary/NegUnary.php000066400000000000000000000007651362457344700225410ustar00rootroot00000000000000raw('-'); } } class_alias('Twig\Node\Expression\Unary\NegUnary', 'Twig_Node_Expression_Unary_Neg'); php-twig-2.12.5/src/Node/Expression/Unary/NotUnary.php000066400000000000000000000007651362457344700225700ustar00rootroot00000000000000raw('!'); } } class_alias('Twig\Node\Expression\Unary\NotUnary', 'Twig_Node_Expression_Unary_Not'); php-twig-2.12.5/src/Node/Expression/Unary/PosUnary.php000066400000000000000000000007651362457344700225710ustar00rootroot00000000000000raw('+'); } } class_alias('Twig\Node\Expression\Unary\PosUnary', 'Twig_Node_Expression_Unary_Pos'); php-twig-2.12.5/src/Node/Expression/VariadicExpression.php000066400000000000000000000006641362457344700235130ustar00rootroot00000000000000raw('...'); parent::compile($compiler); } } php-twig-2.12.5/src/Node/FlushNode.php000066400000000000000000000012741362457344700174370ustar00rootroot00000000000000 */ class FlushNode extends Node { public function __construct(int $lineno, string $tag) { parent::__construct([], [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write("flush();\n") ; } } class_alias('Twig\Node\FlushNode', 'Twig_Node_Flush'); php-twig-2.12.5/src/Node/ForLoopNode.php000066400000000000000000000030741362457344700177360ustar00rootroot00000000000000 */ class ForLoopNode extends Node { public function __construct(int $lineno, string $tag = null) { parent::__construct([], ['with_loop' => false, 'ifexpr' => false, 'else' => false], $lineno, $tag); } public function compile(Compiler $compiler) { if ($this->getAttribute('else')) { $compiler->write("\$context['_iterated'] = true;\n"); } if ($this->getAttribute('with_loop')) { $compiler ->write("++\$context['loop']['index0'];\n") ->write("++\$context['loop']['index'];\n") ->write("\$context['loop']['first'] = false;\n") ; if (!$this->getAttribute('ifexpr')) { $compiler ->write("if (isset(\$context['loop']['length'])) {\n") ->indent() ->write("--\$context['loop']['revindex0'];\n") ->write("--\$context['loop']['revindex'];\n") ->write("\$context['loop']['last'] = 0 === \$context['loop']['revindex0'];\n") ->outdent() ->write("}\n") ; } } } } class_alias('Twig\Node\ForLoopNode', 'Twig_Node_ForLoop'); php-twig-2.12.5/src/Node/ForNode.php000066400000000000000000000103401362457344700170760ustar00rootroot00000000000000 */ class ForNode extends Node { private $loop; public function __construct(AssignNameExpression $keyTarget, AssignNameExpression $valueTarget, AbstractExpression $seq, AbstractExpression $ifexpr = null, Node $body, Node $else = null, int $lineno, string $tag = null) { $body = new Node([$body, $this->loop = new ForLoopNode($lineno, $tag)]); if (null !== $ifexpr) { $body = new IfNode(new Node([$ifexpr, $body]), null, $lineno, $tag); } $nodes = ['key_target' => $keyTarget, 'value_target' => $valueTarget, 'seq' => $seq, 'body' => $body]; if (null !== $else) { $nodes['else'] = $else; } parent::__construct($nodes, ['with_loop' => true, 'ifexpr' => null !== $ifexpr], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write("\$context['_parent'] = \$context;\n") ->write("\$context['_seq'] = twig_ensure_traversable(") ->subcompile($this->getNode('seq')) ->raw(");\n") ; if ($this->hasNode('else')) { $compiler->write("\$context['_iterated'] = false;\n"); } if ($this->getAttribute('with_loop')) { $compiler ->write("\$context['loop'] = [\n") ->write(" 'parent' => \$context['_parent'],\n") ->write(" 'index0' => 0,\n") ->write(" 'index' => 1,\n") ->write(" 'first' => true,\n") ->write("];\n") ; if (!$this->getAttribute('ifexpr')) { $compiler ->write("if (is_array(\$context['_seq']) || (is_object(\$context['_seq']) && \$context['_seq'] instanceof \Countable)) {\n") ->indent() ->write("\$length = count(\$context['_seq']);\n") ->write("\$context['loop']['revindex0'] = \$length - 1;\n") ->write("\$context['loop']['revindex'] = \$length;\n") ->write("\$context['loop']['length'] = \$length;\n") ->write("\$context['loop']['last'] = 1 === \$length;\n") ->outdent() ->write("}\n") ; } } $this->loop->setAttribute('else', $this->hasNode('else')); $this->loop->setAttribute('with_loop', $this->getAttribute('with_loop')); $this->loop->setAttribute('ifexpr', $this->getAttribute('ifexpr')); $compiler ->write("foreach (\$context['_seq'] as ") ->subcompile($this->getNode('key_target')) ->raw(' => ') ->subcompile($this->getNode('value_target')) ->raw(") {\n") ->indent() ->subcompile($this->getNode('body')) ->outdent() ->write("}\n") ; if ($this->hasNode('else')) { $compiler ->write("if (!\$context['_iterated']) {\n") ->indent() ->subcompile($this->getNode('else')) ->outdent() ->write("}\n") ; } $compiler->write("\$_parent = \$context['_parent'];\n"); // remove some "private" loop variables (needed for nested loops) $compiler->write('unset($context[\'_seq\'], $context[\'_iterated\'], $context[\''.$this->getNode('key_target')->getAttribute('name').'\'], $context[\''.$this->getNode('value_target')->getAttribute('name').'\'], $context[\'_parent\'], $context[\'loop\']);'."\n"); // keep the values set in the inner context for variables defined in the outer context $compiler->write("\$context = array_intersect_key(\$context, \$_parent) + \$_parent;\n"); } } class_alias('Twig\Node\ForNode', 'Twig_Node_For'); php-twig-2.12.5/src/Node/IfNode.php000066400000000000000000000032501362457344700167100ustar00rootroot00000000000000 */ class IfNode extends Node { public function __construct(Node $tests, Node $else = null, int $lineno, string $tag = null) { $nodes = ['tests' => $tests]; if (null !== $else) { $nodes['else'] = $else; } parent::__construct($nodes, [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); for ($i = 0, $count = \count($this->getNode('tests')); $i < $count; $i += 2) { if ($i > 0) { $compiler ->outdent() ->write('} elseif (') ; } else { $compiler ->write('if (') ; } $compiler ->subcompile($this->getNode('tests')->getNode($i)) ->raw(") {\n") ->indent() ->subcompile($this->getNode('tests')->getNode($i + 1)) ; } if ($this->hasNode('else')) { $compiler ->outdent() ->write("} else {\n") ->indent() ->subcompile($this->getNode('else')) ; } $compiler ->outdent() ->write("}\n"); } } class_alias('Twig\Node\IfNode', 'Twig_Node_If'); php-twig-2.12.5/src/Node/ImportNode.php000066400000000000000000000033701362457344700176270ustar00rootroot00000000000000 */ class ImportNode extends Node { public function __construct(AbstractExpression $expr, AbstractExpression $var, int $lineno, string $tag = null, bool $global = true) { parent::__construct(['expr' => $expr, 'var' => $var], ['global' => $global], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('$macros[') ->repr($this->getNode('var')->getAttribute('name')) ->raw('] = ') ; if ($this->getAttribute('global')) { $compiler ->raw('$this->macros[') ->repr($this->getNode('var')->getAttribute('name')) ->raw('] = ') ; } if ($this->getNode('expr') instanceof NameExpression && '_self' === $this->getNode('expr')->getAttribute('name')) { $compiler->raw('$this'); } else { $compiler ->raw('$this->loadTemplate(') ->subcompile($this->getNode('expr')) ->raw(', ') ->repr($this->getTemplateName()) ->raw(', ') ->repr($this->getTemplateLine()) ->raw(')->unwrap()') ; } $compiler->raw(";\n"); } } class_alias('Twig\Node\ImportNode', 'Twig_Node_Import'); php-twig-2.12.5/src/Node/IncludeNode.php000066400000000000000000000062211362457344700177360ustar00rootroot00000000000000 */ class IncludeNode extends Node implements NodeOutputInterface { public function __construct(AbstractExpression $expr, AbstractExpression $variables = null, bool $only = false, bool $ignoreMissing = false, int $lineno, string $tag = null) { $nodes = ['expr' => $expr]; if (null !== $variables) { $nodes['variables'] = $variables; } parent::__construct($nodes, ['only' => (bool) $only, 'ignore_missing' => (bool) $ignoreMissing], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); if ($this->getAttribute('ignore_missing')) { $template = $compiler->getVarName(); $compiler ->write(sprintf("$%s = null;\n", $template)) ->write("try {\n") ->indent() ->write(sprintf('$%s = ', $template)) ; $this->addGetTemplate($compiler); $compiler ->raw(";\n") ->outdent() ->write("} catch (LoaderError \$e) {\n") ->indent() ->write("// ignore missing template\n") ->outdent() ->write("}\n") ->write(sprintf("if ($%s) {\n", $template)) ->indent() ->write(sprintf('$%s->display(', $template)) ; $this->addTemplateArguments($compiler); $compiler ->raw(");\n") ->outdent() ->write("}\n") ; } else { $this->addGetTemplate($compiler); $compiler->raw('->display('); $this->addTemplateArguments($compiler); $compiler->raw(");\n"); } } protected function addGetTemplate(Compiler $compiler) { $compiler ->write('$this->loadTemplate(') ->subcompile($this->getNode('expr')) ->raw(', ') ->repr($this->getTemplateName()) ->raw(', ') ->repr($this->getTemplateLine()) ->raw(')') ; } protected function addTemplateArguments(Compiler $compiler) { if (!$this->hasNode('variables')) { $compiler->raw(false === $this->getAttribute('only') ? '$context' : '[]'); } elseif (false === $this->getAttribute('only')) { $compiler ->raw('twig_array_merge($context, ') ->subcompile($this->getNode('variables')) ->raw(')') ; } else { $compiler->raw('twig_to_array('); $compiler->subcompile($this->getNode('variables')); $compiler->raw(')'); } } } class_alias('Twig\Node\IncludeNode', 'Twig_Node_Include'); php-twig-2.12.5/src/Node/MacroNode.php000066400000000000000000000063231362457344700174170ustar00rootroot00000000000000 */ class MacroNode extends Node { const VARARGS_NAME = 'varargs'; public function __construct(string $name, Node $body, Node $arguments, int $lineno, string $tag = null) { foreach ($arguments as $argumentName => $argument) { if (self::VARARGS_NAME === $argumentName) { throw new SyntaxError(sprintf('The argument "%s" in macro "%s" cannot be defined because the variable "%s" is reserved for arbitrary arguments.', self::VARARGS_NAME, $name, self::VARARGS_NAME), $argument->getTemplateLine(), $argument->getSourceContext()); } } parent::__construct(['body' => $body, 'arguments' => $arguments], ['name' => $name], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write(sprintf('public function 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() ->write("\$macros = \$this->macros;\n") ->write("\$context = \$this->env->mergeGlobals([\n") ->indent() ; foreach ($this->getNode('arguments') as $name => $default) { $compiler ->write('') ->string($name) ->raw(' => $__'.$name.'__') ->raw(",\n") ; } $compiler ->write('') ->string(self::VARARGS_NAME) ->raw(' => ') ; $compiler ->raw("\$__varargs__,\n") ->outdent() ->write("]);\n\n") ->write("\$blocks = [];\n\n") ; if ($compiler->getEnvironment()->isDebug()) { $compiler->write("ob_start();\n"); } else { $compiler->write("ob_start(function () { return ''; });\n"); } $compiler ->write("try {\n") ->indent() ->subcompile($this->getNode('body')) ->raw("\n") ->write("return ('' === \$tmp = ob_get_contents()) ? '' : new 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\MacroNode', 'Twig_Node_Macro'); php-twig-2.12.5/src/Node/ModuleNode.php000066400000000000000000000354531362457344700176110ustar00rootroot00000000000000 * * @final since Twig 2.4.0 */ class ModuleNode extends Node { public function __construct(Node $body, AbstractExpression $parent = null, Node $blocks, Node $macros, Node $traits, $embeddedTemplates, Source $source) { if (__CLASS__ !== \get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since Twig 2.4.0 and the class will be final in 3.0.', E_USER_DEPRECATED); } $nodes = [ 'body' => $body, 'blocks' => $blocks, 'macros' => $macros, 'traits' => $traits, 'display_start' => new Node(), 'display_end' => new Node(), 'constructor_start' => new Node(), 'constructor_end' => new Node(), 'class_end' => new Node(), ]; if (null !== $parent) { $nodes['parent'] = $parent; } // embedded templates are set as attributes so that they are only visited once by the visitors parent::__construct($nodes, [ 'index' => null, 'embedded_templates' => $embeddedTemplates, ], 1); // populate the template name of all node children $this->setSourceContext($source); } public function setIndex($index) { $this->setAttribute('index', $index); } public function compile(Compiler $compiler) { $this->compileTemplate($compiler); foreach ($this->getAttribute('embedded_templates') as $template) { $compiler->subcompile($template); } } protected function compileTemplate(Compiler $compiler) { if (!$this->getAttribute('index')) { $compiler->write('compileClassHeader($compiler); $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(Compiler $compiler) { if (!$this->hasNode('parent')) { return; } $parent = $this->getNode('parent'); $compiler ->write("protected function doGetParent(array \$context)\n", "{\n") ->indent() ->addDebugInfo($parent) ->write('return ') ; if ($parent instanceof ConstantExpression) { $compiler->subcompile($parent); } else { $compiler ->raw('$this->loadTemplate(') ->subcompile($parent) ->raw(', ') ->repr($this->getSourceContext()->getName()) ->raw(', ') ->repr($parent->getTemplateLine()) ->raw(')') ; } $compiler ->raw(";\n") ->outdent() ->write("}\n\n") ; } protected function compileClassHeader(Compiler $compiler) { $compiler ->write("\n\n") ; if (!$this->getAttribute('index')) { $compiler ->write("use Twig\Environment;\n") ->write("use Twig\Error\LoaderError;\n") ->write("use Twig\Error\RuntimeError;\n") ->write("use Twig\Extension\SandboxExtension;\n") ->write("use Twig\Markup;\n") ->write("use Twig\Sandbox\SecurityError;\n") ->write("use Twig\Sandbox\SecurityNotAllowedTagError;\n") ->write("use Twig\Sandbox\SecurityNotAllowedFilterError;\n") ->write("use Twig\Sandbox\SecurityNotAllowedFunctionError;\n") ->write("use Twig\Source;\n") ->write("use Twig\Template;\n\n") ; } $compiler // if the template name contains */, add a blank to avoid a PHP parse error ->write('/* '.str_replace('*/', '* /', $this->getSourceContext()->getName())." */\n") ->write('class '.$compiler->getEnvironment()->getTemplateClass($this->getSourceContext()->getName(), $this->getAttribute('index'))) ->raw(sprintf(" extends %s\n", $compiler->getEnvironment()->getBaseTemplateClass(false))) ->write("{\n") ->indent() ->write("private \$source;\n") ->write("private \$macros = [];\n\n") ; } protected function compileConstructor(Compiler $compiler) { $compiler ->write("public function __construct(Environment \$env)\n", "{\n") ->indent() ->subcompile($this->getNode('constructor_start')) ->write("parent::__construct(\$env);\n\n") ->write("\$this->source = \$this->getSourceContext();\n\n") ; // parent if (!$this->hasNode('parent')) { $compiler->write("\$this->parent = false;\n\n"); } $countTraits = \count($this->getNode('traits')); if ($countTraits) { // traits foreach ($this->getNode('traits') as $i => $trait) { $node = $trait->getNode('template'); $compiler ->addDebugInfo($node) ->write(sprintf('$_trait_%s = $this->loadTemplate(', $i)) ->subcompile($node) ->raw(', ') ->repr($node->getTemplateName()) ->raw(', ') ->repr($node->getTemplateLine()) ->raw(");\n") ->write(sprintf("if (!\$_trait_%s->isTraitable()) {\n", $i)) ->indent() ->write("throw new RuntimeError('Template \"'.") ->subcompile($trait->getNode('template')) ->raw(".'\" cannot be used as a trait.', ") ->repr($node->getTemplateLine()) ->raw(", \$this->source);\n") ->outdent() ->write("}\n") ->write(sprintf("\$_trait_%s_blocks = \$_trait_%s->getBlocks();\n\n", $i, $i)) ; foreach ($trait->getNode('targets') as $key => $value) { $compiler ->write(sprintf('if (!isset($_trait_%s_blocks[', $i)) ->string($key) ->raw("])) {\n") ->indent() ->write("throw new RuntimeError('Block ") ->string($key) ->raw(' is not defined in trait ') ->subcompile($trait->getNode('template')) ->raw(".', ") ->repr($node->getTemplateLine()) ->raw(", \$this->source);\n") ->outdent() ->write("}\n\n") ->write(sprintf('$_trait_%s_blocks[', $i)) ->subcompile($value) ->raw(sprintf('] = $_trait_%s_blocks[', $i)) ->string($key) ->raw(sprintf(']; unset($_trait_%s_blocks[', $i)) ->string($key) ->raw("]);\n\n") ; } } if ($countTraits > 1) { $compiler ->write("\$this->traits = array_merge(\n") ->indent() ; for ($i = 0; $i < $countTraits; ++$i) { $compiler ->write(sprintf('$_trait_%s_blocks'.($i == $countTraits - 1 ? '' : ',')."\n", $i)) ; } $compiler ->outdent() ->write(");\n\n") ; } else { $compiler ->write("\$this->traits = \$_trait_0_blocks;\n\n") ; } $compiler ->write("\$this->blocks = array_merge(\n") ->indent() ->write("\$this->traits,\n") ->write("[\n") ; } else { $compiler ->write("\$this->blocks = [\n") ; } // blocks $compiler ->indent() ; foreach ($this->getNode('blocks') as $name => $node) { $compiler ->write(sprintf("'%s' => [\$this, 'block_%s'],\n", $name, $name)) ; } if ($countTraits) { $compiler ->outdent() ->write("]\n") ->outdent() ->write(");\n") ; } else { $compiler ->outdent() ->write("];\n") ; } $compiler ->subcompile($this->getNode('constructor_end')) ->outdent() ->write("}\n\n") ; } protected function compileDisplay(Compiler $compiler) { $compiler ->write("protected function doDisplay(array \$context, array \$blocks = [])\n", "{\n") ->indent() ->write("\$macros = \$this->macros;\n") ->subcompile($this->getNode('display_start')) ->subcompile($this->getNode('body')) ; if ($this->hasNode('parent')) { $parent = $this->getNode('parent'); $compiler->addDebugInfo($parent); if ($parent instanceof ConstantExpression) { $compiler ->write('$this->parent = $this->loadTemplate(') ->subcompile($parent) ->raw(', ') ->repr($this->getSourceContext()->getName()) ->raw(', ') ->repr($parent->getTemplateLine()) ->raw(");\n") ; $compiler->write('$this->parent'); } else { $compiler->write('$this->getParent($context)'); } $compiler->raw("->display(\$context, array_merge(\$this->blocks, \$blocks));\n"); } $compiler ->subcompile($this->getNode('display_end')) ->outdent() ->write("}\n\n") ; } protected function compileClassFooter(Compiler $compiler) { $compiler ->subcompile($this->getNode('class_end')) ->outdent() ->write("}\n") ; } protected function compileMacros(Compiler $compiler) { $compiler->subcompile($this->getNode('macros')); } protected function compileGetTemplateName(Compiler $compiler) { $compiler ->write("public function getTemplateName()\n", "{\n") ->indent() ->write('return ') ->repr($this->getSourceContext()->getName()) ->raw(";\n") ->outdent() ->write("}\n\n") ; } protected function compileIsTraitable(Compiler $compiler) { // A template can be used as a trait if: // * it has no parent // * it has no macros // * it has no body // // Put another way, a template can be used as a trait if it // only contains blocks and use statements. $traitable = !$this->hasNode('parent') && 0 === \count($this->getNode('macros')); if ($traitable) { if ($this->getNode('body') instanceof BodyNode) { $nodes = $this->getNode('body')->getNode(0); } else { $nodes = $this->getNode('body'); } if (!\count($nodes)) { $nodes = new Node([$nodes]); } foreach ($nodes as $node) { if (!\count($node)) { continue; } if ($node instanceof TextNode && ctype_space($node->getAttribute('data'))) { continue; } if ($node instanceof BlockReferenceNode) { continue; } $traitable = false; break; } } if ($traitable) { return; } $compiler ->write("public function isTraitable()\n", "{\n") ->indent() ->write(sprintf("return %s;\n", $traitable ? 'true' : 'false')) ->outdent() ->write("}\n\n") ; } protected function compileDebugInfo(Compiler $compiler) { $compiler ->write("public function getDebugInfo()\n", "{\n") ->indent() ->write(sprintf("return %s;\n", str_replace("\n", '', var_export(array_reverse($compiler->getDebugInfo(), true), true)))) ->outdent() ->write("}\n\n") ; } protected function compileGetSourceContext(Compiler $compiler) { $compiler ->write("public function getSourceContext()\n", "{\n") ->indent() ->write('return new Source(') ->string($compiler->getEnvironment()->isDebug() ? $this->getSourceContext()->getCode() : '') ->raw(', ') ->string($this->getSourceContext()->getName()) ->raw(', ') ->string($this->getSourceContext()->getPath()) ->raw(");\n") ->outdent() ->write("}\n") ; } protected function compileLoadTemplate(Compiler $compiler, $node, $var) { if ($node instanceof ConstantExpression) { $compiler ->write(sprintf('%s = $this->loadTemplate(', $var)) ->subcompile($node) ->raw(', ') ->repr($node->getTemplateName()) ->raw(', ') ->repr($node->getTemplateLine()) ->raw(");\n") ; } else { throw new \LogicException('Trait templates can only be constant nodes.'); } } } class_alias('Twig\Node\ModuleNode', 'Twig_Node_Module'); php-twig-2.12.5/src/Node/Node.php000066400000000000000000000124741362457344700164410ustar00rootroot00000000000000 */ class Node implements \Countable, \IteratorAggregate { protected $nodes; protected $attributes; protected $lineno; protected $tag; private $name; private $sourceContext; /** * @param array $nodes An array of named nodes * @param array $attributes An array of attributes (should not be nodes) * @param int $lineno The line number * @param string $tag The tag name associated with the Node */ public function __construct(array $nodes = [], array $attributes = [], int $lineno = 0, string $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\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 = []; foreach ($this->attributes as $name => $value) { $attributes[] = sprintf('%s: %s', $name, str_replace("\n", '', var_export($value, true))); } $repr = [\get_class($this).'('.implode(', ', $attributes)]; if (\count($this->nodes)) { foreach ($this->nodes as $name => $node) { $len = \strlen($name) + 4; $noderepr = []; foreach (explode("\n", (string) $node) as $line) { $noderepr[] = str_repeat(' ', $len).$line; } $repr[] = sprintf(' %s: %s', $name, ltrim(implode("\n", $noderepr))); } $repr[] = ')'; } else { $repr[0] .= ')'; } return implode("\n", $repr); } public function compile(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 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); } /** * @deprecated since 2.8 (to be removed in 3.0) */ public function setTemplateName($name/*, $triggerDeprecation = true */) { $triggerDeprecation = 2 > \func_num_args() || \func_get_arg(1); if ($triggerDeprecation) { @trigger_error('The '.__METHOD__.' method is deprecated since version 2.8 and will be removed in 3.0. Use setSourceContext() instead.', E_USER_DEPRECATED); } $this->name = $name; foreach ($this->nodes as $node) { $node->setTemplateName($name, $triggerDeprecation); } } public function getTemplateName() { return $this->sourceContext ? $this->sourceContext->getName() : null; } public function setSourceContext(Source $source) { $this->sourceContext = $source; foreach ($this->nodes as $node) { $node->setSourceContext($source); } $this->setTemplateName($source->getName(), false); } public function getSourceContext() { return $this->sourceContext; } } class_alias('Twig\Node\Node', 'Twig_Node'); // Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. class_exists('Twig\Compiler'); php-twig-2.12.5/src/Node/NodeCaptureInterface.php000066400000000000000000000007151362457344700216010ustar00rootroot00000000000000 */ interface NodeCaptureInterface { } class_alias('Twig\Node\NodeCaptureInterface', 'Twig_NodeCaptureInterface'); php-twig-2.12.5/src/Node/NodeOutputInterface.php000066400000000000000000000006661362457344700215030ustar00rootroot00000000000000 */ interface NodeOutputInterface { } class_alias('Twig\Node\NodeOutputInterface', 'Twig_NodeOutputInterface'); php-twig-2.12.5/src/Node/PrintNode.php000066400000000000000000000016501362457344700174500ustar00rootroot00000000000000 */ class PrintNode extends Node implements NodeOutputInterface { public function __construct(AbstractExpression $expr, int $lineno, string $tag = null) { parent::__construct(['expr' => $expr], [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('echo ') ->subcompile($this->getNode('expr')) ->raw(";\n") ; } } class_alias('Twig\Node\PrintNode', 'Twig_Node_Print'); php-twig-2.12.5/src/Node/SandboxNode.php000066400000000000000000000022111362457344700177440ustar00rootroot00000000000000 */ class SandboxNode extends Node { public function __construct(Node $body, int $lineno, string $tag = null) { parent::__construct(['body' => $body], [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write("if (!\$alreadySandboxed = \$this->sandbox->isSandboxed()) {\n") ->indent() ->write("\$this->sandbox->enableSandbox();\n") ->outdent() ->write("}\n") ->subcompile($this->getNode('body')) ->write("if (!\$alreadySandboxed) {\n") ->indent() ->write("\$this->sandbox->disableSandbox();\n") ->outdent() ->write("}\n") ; } } class_alias('Twig\Node\SandboxNode', 'Twig_Node_Sandbox'); php-twig-2.12.5/src/Node/SandboxedPrintNode.php000066400000000000000000000027201362457344700212770ustar00rootroot00000000000000 */ class SandboxedPrintNode extends PrintNode { public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('echo ') ; $expr = $this->getNode('expr'); if ($expr instanceof ConstantExpression) { $compiler ->subcompile($expr) ->raw(";\n") ; } else { $compiler ->write('$this->extensions[SandboxExtension::class]->ensureToStringAllowed(') ->subcompile($expr) ->raw(', ') ->repr($expr->getTemplateLine()) ->raw(", \$this->source);\n") ; } } } class_alias('Twig\Node\SandboxedPrintNode', 'Twig_Node_SandboxedPrint'); php-twig-2.12.5/src/Node/SetNode.php000066400000000000000000000065311362457344700171120ustar00rootroot00000000000000 */ class SetNode extends Node implements NodeCaptureInterface { public function __construct(bool $capture, Node $names, Node $values, int $lineno, string $tag = null) { parent::__construct(['names' => $names, 'values' => $values], ['capture' => $capture, 'safe' => false], $lineno, $tag); /* * Optimizes the node when capture is used for a large block of text. * * {% set foo %}foo{% endset %} is compiled to $context['foo'] = new Twig\Markup("foo"); */ if ($this->getAttribute('capture')) { $this->setAttribute('safe', true); $values = $this->getNode('values'); if ($values instanceof TextNode) { $this->setNode('values', new ConstantExpression($values->getAttribute('data'), $values->getTemplateLine())); $this->setAttribute('capture', false); } } } public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); if (\count($this->getNode('names')) > 1) { $compiler->write('list('); foreach ($this->getNode('names') as $idx => $node) { if ($idx) { $compiler->raw(', '); } $compiler->subcompile($node); } $compiler->raw(')'); } else { if ($this->getAttribute('capture')) { if ($compiler->getEnvironment()->isDebug()) { $compiler->write("ob_start();\n"); } else { $compiler->write("ob_start(function () { return ''; });\n"); } $compiler ->subcompile($this->getNode('values')) ; } $compiler->subcompile($this->getNode('names'), false); if ($this->getAttribute('capture')) { $compiler->raw(" = ('' === \$tmp = ob_get_clean()) ? '' : new Markup(\$tmp, \$this->env->getCharset())"); } } if (!$this->getAttribute('capture')) { $compiler->raw(' = '); if (\count($this->getNode('names')) > 1) { $compiler->write('['); foreach ($this->getNode('values') as $idx => $value) { if ($idx) { $compiler->raw(', '); } $compiler->subcompile($value); } $compiler->raw(']'); } else { if ($this->getAttribute('safe')) { $compiler ->raw("('' === \$tmp = ") ->subcompile($this->getNode('values')) ->raw(") ? '' : new Markup(\$tmp, \$this->env->getCharset())") ; } else { $compiler->subcompile($this->getNode('values')); } } } $compiler->raw(";\n"); } } class_alias('Twig\Node\SetNode', 'Twig_Node_Set'); php-twig-2.12.5/src/Node/SpacelessNode.php000066400000000000000000000022751362457344700203020ustar00rootroot00000000000000 */ class SpacelessNode extends Node implements NodeOutputInterface { public function __construct(Node $body, int $lineno, string $tag = 'spaceless') { parent::__construct(['body' => $body], [], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ; if ($compiler->getEnvironment()->isDebug()) { $compiler->write("ob_start();\n"); } else { $compiler->write("ob_start(function () { return ''; });\n"); } $compiler ->subcompile($this->getNode('body')) ->write("echo trim(preg_replace('/>\s+<', ob_get_clean()));\n") ; } } class_alias('Twig\Node\SpacelessNode', 'Twig_Node_Spaceless'); php-twig-2.12.5/src/Node/TextNode.php000066400000000000000000000014751362457344700173050ustar00rootroot00000000000000 */ class TextNode extends Node implements NodeOutputInterface { public function __construct(string $data, int $lineno) { parent::__construct([], ['data' => $data], $lineno); } public function compile(Compiler $compiler) { $compiler ->addDebugInfo($this) ->write('echo ') ->string($this->getAttribute('data')) ->raw(";\n") ; } } class_alias('Twig\Node\TextNode', 'Twig_Node_Text'); php-twig-2.12.5/src/Node/WithNode.php000066400000000000000000000042521362457344700172700ustar00rootroot00000000000000 */ class WithNode extends Node { public function __construct(Node $body, Node $variables = null, bool $only = false, int $lineno, string $tag = null) { $nodes = ['body' => $body]; if (null !== $variables) { $nodes['variables'] = $variables; } parent::__construct($nodes, ['only' => $only], $lineno, $tag); } public function compile(Compiler $compiler) { $compiler->addDebugInfo($this); if ($this->hasNode('variables')) { $node = $this->getNode('variables'); $varsName = $compiler->getVarName(); $compiler ->write(sprintf('$%s = ', $varsName)) ->subcompile($node) ->raw(";\n") ->write(sprintf("if (!twig_test_iterable(\$%s)) {\n", $varsName)) ->indent() ->write("throw new RuntimeError('Variables passed to the \"with\" tag must be a hash.', ") ->repr($node->getTemplateLine()) ->raw(", \$this->getSourceContext());\n") ->outdent() ->write("}\n") ->write(sprintf("\$%s = twig_to_array(\$%s);\n", $varsName, $varsName)) ; if ($this->getAttribute('only')) { $compiler->write("\$context = ['_parent' => \$context];\n"); } else { $compiler->write("\$context['_parent'] = \$context;\n"); } $compiler->write(sprintf("\$context = \$this->env->mergeGlobals(array_merge(\$context, \$%s));\n", $varsName)); } else { $compiler->write("\$context['_parent'] = \$context;\n"); } $compiler ->subcompile($this->getNode('body')) ->write("\$context = \$context['_parent'];\n") ; } } class_alias('Twig\Node\WithNode', 'Twig_Node_With'); php-twig-2.12.5/src/NodeTraverser.php000066400000000000000000000041721362457344700174460ustar00rootroot00000000000000 */ final class NodeTraverser { private $env; private $visitors = []; /** * @param NodeVisitorInterface[] $visitors */ public function __construct(Environment $env, array $visitors = []) { $this->env = $env; foreach ($visitors as $visitor) { $this->addVisitor($visitor); } } public function addVisitor(NodeVisitorInterface $visitor) { $this->visitors[$visitor->getPriority()][] = $visitor; } /** * Traverses a node and calls the registered visitors. */ public function traverse(Node $node): Node { ksort($this->visitors); foreach ($this->visitors as $visitors) { foreach ($visitors as $visitor) { $node = $this->traverseForVisitor($visitor, $node); } } return $node; } /** * @return Node|null */ private function traverseForVisitor(NodeVisitorInterface $visitor, Node $node) { $node = $visitor->enterNode($node, $this->env); foreach ($node as $k => $n) { if (false !== ($m = $this->traverseForVisitor($visitor, $n)) && null !== $m) { if ($m !== $n) { $node->setNode($k, $m); } } else { if (false === $m) { @trigger_error('Returning "false" to remove a Node from NodeVisitorInterface::leaveNode() is deprecated since Twig version 2.9; return "null" instead.', E_USER_DEPRECATED); } $node->removeNode($k); } } return $visitor->leaveNode($node, $this->env); } } class_alias('Twig\NodeTraverser', 'Twig_NodeTraverser'); php-twig-2.12.5/src/NodeVisitor/000077500000000000000000000000001362457344700164135ustar00rootroot00000000000000php-twig-2.12.5/src/NodeVisitor/AbstractNodeVisitor.php000066400000000000000000000023271362457344700230610ustar00rootroot00000000000000 */ abstract class AbstractNodeVisitor implements NodeVisitorInterface { final public function enterNode(Node $node, Environment $env) { return $this->doEnterNode($node, $env); } final public function leaveNode(Node $node, Environment $env) { return $this->doLeaveNode($node, $env); } /** * Called before child nodes are visited. * * @return Node The modified node */ abstract protected function doEnterNode(Node $node, Environment $env); /** * Called after child nodes are visited. * * @return Node|null The modified node or null if the node must be removed */ abstract protected function doLeaveNode(Node $node, Environment $env); } class_alias('Twig\NodeVisitor\AbstractNodeVisitor', 'Twig_BaseNodeVisitor'); php-twig-2.12.5/src/NodeVisitor/EscaperNodeVisitor.php000066400000000000000000000160311362457344700226750ustar00rootroot00000000000000 */ final class EscaperNodeVisitor extends AbstractNodeVisitor { private $statusStack = []; private $blocks = []; private $safeAnalysis; private $traverser; private $defaultStrategy = false; private $safeVars = []; public function __construct() { $this->safeAnalysis = new SafeAnalysisNodeVisitor(); } protected function doEnterNode(Node $node, Environment $env) { if ($node instanceof ModuleNode) { if ($env->hasExtension(EscaperExtension::class) && $defaultStrategy = $env->getExtension(EscaperExtension::class)->getDefaultStrategy($node->getTemplateName())) { $this->defaultStrategy = $defaultStrategy; } $this->safeVars = []; $this->blocks = []; } elseif ($node instanceof AutoEscapeNode) { $this->statusStack[] = $node->getAttribute('value'); } elseif ($node instanceof BlockNode) { $this->statusStack[] = isset($this->blocks[$node->getAttribute('name')]) ? $this->blocks[$node->getAttribute('name')] : $this->needEscaping($env); } elseif ($node instanceof ImportNode) { $this->safeVars[] = $node->getNode('var')->getAttribute('name'); } return $node; } protected function doLeaveNode(Node $node, Environment $env) { if ($node instanceof ModuleNode) { $this->defaultStrategy = false; $this->safeVars = []; $this->blocks = []; } elseif ($node instanceof FilterExpression) { return $this->preEscapeFilterNode($node, $env); } elseif ($node instanceof PrintNode && false !== $type = $this->needEscaping($env)) { $expression = $node->getNode('expr'); if ($expression instanceof ConditionalExpression && $this->shouldUnwrapConditional($expression, $env, $type)) { return new DoNode($this->unwrapConditional($expression, $env, $type), $expression->getTemplateLine()); } return $this->escapePrintNode($node, $env, $type); } if ($node instanceof AutoEscapeNode || $node instanceof BlockNode) { array_pop($this->statusStack); } elseif ($node instanceof BlockReferenceNode) { $this->blocks[$node->getAttribute('name')] = $this->needEscaping($env); } return $node; } private function shouldUnwrapConditional(ConditionalExpression $expression, Environment $env, $type) { $expr2Safe = $this->isSafeFor($type, $expression->getNode('expr2'), $env); $expr3Safe = $this->isSafeFor($type, $expression->getNode('expr3'), $env); return $expr2Safe !== $expr3Safe; } private function unwrapConditional(ConditionalExpression $expression, Environment $env, $type) { // convert "echo a ? b : c" to "a ? echo b : echo c" recursively $expr2 = $expression->getNode('expr2'); if ($expr2 instanceof ConditionalExpression && $this->shouldUnwrapConditional($expr2, $env, $type)) { $expr2 = $this->unwrapConditional($expr2, $env, $type); } else { $expr2 = $this->escapeInlinePrintNode(new InlinePrint($expr2, $expr2->getTemplateLine()), $env, $type); } $expr3 = $expression->getNode('expr3'); if ($expr3 instanceof ConditionalExpression && $this->shouldUnwrapConditional($expr3, $env, $type)) { $expr3 = $this->unwrapConditional($expr3, $env, $type); } else { $expr3 = $this->escapeInlinePrintNode(new InlinePrint($expr3, $expr3->getTemplateLine()), $env, $type); } return new ConditionalExpression($expression->getNode('expr1'), $expr2, $expr3, $expression->getTemplateLine()); } private function escapeInlinePrintNode(InlinePrint $node, Environment $env, $type) { $expression = $node->getNode('node'); if ($this->isSafeFor($type, $expression, $env)) { return $node; } return new InlinePrint($this->getEscaperFilter($type, $expression), $node->getTemplateLine()); } private function escapePrintNode(PrintNode $node, Environment $env, $type) { if (false === $type) { return $node; } $expression = $node->getNode('expr'); if ($this->isSafeFor($type, $expression, $env)) { return $node; } $class = \get_class($node); return new $class($this->getEscaperFilter($type, $expression), $node->getTemplateLine()); } private function preEscapeFilterNode(FilterExpression $filter, Environment $env) { $name = $filter->getNode('filter')->getAttribute('value'); $type = $env->getFilter($name)->getPreEscape(); if (null === $type) { return $filter; } $node = $filter->getNode('node'); if ($this->isSafeFor($type, $node, $env)) { return $filter; } $filter->setNode('node', $this->getEscaperFilter($type, $node)); return $filter; } private function isSafeFor($type, Node $expression, $env) { $safe = $this->safeAnalysis->getSafe($expression); if (null === $safe) { if (null === $this->traverser) { $this->traverser = new NodeTraverser($env, [$this->safeAnalysis]); } $this->safeAnalysis->setSafeVars($this->safeVars); $this->traverser->traverse($expression); $safe = $this->safeAnalysis->getSafe($expression); } return \in_array($type, $safe) || \in_array('all', $safe); } private function needEscaping(Environment $env) { if (\count($this->statusStack)) { return $this->statusStack[\count($this->statusStack) - 1]; } return $this->defaultStrategy ? $this->defaultStrategy : false; } private function getEscaperFilter(string $type, Node $node): FilterExpression { $line = $node->getTemplateLine(); $name = new ConstantExpression('escape', $line); $args = new Node([new ConstantExpression((string) $type, $line), new ConstantExpression(null, $line), new ConstantExpression(true, $line)]); return new FilterExpression($node, $name, $args, $line); } public function getPriority() { return 0; } } class_alias('Twig\NodeVisitor\EscaperNodeVisitor', 'Twig_NodeVisitor_Escaper'); php-twig-2.12.5/src/NodeVisitor/MacroAutoImportNodeVisitor.php000066400000000000000000000042231362457344700244000ustar00rootroot00000000000000 */ final class MacroAutoImportNodeVisitor implements NodeVisitorInterface { private $inAModule = false; private $hasMacroCalls = false; public function enterNode(Node $node, Environment $env) { if ($node instanceof ModuleNode) { $this->inAModule = true; $this->hasMacroCalls = false; } return $node; } public function leaveNode(Node $node, Environment $env) { if ($node instanceof ModuleNode) { $this->inAModule = false; if ($this->hasMacroCalls) { $node->getNode('constructor_end')->setNode('_auto_macro_import', new ImportNode(new NameExpression('_self', 0), new AssignNameExpression('_self', 0), 0, 'import', true)); } } elseif ($this->inAModule) { if ( $node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression && '_self' === $node->getNode('node')->getAttribute('name') && $node->getNode('attribute') instanceof ConstantExpression ) { $this->hasMacroCalls = true; $name = $node->getNode('attribute')->getAttribute('value'); $node = new MethodCallExpression($node->getNode('node'), 'macro_'.$name, $node->getNode('arguments'), $node->getTemplateLine()); $node->setAttribute('safe', true); } } return $node; } public function getPriority() { // we must be ran before auto-escaping return -10; } } php-twig-2.12.5/src/NodeVisitor/NodeVisitorInterface.php000066400000000000000000000023251362457344700232140ustar00rootroot00000000000000 */ interface NodeVisitorInterface { /** * Called before child nodes are visited. * * @return Node The modified node */ public function enterNode(Node $node, Environment $env); /** * Called after child nodes are visited. * * @return Node|null The modified node or null if the node must be removed */ public function leaveNode(Node $node, Environment $env); /** * Returns the priority for this visitor. * * Priority should be between -10 and 10 (0 is the default). * * @return int The priority level */ public function getPriority(); } class_alias('Twig\NodeVisitor\NodeVisitorInterface', 'Twig_NodeVisitorInterface'); // Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. class_exists('Twig\Environment'); php-twig-2.12.5/src/NodeVisitor/OptimizerNodeVisitor.php000066400000000000000000000151111362457344700232730ustar00rootroot00000000000000 */ final class OptimizerNodeVisitor extends AbstractNodeVisitor { 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 = []; private $loopsTargets = []; private $optimizers; /** * @param int $optimizers The optimizer mode */ public function __construct(int $optimizers = -1) { if (!\is_int($optimizers) || $optimizers > (self::OPTIMIZE_FOR | self::OPTIMIZE_RAW_FILTER | self::OPTIMIZE_VAR_ACCESS)) { throw new \InvalidArgumentException(sprintf('Optimizer mode "%s" is not valid.', $optimizers)); } $this->optimizers = $optimizers; } protected function doEnterNode(Node $node, Environment $env) { if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR & $this->optimizers)) { $this->enterOptimizeFor($node, $env); } return $node; } protected function doLeaveNode(Node $node, 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()" */ private function optimizePrintNode(Node $node, Environment $env): Node { if (!$node instanceof PrintNode) { return $node; } $exprNode = $node->getNode('expr'); if ( $exprNode instanceof BlockReferenceExpression || $exprNode instanceof ParentExpression ) { $exprNode->setAttribute('output', true); return $exprNode; } return $node; } /** * Removes "raw" filters. */ private function optimizeRawFilter(Node $node, Environment $env): Node { if ($node instanceof FilterExpression && 'raw' == $node->getNode('filter')->getAttribute('value')) { return $node->getNode('node'); } return $node; } /** * Optimizes "for" tag by removing the "loop" variable creation whenever possible. */ private function enterOptimizeFor(Node $node, Environment $env) { if ($node instanceof ForNode) { // disable the loop variable by default $node->setAttribute('with_loop', false); array_unshift($this->loops, $node); array_unshift($this->loopsTargets, $node->getNode('value_target')->getAttribute('name')); array_unshift($this->loopsTargets, $node->getNode('key_target')->getAttribute('name')); } elseif (!$this->loops) { // we are outside a loop return; } // when do we need to add the loop variable back? // the loop variable is referenced for the current loop elseif ($node instanceof NameExpression && 'loop' === $node->getAttribute('name')) { $node->setAttribute('always_defined', true); $this->addLoopToCurrent(); } // optimize access to loop targets elseif ($node instanceof NameExpression && \in_array($node->getAttribute('name'), $this->loopsTargets)) { $node->setAttribute('always_defined', true); } // block reference elseif ($node instanceof BlockReferenceNode || $node instanceof BlockReferenceExpression) { $this->addLoopToCurrent(); } // include without the only attribute elseif ($node instanceof IncludeNode && !$node->getAttribute('only')) { $this->addLoopToAll(); } // include function without the with_context=false parameter elseif ($node instanceof FunctionExpression && 'include' === $node->getAttribute('name') && (!$node->getNode('arguments')->hasNode('with_context') || false !== $node->getNode('arguments')->getNode('with_context')->getAttribute('value') ) ) { $this->addLoopToAll(); } // the loop variable is referenced via an attribute elseif ($node instanceof GetAttrExpression && (!$node->getNode('attribute') instanceof ConstantExpression || 'parent' === $node->getNode('attribute')->getAttribute('value') ) && (true === $this->loops[0]->getAttribute('with_loop') || ($node->getNode('node') instanceof NameExpression && 'loop' === $node->getNode('node')->getAttribute('name') ) ) ) { $this->addLoopToAll(); } } /** * Optimizes "for" tag by removing the "loop" variable creation whenever possible. */ private function leaveOptimizeFor(Node $node, Environment $env) { if ($node instanceof ForNode) { 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\OptimizerNodeVisitor', 'Twig_NodeVisitor_Optimizer'); php-twig-2.12.5/src/NodeVisitor/SafeAnalysisNodeVisitor.php000066400000000000000000000116261362457344700237020ustar00rootroot00000000000000safeVars = $safeVars; } public function getSafe(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(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][] = [ 'key' => $node, 'value' => $safe, ]; } protected function doEnterNode(Node $node, Environment $env) { return $node; } protected function doLeaveNode(Node $node, Environment $env) { if ($node instanceof ConstantExpression) { // constants are marked safe for all $this->setSafe($node, ['all']); } elseif ($node instanceof BlockReferenceExpression) { // blocks are safe by definition $this->setSafe($node, ['all']); } elseif ($node instanceof ParentExpression) { // parent block is safe by definition $this->setSafe($node, ['all']); } elseif ($node instanceof ConditionalExpression) { // intersect safeness of both operands $safe = $this->intersectSafe($this->getSafe($node->getNode('expr2')), $this->getSafe($node->getNode('expr3'))); $this->setSafe($node, $safe); } elseif ($node instanceof FilterExpression) { // filter expression is safe when the filter is safe $name = $node->getNode('filter')->getAttribute('value'); $args = $node->getNode('arguments'); if (false !== $filter = $env->getFilter($name)) { $safe = $filter->getSafe($args); if (null === $safe) { $safe = $this->intersectSafe($this->getSafe($node->getNode('node')), $filter->getPreservesSafety()); } $this->setSafe($node, $safe); } else { $this->setSafe($node, []); } } elseif ($node instanceof FunctionExpression) { // function expression is safe when the function is safe $name = $node->getAttribute('name'); $args = $node->getNode('arguments'); $function = $env->getFunction($name); if (false !== $function) { $this->setSafe($node, $function->getSafe($args)); } else { $this->setSafe($node, []); } } elseif ($node instanceof MethodCallExpression) { if ($node->getAttribute('safe')) { $this->setSafe($node, ['all']); } else { $this->setSafe($node, []); } } elseif ($node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression) { $name = $node->getNode('node')->getAttribute('name'); if (\in_array($name, $this->safeVars)) { $this->setSafe($node, ['all']); } else { $this->setSafe($node, []); } } else { $this->setSafe($node, []); } return $node; } private function intersectSafe(array $a = null, array $b = null): array { if (null === $a || null === $b) { return []; } if (\in_array('all', $a)) { return $b; } if (\in_array('all', $b)) { return $a; } return array_intersect($a, $b); } public function getPriority() { return 0; } } class_alias('Twig\NodeVisitor\SafeAnalysisNodeVisitor', 'Twig_NodeVisitor_SafeAnalysis'); php-twig-2.12.5/src/NodeVisitor/SandboxNodeVisitor.php000066400000000000000000000103201362457344700227040ustar00rootroot00000000000000 */ final class SandboxNodeVisitor extends AbstractNodeVisitor { private $inAModule = false; private $tags; private $filters; private $functions; private $needsToStringWrap = false; protected function doEnterNode(Node $node, Environment $env) { if ($node instanceof ModuleNode) { $this->inAModule = true; $this->tags = []; $this->filters = []; $this->functions = []; return $node; } elseif ($this->inAModule) { // look for tags if ($node->getNodeTag() && !isset($this->tags[$node->getNodeTag()])) { $this->tags[$node->getNodeTag()] = $node; } // look for filters if ($node instanceof FilterExpression && !isset($this->filters[$node->getNode('filter')->getAttribute('value')])) { $this->filters[$node->getNode('filter')->getAttribute('value')] = $node; } // look for functions if ($node instanceof FunctionExpression && !isset($this->functions[$node->getAttribute('name')])) { $this->functions[$node->getAttribute('name')] = $node; } // the .. operator is equivalent to the range() function if ($node instanceof RangeBinary && !isset($this->functions['range'])) { $this->functions['range'] = $node; } if ($node instanceof PrintNode) { $this->needsToStringWrap = true; $this->wrapNode($node, 'expr'); } if ($node instanceof SetNode && !$node->getAttribute('capture')) { $this->needsToStringWrap = true; } // wrap outer nodes that can implicitly call __toString() if ($this->needsToStringWrap) { if ($node instanceof ConcatBinary) { $this->wrapNode($node, 'left'); $this->wrapNode($node, 'right'); } if ($node instanceof FilterExpression) { $this->wrapNode($node, 'node'); $this->wrapArrayNode($node, 'arguments'); } if ($node instanceof FunctionExpression) { $this->wrapArrayNode($node, 'arguments'); } } } return $node; } protected function doLeaveNode(Node $node, Environment $env) { if ($node instanceof ModuleNode) { $this->inAModule = false; $node->getNode('constructor_end')->setNode('_security_check', new Node([new CheckSecurityNode($this->filters, $this->tags, $this->functions), $node->getNode('display_start')])); } elseif ($this->inAModule) { if ($node instanceof PrintNode || $node instanceof SetNode) { $this->needsToStringWrap = false; } } return $node; } private function wrapNode(Node $node, string $name) { $expr = $node->getNode($name); if ($expr instanceof NameExpression || $expr instanceof GetAttrExpression) { $node->setNode($name, new CheckToStringNode($expr)); } } private function wrapArrayNode(Node $node, string $name) { $args = $node->getNode($name); foreach ($args as $name => $_) { $this->wrapNode($args, $name); } } public function getPriority() { return 0; } } class_alias('Twig\NodeVisitor\SandboxNodeVisitor', 'Twig_NodeVisitor_Sandbox'); php-twig-2.12.5/src/Parser.php000066400000000000000000000314431362457344700161200ustar00rootroot00000000000000 */ class Parser { private $stack = []; private $stream; private $parent; private $handlers; private $visitors; private $expressionParser; private $blocks; private $blockStack; private $macros; private $env; private $importedSymbols; private $traits; private $embeddedTemplates = []; private $varNameSalt = 0; public function __construct(Environment $env) { $this->env = $env; } public function getVarName() { return sprintf('__internal_%s', hash('sha256', __METHOD__.$this->stream->getSourceContext()->getCode().$this->varNameSalt++)); } public function parse(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 = []; 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 ExpressionParser($this, $this->env); } $this->stream = $stream; $this->parent = null; $this->blocks = []; $this->macros = []; $this->traits = []; $this->blockStack = []; $this->importedSymbols = [[]]; $this->embeddedTemplates = []; $this->varNameSalt = 0; try { $body = $this->subparse($test, $dropNeedle); if (null !== $this->parent && null === $body = $this->filterBodyNodes($body)) { $body = new Node(); } } catch (SyntaxError $e) { if (!$e->getSourceContext()) { $e->setSourceContext($this->stream->getSourceContext()); } if (!$e->getTemplateLine()) { $e->setTemplateLine($this->stream->getCurrent()->getLine()); } throw $e; } $node = new ModuleNode(new BodyNode([$body]), $this->parent, new Node($this->blocks), new Node($this->macros), new Node($this->traits), $this->embeddedTemplates, $stream->getSourceContext()); $traverser = new 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 = []; while (!$this->stream->isEOF()) { switch ($this->getCurrentToken()->getType()) { case /* Token::TEXT_TYPE */ 0: $token = $this->stream->next(); $rv[] = new TextNode($token->getValue(), $token->getLine()); break; case /* Token::VAR_START_TYPE */ 2: $token = $this->stream->next(); $expr = $this->expressionParser->parseExpression(); $this->stream->expect(/* Token::VAR_END_TYPE */ 4); $rv[] = new PrintNode($expr, $token->getLine()); break; case /* Token::BLOCK_START_TYPE */ 1: $this->stream->next(); $token = $this->getCurrentToken(); if (/* Token::NAME_TYPE */ 5 !== $token->getType()) { throw new SyntaxError('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 Node($rv, [], $lineno); } if (!isset($this->handlers[$token->getValue()])) { if (null !== $test) { $e = new SyntaxError(sprintf('Unexpected "%s" tag', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); if (\is_array($test) && isset($test[0]) && $test[0] instanceof TokenParserInterface) { $e->appendMessage(sprintf(' (expecting closing tag for the "%s" tag defined near line %s).', $test[0]->getTag(), $lineno)); } } else { $e = new SyntaxError(sprintf('Unknown "%s" tag.', $token->getValue()), $token->getLine(), $this->stream->getSourceContext()); $e->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 SyntaxError('Lexer or parser ended up in unsupported state.', $this->getCurrentToken()->getLine(), $this->stream->getSourceContext()); } } if (1 === \count($rv)) { return $rv[0]; } return new Node($rv, [], $lineno); } public function getBlockStack() { return $this->blockStack; } public function peekBlockStack() { return isset($this->blockStack[\count($this->blockStack) - 1]) ? $this->blockStack[\count($this->blockStack) - 1] : null; } 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, BlockNode $value) { $this->blocks[$name] = new BodyNode([$value], [], $value->getTemplateLine()); } public function hasMacro($name) { return isset($this->macros[$name]); } public function setMacro($name, MacroNode $node) { $this->macros[$name] = $node; } /** * @deprecated since Twig 2.7 as there are no reserved macro names anymore, will be removed in 3.0. */ public function isReservedMacroName($name) { @trigger_error(sprintf('The "%s" method is deprecated since Twig 2.7 and will be removed in 3.0.', __METHOD__), E_USER_DEPRECATED); return false; } public function addTrait($trait) { $this->traits[] = $trait; } public function hasTraits() { return \count($this->traits) > 0; } public function embedTemplate(ModuleNode $template) { $template->setIndex(mt_rand()); $this->embeddedTemplates[] = $template; } public function addImportedSymbol($type, $alias, $name = null, AbstractExpression $node = null) { $this->importedSymbols[0][$type][$alias] = ['name' => $name, 'node' => $node]; } public function getImportedSymbol($type, $alias) { // if the symbol does not exist in the current scope (0), try in the main/global scope (last index) return $this->importedSymbols[0][$type][$alias] ?? ($this->importedSymbols[\count($this->importedSymbols) - 1][$type][$alias] ?? null); } public function isMainScope() { return 1 === \count($this->importedSymbols); } public function pushLocalScope() { array_unshift($this->importedSymbols, []); } public function popLocalScope() { array_shift($this->importedSymbols); } /** * @return ExpressionParser */ public function getExpressionParser() { return $this->expressionParser; } public function getParent() { return $this->parent; } public function setParent($parent) { $this->parent = $parent; } /** * @return TokenStream */ public function getStream() { return $this->stream; } /** * @return Token */ public function getCurrentToken() { return $this->stream->getCurrent(); } private function filterBodyNodes(Node $node, bool $nested = false) { // check that the body does not contain non-empty output nodes if ( ($node instanceof TextNode && !ctype_space($node->getAttribute('data'))) || // the "&& !$node instanceof SpacelessNode" part of the condition must be removed in 3.0 (!$node instanceof TextNode && !$node instanceof BlockReferenceNode && ($node instanceof NodeOutputInterface && !$node instanceof SpacelessNode)) ) { if (false !== strpos((string) $node, \chr(0xEF).\chr(0xBB).\chr(0xBF))) { $t = substr($node->getAttribute('data'), 3); if ('' === $t || ctype_space($t)) { // bypass empty nodes starting with a BOM return; } } throw new SyntaxError('A template that extends another one cannot include content outside Twig blocks. Did you forget to put the content inside a {% block %} tag?', $node->getTemplateLine(), $this->stream->getSourceContext()); } // bypass nodes that "capture" the output if ($node instanceof NodeCaptureInterface) { // a "block" tag in such a node will serve as a block definition AND be displayed in place as well return $node; } // to be removed completely in Twig 3.0 if (!$nested && $node instanceof SpacelessNode) { @trigger_error(sprintf('Using the spaceless tag at the root level of a child template in "%s" at line %d is deprecated since Twig 2.5.0 and will become a syntax error in 3.0.', $this->stream->getSourceContext()->getName(), $node->getTemplateLine()), E_USER_DEPRECATED); } // "block" tags that are not captured (see above) are only used for defining // the content of the block. In such a case, nesting it does not work as // expected as the definition is not part of the default template code flow. if ($nested && ($node instanceof BlockReferenceNode || $node instanceof \Twig_Node_BlockReference)) { //throw new SyntaxError('A block definition cannot be nested under non-capturing nodes.', $node->getTemplateLine(), $this->stream->getSourceContext()); @trigger_error(sprintf('Nesting a block definition under a non-capturing node in "%s" at line %d is deprecated since Twig 2.5.0 and will become a syntax error in 3.0.', $this->stream->getSourceContext()->getName(), $node->getTemplateLine()), E_USER_DEPRECATED); return; } // the "&& !$node instanceof SpacelessNode" part of the condition must be removed in 3.0 if ($node instanceof NodeOutputInterface && !$node instanceof SpacelessNode) { return; } // here, $nested means "being at the root level of a child template" // we need to discard the wrapping "Twig_Node" for the "body" node $nested = $nested || ('Twig_Node' !== \get_class($node) && Node::class !== \get_class($node)); foreach ($node as $k => $n) { if (null !== $n && null === $this->filterBodyNodes($n, $nested)) { $node->removeNode($k); } } return $node; } } class_alias('Twig\Parser', 'Twig_Parser'); php-twig-2.12.5/src/Profiler/000077500000000000000000000000001362457344700157305ustar00rootroot00000000000000php-twig-2.12.5/src/Profiler/Dumper/000077500000000000000000000000001362457344700171645ustar00rootroot00000000000000php-twig-2.12.5/src/Profiler/Dumper/BaseDumper.php000066400000000000000000000033561362457344700217330ustar00rootroot00000000000000 */ abstract class BaseDumper { private $root; public function dump(Profile $profile) { return $this->dumpProfile($profile); } abstract protected function formatTemplate(Profile $profile, $prefix); abstract protected function formatNonTemplate(Profile $profile, $prefix); abstract protected function formatTime(Profile $profile, $percent); private function dumpProfile(Profile $profile, $prefix = '', $sibling = false): string { if ($profile->isRoot()) { $this->root = $profile->getDuration(); $start = $profile->getName(); } else { if ($profile->isTemplate()) { $start = $this->formatTemplate($profile, $prefix); } else { $start = $this->formatNonTemplate($profile, $prefix); } $prefix .= $sibling ? '│ ' : ' '; } $percent = $this->root ? $profile->getDuration() / $this->root * 100 : 0; if ($profile->getDuration() * 1000 < 1) { $str = $start."\n"; } else { $str = sprintf("%s %s\n", $start, $this->formatTime($profile, $percent)); } $nCount = \count($profile->getProfiles()); foreach ($profile as $i => $p) { $str .= $this->dumpProfile($p, $prefix, $i + 1 !== $nCount); } return $str; } } class_alias('Twig\Profiler\Dumper\BaseDumper', 'Twig_Profiler_Dumper_Base'); php-twig-2.12.5/src/Profiler/Dumper/BlackfireDumper.php000066400000000000000000000040251362457344700227350ustar00rootroot00000000000000 */ final class BlackfireDumper { public function dump(Profile $profile) { $data = []; $this->dumpProfile('main()', $profile, $data); $this->dumpChildren('main()', $profile, $data); $start = sprintf('%f', microtime(true)); $str = << $values) { $str .= "{$name}//{$values['ct']} {$values['wt']} {$values['mu']} {$values['pmu']}\n"; } return $str; } private function dumpChildren(string $parent, Profile $profile, &$data) { foreach ($profile as $p) { if ($p->isTemplate()) { $name = $p->getTemplate(); } else { $name = sprintf('%s::%s(%s)', $p->getTemplate(), $p->getType(), $p->getName()); } $this->dumpProfile(sprintf('%s==>%s', $parent, $name), $p, $data); $this->dumpChildren($name, $p, $data); } } private function dumpProfile(string $edge, Profile $profile, &$data) { if (isset($data[$edge])) { ++$data[$edge]['ct']; $data[$edge]['wt'] += floor($profile->getDuration() * 1000000); $data[$edge]['mu'] += $profile->getMemoryUsage(); $data[$edge]['pmu'] += $profile->getPeakMemoryUsage(); } else { $data[$edge] = [ 'ct' => 1, 'wt' => floor($profile->getDuration() * 1000000), 'mu' => $profile->getMemoryUsage(), 'pmu' => $profile->getPeakMemoryUsage(), ]; } } } class_alias('Twig\Profiler\Dumper\BlackfireDumper', 'Twig_Profiler_Dumper_Blackfire'); php-twig-2.12.5/src/Profiler/Dumper/HtmlDumper.php000066400000000000000000000027201362457344700217570ustar00rootroot00000000000000 */ final class HtmlDumper extends BaseDumper { private static $colors = [ 'block' => '#dfd', 'macro' => '#ddf', 'template' => '#ffd', 'big' => '#d44', ]; public function dump(Profile $profile) { return '
    '.parent::dump($profile).'
    '; } protected function formatTemplate(Profile $profile, $prefix) { return sprintf('%s└ %s', $prefix, self::$colors['template'], $profile->getTemplate()); } protected function formatNonTemplate(Profile $profile, $prefix) { return sprintf('%s└ %s::%s(%s)', $prefix, $profile->getTemplate(), $profile->getType(), isset(self::$colors[$profile->getType()]) ? self::$colors[$profile->getType()] : 'auto', $profile->getName()); } protected function formatTime(Profile $profile, $percent) { return sprintf('%.2fms/%.0f%%', $percent > 20 ? self::$colors['big'] : 'auto', $profile->getDuration() * 1000, $percent); } } class_alias('Twig\Profiler\Dumper\HtmlDumper', 'Twig_Profiler_Dumper_Html'); php-twig-2.12.5/src/Profiler/Dumper/TextDumper.php000066400000000000000000000016661362457344700220070ustar00rootroot00000000000000 */ final class TextDumper extends BaseDumper { protected function formatTemplate(Profile $profile, $prefix) { return sprintf('%s└ %s', $prefix, $profile->getTemplate()); } protected function formatNonTemplate(Profile $profile, $prefix) { return sprintf('%s└ %s::%s(%s)', $prefix, $profile->getTemplate(), $profile->getType(), $profile->getName()); } protected function formatTime(Profile $profile, $percent) { return sprintf('%.2fms/%.0f%%', $profile->getDuration() * 1000, $percent); } } class_alias('Twig\Profiler\Dumper\TextDumper', 'Twig_Profiler_Dumper_Text'); php-twig-2.12.5/src/Profiler/Node/000077500000000000000000000000001362457344700166155ustar00rootroot00000000000000php-twig-2.12.5/src/Profiler/Node/EnterProfileNode.php000066400000000000000000000024571362457344700225420ustar00rootroot00000000000000 */ class EnterProfileNode extends Node { public function __construct(string $extensionName, string $type, string $name, string $varName) { parent::__construct([], ['extension_name' => $extensionName, 'name' => $name, 'type' => $type, 'var_name' => $varName]); } public function compile(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\EnterProfileNode', 'Twig_Profiler_Node_EnterProfile'); php-twig-2.12.5/src/Profiler/Node/LeaveProfileNode.php000066400000000000000000000015351362457344700225150ustar00rootroot00000000000000 */ class LeaveProfileNode extends Node { public function __construct(string $varName) { parent::__construct([], ['var_name' => $varName]); } public function compile(Compiler $compiler) { $compiler ->write("\n") ->write(sprintf("\$%s->leave(\$%s);\n\n", $this->getAttribute('var_name'), $this->getAttribute('var_name').'_prof')) ; } } class_alias('Twig\Profiler\Node\LeaveProfileNode', 'Twig_Profiler_Node_LeaveProfile'); php-twig-2.12.5/src/Profiler/NodeVisitor/000077500000000000000000000000001362457344700201755ustar00rootroot00000000000000php-twig-2.12.5/src/Profiler/NodeVisitor/ProfilerNodeVisitor.php000066400000000000000000000045731362457344700246670ustar00rootroot00000000000000 */ final class ProfilerNodeVisitor extends AbstractNodeVisitor { private $extensionName; public function __construct(string $extensionName) { $this->extensionName = $extensionName; } protected function doEnterNode(Node $node, Environment $env) { return $node; } protected function doLeaveNode(Node $node, Environment $env) { if ($node instanceof ModuleNode) { $varName = $this->getVarName(); $node->setNode('display_start', new Node([new EnterProfileNode($this->extensionName, Profile::TEMPLATE, $node->getTemplateName(), $varName), $node->getNode('display_start')])); $node->setNode('display_end', new Node([new LeaveProfileNode($varName), $node->getNode('display_end')])); } elseif ($node instanceof BlockNode) { $varName = $this->getVarName(); $node->setNode('body', new BodyNode([ new EnterProfileNode($this->extensionName, Profile::BLOCK, $node->getAttribute('name'), $varName), $node->getNode('body'), new LeaveProfileNode($varName), ])); } elseif ($node instanceof MacroNode) { $varName = $this->getVarName(); $node->setNode('body', new BodyNode([ new EnterProfileNode($this->extensionName, Profile::MACRO, $node->getAttribute('name'), $varName), $node->getNode('body'), new LeaveProfileNode($varName), ])); } return $node; } private function getVarName(): string { return sprintf('__internal_%s', hash('sha256', $this->extensionName)); } public function getPriority() { return 0; } } class_alias('Twig\Profiler\NodeVisitor\ProfilerNodeVisitor', 'Twig_Profiler_NodeVisitor_Profiler'); php-twig-2.12.5/src/Profiler/Profile.php000066400000000000000000000103501362457344700200400ustar00rootroot00000000000000 * * @final since Twig 2.4.0 */ class Profile implements \IteratorAggregate, \Serializable { const ROOT = 'ROOT'; const BLOCK = 'block'; const TEMPLATE = 'template'; const MACRO = 'macro'; private $template; private $name; private $type; private $starts = []; private $ends = []; private $profiles = []; public function __construct(string $template = 'main', string $type = self::ROOT, string $name = 'main') { if (__CLASS__ !== \get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since Twig 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(self $profile) { $this->profiles[] = $profile; } /** * Returns the duration in microseconds. * * @return float */ 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 = [ 'wt' => microtime(true), 'mu' => memory_get_usage(), 'pmu' => memory_get_peak_usage(), ]; } /** * Stops the profiling. */ public function leave() { $this->ends = [ 'wt' => microtime(true), 'mu' => memory_get_usage(), 'pmu' => memory_get_peak_usage(), ]; } public function reset() { $this->starts = $this->ends = $this->profiles = []; $this->enter(); } public function getIterator() { return new \ArrayIterator($this->profiles); } public function serialize() { return serialize($this->__serialize()); } public function unserialize($data) { $this->__unserialize(unserialize($data)); } /** * @internal */ public function __serialize() { return [$this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles]; } /** * @internal */ public function __unserialize(array $data) { list($this->template, $this->name, $this->type, $this->starts, $this->ends, $this->profiles) = $data; } } class_alias('Twig\Profiler\Profile', 'Twig_Profiler_Profile'); php-twig-2.12.5/src/RuntimeLoader/000077500000000000000000000000001362457344700167205ustar00rootroot00000000000000php-twig-2.12.5/src/RuntimeLoader/ContainerRuntimeLoader.php000066400000000000000000000017221362457344700240500ustar00rootroot00000000000000 * @author Robin Chalas */ class ContainerRuntimeLoader implements RuntimeLoaderInterface { private $container; public function __construct(ContainerInterface $container) { $this->container = $container; } public function load($class) { if ($this->container->has($class)) { return $this->container->get($class); } } } class_alias('Twig\RuntimeLoader\ContainerRuntimeLoader', 'Twig_ContainerRuntimeLoader'); php-twig-2.12.5/src/RuntimeLoader/FactoryRuntimeLoader.php000066400000000000000000000016111362457344700235320ustar00rootroot00000000000000 */ class FactoryRuntimeLoader implements RuntimeLoaderInterface { private $map; /** * @param array $map An array where keys are class names and values factory callables */ public function __construct(array $map = []) { $this->map = $map; } public function load($class) { if (isset($this->map[$class])) { $runtimeFactory = $this->map[$class]; return $runtimeFactory(); } } } class_alias('Twig\RuntimeLoader\FactoryRuntimeLoader', 'Twig_FactoryRuntimeLoader'); php-twig-2.12.5/src/RuntimeLoader/RuntimeLoaderInterface.php000066400000000000000000000014611362457344700240260ustar00rootroot00000000000000 */ interface RuntimeLoaderInterface { /** * Creates the runtime implementation of a Twig element (filter/function/test). * * @param string $class A runtime class * * @return object|null The runtime instance or null if the loader does not know how to create the runtime for this class */ public function load($class); } class_alias('Twig\RuntimeLoader\RuntimeLoaderInterface', 'Twig_RuntimeLoaderInterface'); php-twig-2.12.5/src/Sandbox/000077500000000000000000000000001362457344700155445ustar00rootroot00000000000000php-twig-2.12.5/src/Sandbox/SecurityError.php000066400000000000000000000007431362457344700211020ustar00rootroot00000000000000 */ class SecurityError extends Error { } class_alias('Twig\Sandbox\SecurityError', 'Twig_Sandbox_SecurityError'); php-twig-2.12.5/src/Sandbox/SecurityNotAllowedFilterError.php000066400000000000000000000027611362457344700242430ustar00rootroot00000000000000 * * @final */ class SecurityNotAllowedFilterError extends SecurityError { private $filterName; public function __construct(string $message, string $functionName, int $lineno = -1, string $filename = null, \Exception $previous = null) { if (-1 !== $lineno) { @trigger_error(sprintf('Passing $lineno as a 3th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $filename) { @trigger_error(sprintf('Passing $filename as a 4th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $previous) { @trigger_error(sprintf('Passing $previous as a 5th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } parent::__construct($message, $lineno, $filename, $previous); $this->filterName = $functionName; } public function getFilterName() { return $this->filterName; } } class_alias('Twig\Sandbox\SecurityNotAllowedFilterError', 'Twig_Sandbox_SecurityNotAllowedFilterError'); php-twig-2.12.5/src/Sandbox/SecurityNotAllowedFunctionError.php000066400000000000000000000030011362457344700245670ustar00rootroot00000000000000 * * @final */ class SecurityNotAllowedFunctionError extends SecurityError { private $functionName; public function __construct(string $message, string $functionName, int $lineno = -1, string $filename = null, \Exception $previous = null) { if (-1 !== $lineno) { @trigger_error(sprintf('Passing $lineno as a 3th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $filename) { @trigger_error(sprintf('Passing $filename as a 4th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $previous) { @trigger_error(sprintf('Passing $previous as a 5th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } parent::__construct($message, $lineno, $filename, $previous); $this->functionName = $functionName; } public function getFunctionName() { return $this->functionName; } } class_alias('Twig\Sandbox\SecurityNotAllowedFunctionError', 'Twig_Sandbox_SecurityNotAllowedFunctionError'); php-twig-2.12.5/src/Sandbox/SecurityNotAllowedMethodError.php000066400000000000000000000032221362457344700242270ustar00rootroot00000000000000 * * @final */ class SecurityNotAllowedMethodError extends SecurityError { private $className; private $methodName; public function __construct(string $message, string $className, string $methodName, int $lineno = -1, string $filename = null, \Exception $previous = null) { if (-1 !== $lineno) { @trigger_error(sprintf('Passing $lineno as a 3th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $filename) { @trigger_error(sprintf('Passing $filename as a 4th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $previous) { @trigger_error(sprintf('Passing $previous as a 5th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } 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'); php-twig-2.12.5/src/Sandbox/SecurityNotAllowedPropertyError.php000066400000000000000000000032461362457344700246410ustar00rootroot00000000000000 * * @final */ class SecurityNotAllowedPropertyError extends SecurityError { private $className; private $propertyName; public function __construct(string $message, string $className, string $propertyName, int $lineno = -1, string $filename = null, \Exception $previous = null) { if (-1 !== $lineno) { @trigger_error(sprintf('Passing $lineno as a 3th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $filename) { @trigger_error(sprintf('Passing $filename as a 4th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $previous) { @trigger_error(sprintf('Passing $previous as a 5th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } 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'); php-twig-2.12.5/src/Sandbox/SecurityNotAllowedTagError.php000066400000000000000000000027171362457344700235320ustar00rootroot00000000000000 * * @final */ class SecurityNotAllowedTagError extends SecurityError { private $tagName; public function __construct(string $message, string $tagName, int $lineno = -1, string $filename = null, \Exception $previous = null) { if (-1 !== $lineno) { @trigger_error(sprintf('Passing $lineno as a 3th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $filename) { @trigger_error(sprintf('Passing $filename as a 4th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } if (null !== $previous) { @trigger_error(sprintf('Passing $previous as a 5th argument of the %s constructor is deprecated since Twig 2.8.1.', __CLASS__), E_USER_DEPRECATED); } parent::__construct($message, $lineno, $filename, $previous); $this->tagName = $tagName; } public function getTagName() { return $this->tagName; } } class_alias('Twig\Sandbox\SecurityNotAllowedTagError', 'Twig_Sandbox_SecurityNotAllowedTagError'); php-twig-2.12.5/src/Sandbox/SecurityPolicy.php000066400000000000000000000077061362457344700212560ustar00rootroot00000000000000 */ final class SecurityPolicy implements SecurityPolicyInterface { private $allowedTags; private $allowedFilters; private $allowedMethods; private $allowedProperties; private $allowedFunctions; public function __construct(array $allowedTags = [], array $allowedFilters = [], array $allowedMethods = [], array $allowedProperties = [], array $allowedFunctions = []) { $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 = []; foreach ($methods as $class => $m) { $this->allowedMethods[$class] = array_map(function ($value) { return strtr($value, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); }, \is_array($m) ? $m : [$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 SecurityNotAllowedTagError(sprintf('Tag "%s" is not allowed.', $tag), $tag); } } foreach ($filters as $filter) { if (!\in_array($filter, $this->allowedFilters)) { throw new SecurityNotAllowedFilterError(sprintf('Filter "%s" is not allowed.', $filter), $filter); } } foreach ($functions as $function) { if (!\in_array($function, $this->allowedFunctions)) { throw new SecurityNotAllowedFunctionError(sprintf('Function "%s" is not allowed.', $function), $function); } } } public function checkMethodAllowed($obj, $method) { if ($obj instanceof Template || $obj instanceof Markup) { return; } $allowed = false; $method = strtr($method, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'); foreach ($this->allowedMethods as $class => $methods) { if ($obj instanceof $class) { $allowed = \in_array($method, $methods); break; } } if (!$allowed) { $class = \get_class($obj); throw new SecurityNotAllowedMethodError(sprintf('Calling "%s" method on a "%s" object is not allowed.', $method, $class), $class, $method); } } public function checkPropertyAllowed($obj, $property) { $allowed = false; foreach ($this->allowedProperties as $class => $properties) { if ($obj instanceof $class) { $allowed = \in_array($property, \is_array($properties) ? $properties : [$properties]); break; } } if (!$allowed) { $class = \get_class($obj); throw new SecurityNotAllowedPropertyError(sprintf('Calling "%s" property on a "%s" object is not allowed.', $property, $class), $class, $property); } } } class_alias('Twig\Sandbox\SecurityPolicy', 'Twig_Sandbox_SecurityPolicy'); php-twig-2.12.5/src/Sandbox/SecurityPolicyInterface.php000066400000000000000000000014751362457344700230740ustar00rootroot00000000000000 */ interface SecurityPolicyInterface { /** * @throws SecurityError */ public function checkSecurity($tags, $filters, $functions); /** * @throws SecurityNotAllowedMethodError */ public function checkMethodAllowed($obj, $method); /** * @throws SecurityNotAllowedPropertyError */ public function checkPropertyAllowed($obj, $method); } class_alias('Twig\Sandbox\SecurityPolicyInterface', 'Twig_Sandbox_SecurityPolicyInterface'); php-twig-2.12.5/src/Source.php000066400000000000000000000020431362457344700161160ustar00rootroot00000000000000 */ final class 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(string $code, string $name, string $path = '') { $this->code = $code; $this->name = $name; $this->path = $path; } public function getCode(): string { return $this->code; } public function getName() { return $this->name; } public function getPath(): string { return $this->path; } } class_alias('Twig\Source', 'Twig_Source'); php-twig-2.12.5/src/Template.php000066400000000000000000000315461362457344700164430ustar00rootroot00000000000000load() * instead, which returns an instance of \Twig\TemplateWrapper. * * @author Fabien Potencier * * @internal */ abstract class Template { const ANY_CALL = 'any'; const ARRAY_CALL = 'array'; const METHOD_CALL = 'method'; protected $parent; protected $parents = []; protected $env; protected $blocks = []; protected $traits = []; protected $extensions = []; protected $sandbox; public function __construct(Environment $env) { $this->env = $env; $this->extensions = $env->getExtensions(); } /** * @internal this method will be removed in 3.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 */ abstract public function getDebugInfo(); /** * Returns information about the original template source code. * * @return Source */ public function getSourceContext() { return new Source('', $this->getTemplateName()); } /** * Returns the parent template. * * This method is for internal use only and should never be called * directly. * * @param array $context * * @return Template|TemplateWrapper|false The parent template or false if there is no parent */ 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 || $parent instanceof TemplateWrapper) { return $this->parents[$parent->getSourceContext()->getName()] = $parent; } if (!isset($this->parents[$parent])) { $this->parents[$parent] = $this->loadTemplate($parent); } } catch (LoaderError $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 */ public function displayParentBlock($name, array $context, array $blocks = []) { 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 RuntimeError(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 */ public function displayBlock($name, array $context, array $blocks = [], $useBlocks = true, self $templateContext = null) { 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 (Error $e) { if (!$e->getSourceContext()) { $e->setSourceContext($template->getSourceContext()); } // this is mostly useful for \Twig\Error\LoaderError exceptions // see \Twig\Error\LoaderError if (-1 === $e->getTemplateLine()) { $e->guess(); } throw $e; } catch (\Exception $e) { $e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $template->getSourceContext(), $e); $e->guess(); throw $e; } } elseif (false !== $parent = $this->getParent($context)) { $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks), false, $templateContext ?? $this); } elseif (isset($blocks[$name])) { throw new RuntimeError(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]->getSourceContext()); } else { throw new RuntimeError(sprintf('Block "%s" on template "%s" does not exist.', $name, $this->getTemplateName()), -1, ($templateContext ?? $this)->getSourceContext()); } } /** * 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 */ public function renderParentBlock($name, array $context, array $blocks = []) { if ($this->env->isDebug()) { ob_start(); } else { ob_start(function () { return ''; }); } $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 */ public function renderBlock($name, array $context, array $blocks = [], $useBlocks = true) { if ($this->env->isDebug()) { ob_start(); } else { ob_start(function () { return ''; }); } $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 */ public function hasBlock($name, array $context, array $blocks = []) { 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 */ public function getBlockNames(array $context, array $blocks = []) { $names = array_merge(array_keys($blocks), array_keys($this->blocks)); if (false !== $parent = $this->getParent($context)) { $names = array_merge($names, $parent->getBlockNames($context)); } return array_unique($names); } /** * @return Template|TemplateWrapper */ protected function loadTemplate($template, $templateName = null, $line = null, $index = null) { try { if (\is_array($template)) { return $this->env->resolveTemplate($template); } if ($template instanceof self || $template instanceof TemplateWrapper) { return $template; } if ($template === $this->getTemplateName()) { $class = \get_class($this); if (false !== $pos = strrpos($class, '___', -1)) { $class = substr($class, 0, $pos); } return $this->env->loadClass($class, $template, $index); } return $this->env->loadTemplate($template, $index); } catch (Error $e) { if (!$e->getSourceContext()) { $e->setSourceContext($templateName ? new Source('', $templateName) : $this->getSourceContext()); } if ($e->getTemplateLine() > 0) { throw $e; } if (!$line) { $e->guess(); } else { $e->setTemplateLine($line); } throw $e; } } /** * @internal * * @return Template */ protected function unwrap() { return $this; } /** * Returns all blocks. * * This method is for internal use only and should never be called * directly. * * @return array An array of blocks */ public function getBlocks() { return $this->blocks; } public function display(array $context, array $blocks = []) { $this->displayWithErrorHandling($this->env->mergeGlobals($context), array_merge($this->blocks, $blocks)); } public function render(array $context) { $level = ob_get_level(); if ($this->env->isDebug()) { ob_start(); } else { ob_start(function () { return ''; }); } 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 = []) { try { $this->doDisplay($context, $blocks); } catch (Error $e) { if (!$e->getSourceContext()) { $e->setSourceContext($this->getSourceContext()); } // this is mostly useful for \Twig\Error\LoaderError exceptions // see \Twig\Error\LoaderError if (-1 === $e->getTemplateLine()) { $e->guess(); } throw $e; } catch (\Exception $e) { $e = new RuntimeError(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, $this->getSourceContext(), $e); $e->guess(); throw $e; } } /** * 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 = []); } class_alias('Twig\Template', 'Twig_Template'); php-twig-2.12.5/src/TemplateWrapper.php000066400000000000000000000072611362457344700200010ustar00rootroot00000000000000 */ final class 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(Environment $env, Template $template) { $this->env = $env; $this->template = $template; } /** * Renders the template. * * @param array $context An array of parameters to pass to the template */ public function render(array $context = []): string { // using func_get_args() allows to not expose the blocks argument // as it should only be used by internal code return $this->template->render($context, \func_get_args()[1] ?? []); } /** * Displays the template. * * @param array $context An array of parameters to pass to the template */ public function display(array $context = []) { // using func_get_args() allows to not expose the blocks argument // as it should only be used by internal code $this->template->display($context, \func_get_args()[1] ?? []); } /** * Checks if a block is defined. * * @param string $name The block name * @param array $context An array of parameters to pass to the template */ public function hasBlock(string $name, array $context = []): bool { 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(array $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(string $name, array $context = []): string { $context = $this->env->mergeGlobals($context); $level = ob_get_level(); if ($this->env->isDebug()) { ob_start(); } else { ob_start(function () { return ''; }); } 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(string $name, array $context = []) { $this->template->displayBlock($name, $this->env->mergeGlobals($context)); } public function getSourceContext(): Source { return $this->template->getSourceContext(); } public function getTemplateName(): string { return $this->template->getTemplateName(); } /** * @internal * * @return Template */ public function unwrap() { return $this->template; } } class_alias('Twig\TemplateWrapper', 'Twig_TemplateWrapper'); php-twig-2.12.5/src/Test/000077500000000000000000000000001362457344700150655ustar00rootroot00000000000000php-twig-2.12.5/src/Test/IntegrationTestCase.php000066400000000000000000000214631362457344700215230ustar00rootroot00000000000000 * @author Karma Dordrak */ abstract class IntegrationTestCase extends TestCase { /** * @return string */ abstract protected function getFixturesDir(); /** * @return RuntimeLoaderInterface[] */ protected function getRuntimeLoaders() { return []; } /** * @return ExtensionInterface[] */ protected function getExtensions() { return []; } /** * @return TwigFilter[] */ protected function getTwigFilters() { return []; } /** * @return TwigFunction[] */ protected function getTwigFunctions() { return []; } /** * @return TwigTest[] */ protected function getTwigTests() { return []; } /** * @dataProvider getTests */ public function testIntegration($file, $message, $condition, $templates, $exception, $outputs, $deprecation = '') { $this->doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs, $deprecation); } /** * @dataProvider getLegacyTests * @group legacy */ public function testLegacyIntegration($file, $message, $condition, $templates, $exception, $outputs, $deprecation = '') { $this->doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs, $deprecation); } public function getTests($name, $legacyTests = false) { $fixturesDir = realpath($this->getFixturesDir()); $tests = []; 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*(?:--DEPRECATION--\s*(.*?))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)\s*(?:--DATA--\s*(.*))?\s*--EXCEPTION--\s*(.*)/sx', $test, $match)) { $message = $match[1]; $condition = $match[2]; $deprecation = $match[3]; $templates = self::parseTemplates($match[4]); $exception = $match[6]; $outputs = [[null, $match[5], null, '']]; } elseif (preg_match('/--TEST--\s*(.*?)\s*(?:--CONDITION--\s*(.*))?\s*(?:--DEPRECATION--\s*(.*?))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)--DATA--.*?--EXPECT--.*/s', $test, $match)) { $message = $match[1]; $condition = $match[2]; $deprecation = $match[3]; $templates = self::parseTemplates($match[4]); $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[] = [str_replace($fixturesDir.'/', '', $file), $message, $condition, $templates, $exception, $outputs, $deprecation]; } if ($legacyTests && empty($tests)) { // add a dummy test to avoid a PHPUnit message return [['not', '-', '', [], '', []]]; } return $tests; } public function getLegacyTests() { return $this->getTests('testLegacyIntegration', true); } protected function doIntegrationTest($file, $message, $condition, $templates, $exception, $outputs, $deprecation = '') { if (!$outputs) { $this->markTestSkipped('no tests to run'); } if ($condition) { eval('$ret = '.$condition.';'); if (!$ret) { $this->markTestSkipped($condition); } } $loader = new ArrayLoader($templates); foreach ($outputs as $i => $match) { $config = array_merge([ 'cache' => false, 'strict_variables' => true, ], $match[2] ? eval($match[2].';') : []); $twig = new 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).'_'); $deprecations = []; try { $prevHandler = set_error_handler(function ($type, $msg, $file, $line, $context = []) use (&$deprecations, &$prevHandler) { if (E_USER_DEPRECATED === $type) { $deprecations[] = $msg; return true; } return $prevHandler ? $prevHandler($type, $msg, $file, $line, $context) : false; }); $template = $twig->load('index.twig'); } catch (\Exception $e) { if (false !== $exception) { $message = $e->getMessage(); $this->assertSame(trim($exception), trim(sprintf('%s: %s', \get_class($e), $message))); $last = substr($message, \strlen($message) - 1); $this->assertTrue('.' === $last || '?' === $last, 'Exception message must end with a dot or a question mark.'); return; } throw new Error(sprintf('%s: %s', \get_class($e), $e->getMessage()), -1, null, $e); } finally { restore_error_handler(); } $this->assertSame($deprecation, implode("\n", $deprecations)); 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 Error(sprintf('%s: %s', \get_class($e), $e->getMessage()), -1, null, $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 = []; 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'); php-twig-2.12.5/src/Test/NodeTestCase.php000066400000000000000000000033411362457344700201200ustar00rootroot00000000000000assertNodeCompilation($source, $node, $environment, $isPattern); } public function assertNodeCompilation($source, Node $node, 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(Environment $environment = null) { return new Compiler(null === $environment ? $this->getEnvironment() : $environment); } protected function getEnvironment() { return new Environment(new ArrayLoader([])); } protected function getVariableGetter($name, $line = false) { $line = $line > 0 ? "// line {$line}\n" : ''; return sprintf('%s($context["%s"] ?? null)', $line, $name); } protected function getAttributeGetter() { return 'twig_get_attribute($this->env, $this->source, '; } } class_alias('Twig\Test\NodeTestCase', 'Twig_Test_NodeTestCase'); php-twig-2.12.5/src/Token.php000066400000000000000000000135341362457344700157450ustar00rootroot00000000000000 */ final class 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; const ARROW_TYPE = 12; /** * @param int $type The type of the token * @param string $value The token value * @param int $lineno The line position in the source */ public function __construct($type, $value, $lineno) { $this->type = $type; $this->value = $value; $this->lineno = $lineno; } public function __toString() { return sprintf('%s(%s)', self::typeToString($this->type, true), $this->value); } /** * Tests the current token for a type and/or a value. * * Parameters may be: * * just type * * type and value (or array of possible values) * * just value (or array of possible values) (NAME_TYPE is used as type) * * @param array|string|int $type The type to test * @param array|string|null $values The token value * * @return bool */ public function test($type, $values = null) { if (null === $values && !\is_int($type)) { $values = $type; $type = self::NAME_TYPE; } return ($this->type === $type) && ( null === $values || (\is_array($values) && \in_array($this->value, $values)) || $this->value == $values ); } /** * @return int */ public function getLine() { return $this->lineno; } /** * @return int */ public function getType() { return $this->type; } /** * @return string */ public function getValue() { return $this->value; } /** * Returns the constant representation (internal) of a given type. * * @param int $type The type as an integer * @param bool $short Whether to return a short representation or not * * @return string The string representation */ public static function typeToString($type, $short = false) { switch ($type) { case self::EOF_TYPE: $name = 'EOF_TYPE'; break; case self::TEXT_TYPE: $name = 'TEXT_TYPE'; break; case self::BLOCK_START_TYPE: $name = 'BLOCK_START_TYPE'; break; case self::VAR_START_TYPE: $name = 'VAR_START_TYPE'; break; case self::BLOCK_END_TYPE: $name = 'BLOCK_END_TYPE'; break; case self::VAR_END_TYPE: $name = 'VAR_END_TYPE'; break; case self::NAME_TYPE: $name = 'NAME_TYPE'; break; case self::NUMBER_TYPE: $name = 'NUMBER_TYPE'; break; case self::STRING_TYPE: $name = 'STRING_TYPE'; break; case self::OPERATOR_TYPE: $name = 'OPERATOR_TYPE'; break; case self::PUNCTUATION_TYPE: $name = 'PUNCTUATION_TYPE'; break; case self::INTERPOLATION_START_TYPE: $name = 'INTERPOLATION_START_TYPE'; break; case self::INTERPOLATION_END_TYPE: $name = 'INTERPOLATION_END_TYPE'; break; case self::ARROW_TYPE: $name = 'ARROW_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'; case self::ARROW_TYPE: return 'arrow function'; default: throw new \LogicException(sprintf('Token of type "%s" does not exist.', $type)); } } } class_alias('Twig\Token', 'Twig_Token'); php-twig-2.12.5/src/TokenParser/000077500000000000000000000000001362457344700164035ustar00rootroot00000000000000php-twig-2.12.5/src/TokenParser/AbstractTokenParser.php000066400000000000000000000012011362457344700230270ustar00rootroot00000000000000 */ abstract class AbstractTokenParser implements TokenParserInterface { /** * @var Parser */ protected $parser; public function setParser(Parser $parser) { $this->parser = $parser; } } class_alias('Twig\TokenParser\AbstractTokenParser', 'Twig_TokenParser'); php-twig-2.12.5/src/TokenParser/ApplyTokenParser.php000066400000000000000000000026611362457344700223640ustar00rootroot00000000000000getLine(); $name = $this->parser->getVarName(); $ref = new TempNameExpression($name, $lineno); $ref->setAttribute('always_defined', true); $filter = $this->parser->getExpressionParser()->parseFilterExpressionRaw($ref, $this->getTag()); $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); $body = $this->parser->subparse([$this, 'decideApplyEnd'], true); $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new Node([ new SetNode(true, $ref, $body, $lineno, $this->getTag()), new PrintNode($filter, $lineno, $this->getTag()), ]); } public function decideApplyEnd(Token $token) { return $token->test('endapply'); } public function getTag() { return 'apply'; } } php-twig-2.12.5/src/TokenParser/AutoEscapeTokenParser.php000066400000000000000000000031151362457344700233230ustar00rootroot00000000000000getLine(); $stream = $this->parser->getStream(); if ($stream->test(/* Token::BLOCK_END_TYPE */ 3)) { $value = 'html'; } else { $expr = $this->parser->getExpressionParser()->parseExpression(); if (!$expr instanceof ConstantExpression) { throw new SyntaxError('An escaping strategy must be a string or false.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); } $value = $expr->getAttribute('value'); } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); return new AutoEscapeNode($value, $body, $lineno, $this->getTag()); } public function decideBlockEnd(Token $token) { return $token->test('endautoescape'); } public function getTag() { return 'autoescape'; } } class_alias('Twig\TokenParser\AutoEscapeTokenParser', 'Twig_TokenParser_AutoEscape'); php-twig-2.12.5/src/TokenParser/BlockTokenParser.php000066400000000000000000000047301362457344700223300ustar00rootroot00000000000000 * {% block title %}{% endblock %} - My Webpage * {% endblock %} */ final class BlockTokenParser extends AbstractTokenParser { public function parse(Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); if ($this->parser->hasBlock($name)) { throw new SyntaxError(sprintf("The block '%s' has already been defined line %d.", $name, $this->parser->getBlock($name)->getTemplateLine()), $stream->getCurrent()->getLine(), $stream->getSourceContext()); } $this->parser->setBlock($name, $block = new BlockNode($name, new Node([]), $lineno)); $this->parser->pushLocalScope(); $this->parser->pushBlockStack($name); if ($stream->nextIf(/* Token::BLOCK_END_TYPE */ 3)) { $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) { $value = $token->getValue(); if ($value != $name) { throw new SyntaxError(sprintf('Expected endblock for block "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext()); } } } else { $body = new Node([ new PrintNode($this->parser->getExpressionParser()->parseExpression(), $lineno), ]); } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $block->setNode('body', $body); $this->parser->popBlockStack(); $this->parser->popLocalScope(); return new BlockReferenceNode($name, $lineno, $this->getTag()); } public function decideBlockEnd(Token $token) { return $token->test('endblock'); } public function getTag() { return 'block'; } } class_alias('Twig\TokenParser\BlockTokenParser', 'Twig_TokenParser_Block'); php-twig-2.12.5/src/TokenParser/DeprecatedTokenParser.php000066400000000000000000000017651362457344700233430ustar00rootroot00000000000000 * * @final */ class DeprecatedTokenParser extends AbstractTokenParser { public function parse(Token $token) { $expr = $this->parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new DeprecatedNode($expr, $token->getLine(), $this->getTag()); } public function getTag() { return 'deprecated'; } } class_alias('Twig\TokenParser\DeprecatedTokenParser', 'Twig_TokenParser_Deprecated'); php-twig-2.12.5/src/TokenParser/DoTokenParser.php000066400000000000000000000014411362457344700216340ustar00rootroot00000000000000parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect(/* Token::BLOCK_END_TYPE */ 3); return new DoNode($expr, $token->getLine(), $this->getTag()); } public function getTag() { return 'do'; } } class_alias('Twig\TokenParser\DoTokenParser', 'Twig_TokenParser_Do'); php-twig-2.12.5/src/TokenParser/EmbedTokenParser.php000066400000000000000000000043651362457344700223160ustar00rootroot00000000000000parser->getStream(); $parent = $this->parser->getExpressionParser()->parseExpression(); list($variables, $only, $ignoreMissing) = $this->parseArguments(); $parentToken = $fakeParentToken = new Token(/* Token::STRING_TYPE */ 7, '__parent__', $token->getLine()); if ($parent instanceof ConstantExpression) { $parentToken = new Token(/* Token::STRING_TYPE */ 7, $parent->getAttribute('value'), $token->getLine()); } elseif ($parent instanceof NameExpression) { $parentToken = new Token(/* Token::NAME_TYPE */ 5, $parent->getAttribute('name'), $token->getLine()); } // inject a fake parent to make the parent() function work $stream->injectTokens([ new Token(/* Token::BLOCK_START_TYPE */ 1, '', $token->getLine()), new Token(/* Token::NAME_TYPE */ 5, 'extends', $token->getLine()), $parentToken, new Token(/* Token::BLOCK_END_TYPE */ 3, '', $token->getLine()), ]); $module = $this->parser->parse($stream, [$this, 'decideBlockEnd'], true); // override the parent with the correct one if ($fakeParentToken === $parentToken) { $module->setNode('parent', $parent); } $this->parser->embedTemplate($module); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); return new EmbedNode($module->getTemplateName(), $module->getAttribute('index'), $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag()); } public function decideBlockEnd(Token $token) { return $token->test('endembed'); } public function getTag() { return 'embed'; } } class_alias('Twig\TokenParser\EmbedTokenParser', 'Twig_TokenParser_Embed'); php-twig-2.12.5/src/TokenParser/ExtendsTokenParser.php000066400000000000000000000025751362457344700227150ustar00rootroot00000000000000parser->getStream(); if ($this->parser->peekBlockStack()) { throw new SyntaxError('Cannot use "extend" in a block.', $token->getLine(), $stream->getSourceContext()); } elseif (!$this->parser->isMainScope()) { throw new SyntaxError('Cannot use "extend" in a macro.', $token->getLine(), $stream->getSourceContext()); } if (null !== $this->parser->getParent()) { throw new SyntaxError('Multiple extends tags are forbidden.', $token->getLine(), $stream->getSourceContext()); } $this->parser->setParent($this->parser->getExpressionParser()->parseExpression()); $stream->expect(Token::BLOCK_END_TYPE); return new Node(); } public function getTag() { return 'extends'; } } class_alias('Twig\TokenParser\ExtendsTokenParser', 'Twig_TokenParser_Extends'); php-twig-2.12.5/src/TokenParser/FilterTokenParser.php000066400000000000000000000035541362457344700225260ustar00rootroot00000000000000parser->getStream(); $lineno = $token->getLine(); @trigger_error(sprintf('The "filter" tag in "%s" at line %d is deprecated since Twig 2.9, use the "apply" tag instead.', $stream->getSourceContext()->getName(), $lineno), E_USER_DEPRECATED); $name = $this->parser->getVarName(); $ref = new BlockReferenceExpression(new ConstantExpression($name, $lineno), null, $lineno, $this->getTag()); $filter = $this->parser->getExpressionParser()->parseFilterExpressionRaw($ref, $this->getTag()); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $block = new BlockNode($name, $body, $lineno); $this->parser->setBlock($name, $block); return new PrintNode($filter, $lineno, $this->getTag()); } public function decideBlockEnd(Token $token) { return $token->test('endfilter'); } public function getTag() { return 'filter'; } } class_alias('Twig\TokenParser\FilterTokenParser', 'Twig_TokenParser_Filter'); php-twig-2.12.5/src/TokenParser/FlushTokenParser.php000066400000000000000000000013371362457344700223570ustar00rootroot00000000000000parser->getStream()->expect(/* Token::BLOCK_END_TYPE */ 3); return new FlushNode($token->getLine(), $this->getTag()); } public function getTag() { return 'flush'; } } class_alias('Twig\TokenParser\FlushTokenParser', 'Twig_TokenParser_Flush'); php-twig-2.12.5/src/TokenParser/ForTokenParser.php000066400000000000000000000117171362457344700220270ustar00rootroot00000000000000 * {% for user in users %} *
  • {{ user.username|e }}
  • * {% endfor %} * */ final class ForTokenParser extends AbstractTokenParser { public function parse(Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); $targets = $this->parser->getExpressionParser()->parseAssignmentExpression(); $stream->expect(/* Token::OPERATOR_TYPE */ 8, 'in'); $seq = $this->parser->getExpressionParser()->parseExpression(); $ifexpr = null; if ($stream->nextIf(/* Token::NAME_TYPE */ 5, 'if')) { @trigger_error(sprintf('Using an "if" condition on "for" tag in "%s" at line %d is deprecated since Twig 2.10.0, use a "filter" filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop).', $stream->getSourceContext()->getName(), $lineno), E_USER_DEPRECATED); $ifexpr = $this->parser->getExpressionParser()->parseExpression(); } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideForFork']); if ('else' == $stream->next()->getValue()) { $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $else = $this->parser->subparse([$this, 'decideForEnd'], true); } else { $else = null; } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); if (\count($targets) > 1) { $keyTarget = $targets->getNode(0); $keyTarget = new AssignNameExpression($keyTarget->getAttribute('name'), $keyTarget->getTemplateLine()); $valueTarget = $targets->getNode(1); $valueTarget = new AssignNameExpression($valueTarget->getAttribute('name'), $valueTarget->getTemplateLine()); } else { $keyTarget = new AssignNameExpression('_key', $lineno); $valueTarget = $targets->getNode(0); $valueTarget = new AssignNameExpression($valueTarget->getAttribute('name'), $valueTarget->getTemplateLine()); } if ($ifexpr) { $this->checkLoopUsageCondition($stream, $ifexpr); $this->checkLoopUsageBody($stream, $body); } return new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, $lineno, $this->getTag()); } public function decideForFork(Token $token) { return $token->test(['else', 'endfor']); } public function decideForEnd(Token $token) { return $token->test('endfor'); } // the loop variable cannot be used in the condition private function checkLoopUsageCondition(TokenStream $stream, Node $node) { if ($node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression && 'loop' == $node->getNode('node')->getAttribute('name')) { throw new SyntaxError('The "loop" variable cannot be used in a looping condition.', $node->getTemplateLine(), $stream->getSourceContext()); } foreach ($node as $n) { if (!$n) { continue; } $this->checkLoopUsageCondition($stream, $n); } } // check usage of non-defined loop-items // it does not catch all problems (for instance when a for is included into another or when the variable is used in an include) private function checkLoopUsageBody(TokenStream $stream, Node $node) { if ($node instanceof GetAttrExpression && $node->getNode('node') instanceof NameExpression && 'loop' == $node->getNode('node')->getAttribute('name')) { $attribute = $node->getNode('attribute'); if ($attribute instanceof ConstantExpression && \in_array($attribute->getAttribute('value'), ['length', 'revindex0', 'revindex', 'last'])) { throw new SyntaxError(sprintf('The "loop.%s" variable is not defined when looping with a condition.', $attribute->getAttribute('value')), $node->getTemplateLine(), $stream->getSourceContext()); } } // should check for parent.loop.XXX usage if ($node instanceof ForNode) { return; } foreach ($node as $n) { if (!$n) { continue; } $this->checkLoopUsageBody($stream, $n); } } public function getTag() { return 'for'; } } class_alias('Twig\TokenParser\ForTokenParser', 'Twig_TokenParser_For'); php-twig-2.12.5/src/TokenParser/FromTokenParser.php000066400000000000000000000032521362457344700221770ustar00rootroot00000000000000parser->getExpressionParser()->parseExpression(); $stream = $this->parser->getStream(); $stream->expect(/* Token::NAME_TYPE */ 5, 'import'); $targets = []; do { $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); $alias = $name; if ($stream->nextIf('as')) { $alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); } $targets[$name] = $alias; if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { break; } } while (true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $var = new AssignNameExpression($this->parser->getVarName(), $token->getLine()); $node = new ImportNode($macro, $var, $token->getLine(), $this->getTag(), $this->parser->isMainScope()); foreach ($targets as $name => $alias) { $this->parser->addImportedSymbol('function', $alias, 'macro_'.$name, $var); } return $node; } public function getTag() { return 'from'; } } class_alias('Twig\TokenParser\FromTokenParser', 'Twig_TokenParser_From'); php-twig-2.12.5/src/TokenParser/IfTokenParser.php000066400000000000000000000047441362457344700216410ustar00rootroot00000000000000 * {% for user in users %} *
  • {{ user.username|e }}
  • * {% endfor %} * * {% endif %} */ final class IfTokenParser extends AbstractTokenParser { public function parse(Token $token) { $lineno = $token->getLine(); $expr = $this->parser->getExpressionParser()->parseExpression(); $stream = $this->parser->getStream(); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideIfFork']); $tests = [$expr, $body]; $else = null; $end = false; while (!$end) { switch ($stream->next()->getValue()) { case 'else': $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $else = $this->parser->subparse([$this, 'decideIfEnd']); break; case 'elseif': $expr = $this->parser->getExpressionParser()->parseExpression(); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideIfFork']); $tests[] = $expr; $tests[] = $body; break; case 'endif': $end = true; break; default: throw new SyntaxError(sprintf('Unexpected end of template. Twig was looking for the following tags "else", "elseif", or "endif" to close the "if" block started at line %d).', $lineno), $stream->getCurrent()->getLine(), $stream->getSourceContext()); } } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); return new IfNode(new Node($tests), $else, $lineno, $this->getTag()); } public function decideIfFork(Token $token) { return $token->test(['elseif', 'else', 'endif']); } public function decideIfEnd(Token $token) { return $token->test(['endif']); } public function getTag() { return 'if'; } } class_alias('Twig\TokenParser\IfTokenParser', 'Twig_TokenParser_If'); php-twig-2.12.5/src/TokenParser/ImportTokenParser.php000066400000000000000000000022651362457344700225510ustar00rootroot00000000000000parser->getExpressionParser()->parseExpression(); $this->parser->getStream()->expect(/* Token::NAME_TYPE */ 5, 'as'); $var = new AssignNameExpression($this->parser->getStream()->expect(/* Token::NAME_TYPE */ 5)->getValue(), $token->getLine()); $this->parser->getStream()->expect(/* Token::BLOCK_END_TYPE */ 3); $this->parser->addImportedSymbol('template', $var->getAttribute('name')); return new ImportNode($macro, $var, $token->getLine(), $this->getTag(), $this->parser->isMainScope()); } public function getTag() { return 'import'; } } class_alias('Twig\TokenParser\ImportTokenParser', 'Twig_TokenParser_Import'); php-twig-2.12.5/src/TokenParser/IncludeTokenParser.php000066400000000000000000000031731362457344700226610ustar00rootroot00000000000000parser->getExpressionParser()->parseExpression(); list($variables, $only, $ignoreMissing) = $this->parseArguments(); return new IncludeNode($expr, $variables, $only, $ignoreMissing, $token->getLine(), $this->getTag()); } protected function parseArguments() { $stream = $this->parser->getStream(); $ignoreMissing = false; if ($stream->nextIf(/* Token::NAME_TYPE */ 5, 'ignore')) { $stream->expect(/* Token::NAME_TYPE */ 5, 'missing'); $ignoreMissing = true; } $variables = null; if ($stream->nextIf(/* Token::NAME_TYPE */ 5, 'with')) { $variables = $this->parser->getExpressionParser()->parseExpression(); } $only = false; if ($stream->nextIf(/* Token::NAME_TYPE */ 5, 'only')) { $only = true; } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); return [$variables, $only, $ignoreMissing]; } public function getTag() { return 'include'; } } class_alias('Twig\TokenParser\IncludeTokenParser', 'Twig_TokenParser_Include'); php-twig-2.12.5/src/TokenParser/MacroTokenParser.php000066400000000000000000000036161362457344700223410ustar00rootroot00000000000000 * {% endmacro %} */ final class MacroTokenParser extends AbstractTokenParser { public function parse(Token $token) { $lineno = $token->getLine(); $stream = $this->parser->getStream(); $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); $arguments = $this->parser->getExpressionParser()->parseArguments(true, true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $this->parser->pushLocalScope(); $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); if ($token = $stream->nextIf(/* Token::NAME_TYPE */ 5)) { $value = $token->getValue(); if ($value != $name) { throw new SyntaxError(sprintf('Expected endmacro for macro "%s" (but "%s" given).', $name, $value), $stream->getCurrent()->getLine(), $stream->getSourceContext()); } } $this->parser->popLocalScope(); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $this->parser->setMacro($name, new MacroNode($name, new BodyNode([$body]), $arguments, $lineno, $this->getTag())); return new Node(); } public function decideBlockEnd(Token $token) { return $token->test('endmacro'); } public function getTag() { return 'macro'; } } class_alias('Twig\TokenParser\MacroTokenParser', 'Twig_TokenParser_Macro'); php-twig-2.12.5/src/TokenParser/SandboxTokenParser.php000066400000000000000000000034551362457344700226770ustar00rootroot00000000000000parser->getStream(); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideBlockEnd'], true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); // in a sandbox tag, only include tags are allowed if (!$body instanceof IncludeNode) { foreach ($body as $node) { if ($node instanceof TextNode && ctype_space($node->getAttribute('data'))) { continue; } if (!$node instanceof IncludeNode) { throw new SyntaxError('Only "include" tags are allowed within a "sandbox" section.', $node->getTemplateLine(), $stream->getSourceContext()); } } } return new SandboxNode($body, $token->getLine(), $this->getTag()); } public function decideBlockEnd(Token $token) { return $token->test('endsandbox'); } public function getTag() { return 'sandbox'; } } class_alias('Twig\TokenParser\SandboxTokenParser', 'Twig_TokenParser_Sandbox'); php-twig-2.12.5/src/TokenParser/SetTokenParser.php000066400000000000000000000040701362457344700220260ustar00rootroot00000000000000getLine(); $stream = $this->parser->getStream(); $names = $this->parser->getExpressionParser()->parseAssignmentExpression(); $capture = false; if ($stream->nextIf(/* Token::OPERATOR_TYPE */ 8, '=')) { $values = $this->parser->getExpressionParser()->parseMultitargetExpression(); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); if (\count($names) !== \count($values)) { throw new SyntaxError('When using set, you must have the same number of variables and assignments.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); } } else { $capture = true; if (\count($names) > 1) { throw new SyntaxError('When using set with a block, you cannot have a multi-target.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $values = $this->parser->subparse([$this, 'decideBlockEnd'], true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); } return new SetNode($capture, $names, $values, $lineno, $this->getTag()); } public function decideBlockEnd(Token $token) { return $token->test('endset'); } public function getTag() { return 'set'; } } class_alias('Twig\TokenParser\SetTokenParser', 'Twig_TokenParser_Set'); php-twig-2.12.5/src/TokenParser/SpacelessTokenParser.php000066400000000000000000000030311362457344700232110ustar00rootroot00000000000000 * foo * * {% endspaceless %} * {# output will be
    foo
    #} * * @deprecated since Twig 2.7, to be removed in 3.0 (use the "spaceless" filter with the "apply" tag instead) */ final class SpacelessTokenParser extends AbstractTokenParser { public function parse(Token $token) { $stream = $this->parser->getStream(); $lineno = $token->getLine(); @trigger_error(sprintf('The spaceless tag in "%s" at line %d is deprecated since Twig 2.7, use the "spaceless" filter with the "apply" tag instead.', $stream->getSourceContext()->getName(), $lineno), E_USER_DEPRECATED); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideSpacelessEnd'], true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); return new SpacelessNode($body, $lineno, $this->getTag()); } public function decideSpacelessEnd(Token $token) { return $token->test('endspaceless'); } public function getTag() { return 'spaceless'; } } class_alias('Twig\TokenParser\SpacelessTokenParser', 'Twig_TokenParser_Spaceless'); php-twig-2.12.5/src/TokenParser/TokenParserInterface.php000066400000000000000000000021661362457344700231770ustar00rootroot00000000000000 */ interface TokenParserInterface { /** * Sets the parser associated with this token parser. */ public function setParser(Parser $parser); /** * Parses a token and returns a node. * * @return Node * * @throws SyntaxError */ public function parse(Token $token); /** * Gets the tag name associated with this token parser. * * @return string The tag name */ public function getTag(); } class_alias('Twig\TokenParser\TokenParserInterface', 'Twig_TokenParserInterface'); // Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. class_exists('Twig\Token'); class_exists('Twig\Parser'); php-twig-2.12.5/src/TokenParser/UseTokenParser.php000066400000000000000000000037431362457344700220350ustar00rootroot00000000000000parser->getExpressionParser()->parseExpression(); $stream = $this->parser->getStream(); if (!$template instanceof ConstantExpression) { throw new SyntaxError('The template references in a "use" statement must be a string.', $stream->getCurrent()->getLine(), $stream->getSourceContext()); } $targets = []; if ($stream->nextIf('with')) { do { $name = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); $alias = $name; if ($stream->nextIf('as')) { $alias = $stream->expect(/* Token::NAME_TYPE */ 5)->getValue(); } $targets[$name] = new ConstantExpression($alias, -1); if (!$stream->nextIf(/* Token::PUNCTUATION_TYPE */ 9, ',')) { break; } } while (true); } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $this->parser->addTrait(new Node(['template' => $template, 'targets' => new Node($targets)])); return new Node(); } public function getTag() { return 'use'; } } class_alias('Twig\TokenParser\UseTokenParser', 'Twig_TokenParser_Use'); php-twig-2.12.5/src/TokenParser/WithTokenParser.php000066400000000000000000000024501362457344700222060ustar00rootroot00000000000000 */ final class WithTokenParser extends AbstractTokenParser { public function parse(Token $token) { $stream = $this->parser->getStream(); $variables = null; $only = false; if (!$stream->test(/* Token::BLOCK_END_TYPE */ 3)) { $variables = $this->parser->getExpressionParser()->parseExpression(); $only = (bool) $stream->nextIf(/* Token::NAME_TYPE */ 5, 'only'); } $stream->expect(/* Token::BLOCK_END_TYPE */ 3); $body = $this->parser->subparse([$this, 'decideWithEnd'], true); $stream->expect(/* Token::BLOCK_END_TYPE */ 3); return new WithNode($body, $variables, $only, $token->getLine(), $this->getTag()); } public function decideWithEnd(Token $token) { return $token->test('endwith'); } public function getTag() { return 'with'; } } class_alias('Twig\TokenParser\WithTokenParser', 'Twig_TokenParser_With'); php-twig-2.12.5/src/TokenStream.php000066400000000000000000000070011362457344700171110ustar00rootroot00000000000000 */ final class TokenStream { private $tokens; private $current = 0; private $source; public function __construct(array $tokens, Source $source = null) { $this->tokens = $tokens; $this->source = $source ?: new 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. */ public function next(): Token { if (!isset($this->tokens[++$this->current])) { throw new SyntaxError('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 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. */ public function expect($type, $value = null, string $message = null): Token { $token = $this->tokens[$this->current]; if (!$token->test($type, $value)) { $line = $token->getLine(); throw new SyntaxError(sprintf('%sUnexpected token "%s"%s ("%s" expected%s).', $message ? $message.'. ' : '', Token::typeToEnglish($token->getType()), $token->getValue() ? sprintf(' of value "%s"', $token->getValue()) : '', Token::typeToEnglish($type), $value ? sprintf(' with value "%s"', $value) : ''), $line, $this->source ); } $this->next(); return $token; } /** * Looks at the next token. */ public function look(int $number = 1): Token { if (!isset($this->tokens[$this->current + $number])) { throw new SyntaxError('Unexpected end of template.', $this->tokens[$this->current + $number - 1]->getLine(), $this->source); } return $this->tokens[$this->current + $number]; } /** * Tests the current token. */ public function test($primary, $secondary = null): bool { return $this->tokens[$this->current]->test($primary, $secondary); } /** * Checks if end of stream was reached. */ public function isEOF(): bool { return /* Token::EOF_TYPE */ -1 === $this->tokens[$this->current]->getType(); } public function getCurrent(): Token { return $this->tokens[$this->current]; } /** * Gets the source associated with this stream. * * @internal */ public function getSourceContext(): Source { return $this->source; } } class_alias('Twig\TokenStream', 'Twig_TokenStream'); php-twig-2.12.5/src/TwigFilter.php000066400000000000000000000070471362457344700167470ustar00rootroot00000000000000 * * @see https://twig.symfony.com/doc/templates.html#filters */ class TwigFilter { private $name; private $callable; private $options; private $arguments = []; /** * 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 = []) { if (__CLASS__ !== \get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since Twig 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([ 'needs_environment' => false, 'needs_context' => false, 'is_variadic' => false, 'is_safe' => null, 'is_safe_callback' => null, 'pre_escape' => null, 'preserves_safety' => null, 'node_class' => FilterExpression::class, '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(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\TwigFilter', 'Twig_SimpleFilter', false); class_alias('Twig\TwigFilter', 'Twig_Filter'); // Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. class_exists('Twig\Node\Node'); php-twig-2.12.5/src/TwigFunction.php000066400000000000000000000064701362457344700173060ustar00rootroot00000000000000 * * @see https://twig.symfony.com/doc/templates.html#functions */ class TwigFunction { private $name; private $callable; private $options; private $arguments = []; /** * 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 = []) { if (__CLASS__ !== \get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since Twig 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([ 'needs_environment' => false, 'needs_context' => false, 'is_variadic' => false, 'is_safe' => null, 'is_safe_callback' => null, 'node_class' => FunctionExpression::class, '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(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 []; } 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\TwigFunction', 'Twig_SimpleFunction', false); class_alias('Twig\TwigFunction', 'Twig_Function'); // Ensure that the aliased name is loaded to keep BC for classes implementing the typehint with the old aliased name. class_exists('Twig\Node\Node'); php-twig-2.12.5/src/TwigTest.php000066400000000000000000000047141362457344700164370ustar00rootroot00000000000000 * * @see https://twig.symfony.com/doc/templates.html#test-operator */ class TwigTest { private $name; private $callable; private $options; private $arguments = []; /** * 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 = []) { if (__CLASS__ !== \get_class($this)) { @trigger_error('Overriding '.__CLASS__.' is deprecated since Twig 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([ 'is_variadic' => false, 'node_class' => TestExpression::class, '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 setArguments($arguments) { $this->arguments = $arguments; } public function getArguments() { return $this->arguments; } 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\TwigTest', 'Twig_SimpleTest', false); class_alias('Twig\TwigTest', 'Twig_Test'); php-twig-2.12.5/src/Util/000077500000000000000000000000001362457344700150635ustar00rootroot00000000000000php-twig-2.12.5/src/Util/DeprecationCollector.php000066400000000000000000000040731362457344700217040ustar00rootroot00000000000000 */ final class DeprecationCollector { private $twig; public function __construct(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 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 = []; 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 Source($contents, $name))); } catch (SyntaxError $e) { // ignore templates containing syntax errors } } restore_error_handler(); return $deprecations; } } class_alias('Twig\Util\DeprecationCollector', 'Twig_Util_DeprecationCollector'); php-twig-2.12.5/src/Util/TemplateDirIterator.php000066400000000000000000000011161362457344700215170ustar00rootroot00000000000000 */ class 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'); php-twig-2.12.5/tests/000077500000000000000000000000001362457344700145215ustar00rootroot00000000000000php-twig-2.12.5/tests/Cache/000077500000000000000000000000001362457344700155245ustar00rootroot00000000000000php-twig-2.12.5/tests/Cache/FilesystemTest.php000066400000000000000000000126221362457344700212240ustar00rootroot00000000000000classname = '__Twig_Tests_Cache_FilesystemTest_Template_'.$nonce; $this->directory = sys_get_temp_dir().'/twig-test'; $this->cache = new FilesystemCache($this->directory); } protected function tearDown() { if (file_exists($this->directory)) { FilesystemHelper::removeDir($this->directory); } } public function testLoad() { $key = $this->directory.'/cache/cachefile.php'; $dir = \dirname($key); @mkdir($dir, 0777, true); $this->assertDirectoryExists($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); } public function testWriteFailMkdir() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unable to create the cache directory'); 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->assertDirectoryExists($this->directory); $this->cache->write($key, $content); } public function testWriteFailDirWritable() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Unable to write in the cache directory'); 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->assertDirectoryExists($this->directory.'/cache'); $this->cache->write($key, $content); } public function testWriteFailWriteFile() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('Failed to write cache file'); $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->assertDirectoryExists($key); $this->cache->write($key, $content); } public function testGetTimestamp() { $key = $this->directory.'/cache/cachefile.php'; $dir = \dirname($key); @mkdir($dir, 0777, true); $this->assertDirectoryExists($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 FilesystemCache($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 [ [$pattern, 'a/b'], [$pattern, 'a/b/'], [$pattern, 'a/b\\'], [$pattern, 'a/b\\/'], [$pattern, 'a/b\\//'], ['#/'.substr($pattern, 1), '/a/b'], ]; } private function generateSource() { return strtr(' $this->classname, ]); } } php-twig-2.12.5/tests/CompilerTest.php000066400000000000000000000022551362457344700176500ustar00rootroot00000000000000createMock(LoaderInterface::class))); $locale = setlocale(LC_NUMERIC, 0); if (false === $locale) { $this->markTestSkipped('Your platform does not support locales.'); } $required_locales = ['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->assertStringContainsString('fr', strtolower(setlocale(LC_NUMERIC, 0))); setlocale(LC_NUMERIC, $locale); } } php-twig-2.12.5/tests/ContainerRuntimeLoaderTest.php000066400000000000000000000022471362457344700225140ustar00rootroot00000000000000createMock(ContainerInterface::class); $container->expects($this->once())->method('has')->with('stdClass')->willReturn(true); $container->expects($this->once())->method('get')->with('stdClass')->willReturn(new \stdClass()); $loader = new ContainerRuntimeLoader($container); $this->assertInstanceOf('stdClass', $loader->load('stdClass')); } public function testLoadUnknownRuntimeReturnsNull() { $container = $this->createMock(ContainerInterface::class); $container->expects($this->once())->method('has')->with('Foo'); $container->expects($this->never())->method('get'); $this->assertNull((new ContainerRuntimeLoader($container))->load('Foo')); } } php-twig-2.12.5/tests/CustomExtensionTest.php000066400000000000000000000035221362457344700212430ustar00rootroot00000000000000expectException(\InvalidArgumentException::class); $this->expectExceptionMessage($expectedExceptionMessage); $env = new Environment($this->createMock(LoaderInterface::class)); $env->addExtension($extension); $env->getUnaryOperators(); } public function provideInvalidExtensions() { return [ [new InvalidOperatorExtension(new \stdClass()), '"Twig\Tests\InvalidOperatorExtension::getOperators()" must return an array with operators, got "stdClass".'], [new InvalidOperatorExtension([1, 2, 3]), '"Twig\Tests\InvalidOperatorExtension::getOperators()" must return an array of 2 elements, got 3.'], ]; } } class InvalidOperatorExtension implements ExtensionInterface { private $operators; public function __construct($operators) { $this->operators = $operators; } public function getTokenParsers() { return []; } public function getNodeVisitors() { return []; } public function getFilters() { return []; } public function getTests() { return []; } public function getFunctions() { return []; } public function getOperators() { return $this->operators; } } php-twig-2.12.5/tests/EnvironmentTest.php000066400000000000000000000407661362457344700204130ustar00rootroot00000000000000 '{{ foo }} {{ foo }}', 'js' => '{{ bar }} {{ bar }}', ]); $twig = new Environment($loader, [ 'debug' => true, 'cache' => false, 'autoescape' => [$this, 'escapingStrategyCallback'], ]); $this->assertEquals('foo<br/ > foo<br/ >', $twig->render('html', ['foo' => 'foo
    '])); $this->assertEquals('foo\u003Cbr\/\u0020\u003E foo\u003Cbr\/\u0020\u003E', $twig->render('js', ['bar' => 'foo
    '])); } public function escapingStrategyCallback($name) { return $name; } public function testGlobals() { $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->any())->method('getSourceContext')->willReturn(new Source('', '')); // globals can be added after calling getGlobals $twig = new 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 Environment($loader); $twig->addGlobal('foo', 'foo'); $twig->getGlobals(); $twig->load('index'); $twig->addGlobal('foo', 'bar'); $globals = $twig->getGlobals(); $this->assertEquals('bar', $globals['foo']); // globals can be modified after extensions init $twig = new 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 ArrayLoader(['index' => '{{foo}}']); $twig = new Environment($arrayLoader); $twig->addGlobal('foo', 'foo'); $twig->getGlobals(); $twig->getFunctions(); $twig->load('index'); $twig->addGlobal('foo', 'bar'); $globals = $twig->getGlobals(); $this->assertEquals('bar', $globals['foo']); $twig = new Environment($arrayLoader); $twig->getGlobals(); $twig->addGlobal('foo', 'bar'); $template = $twig->load('index'); $this->assertEquals('bar', $template->render([])); // globals cannot be added after a template has been loaded $twig = new Environment($loader); $twig->addGlobal('foo', 'foo'); $twig->getGlobals(); $twig->load('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 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 Environment($loader); $twig->addGlobal('foo', 'foo'); $twig->getGlobals(); $twig->getFunctions(); $twig->load('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 Environment($loader); $twig->load('index'); try { $twig->addGlobal('bar', 'bar'); $this->fail(); } catch (\LogicException $e) { $this->assertArrayNotHasKey('bar', $twig->getGlobals()); } } public function testExtensionsAreNotInitializedWhenRenderingACompiledTemplate() { $cache = new FilesystemCache($dir = sys_get_temp_dir().'/twig'); $options = ['cache' => $cache, 'auto_reload' => false, 'debug' => false]; // force compilation $twig = new Environment($loader = new ArrayLoader(['index' => '{{ foo }}']), $options); $key = $cache->generateKey('index', $twig->getTemplateClass('index')); $cache->write($key, $twig->compileSource(new Source('{{ foo }}', 'index'))); // check that extensions won't be initialized when rendering a template that is already in the cache $twig = $this ->getMockBuilder(Environment::class) ->setConstructorArgs([$loader, $options]) ->setMethods(['initExtensions']) ->getMock() ; $twig->expects($this->never())->method('initExtensions'); // render template $output = $twig->render('index', ['foo' => 'bar']); $this->assertEquals('bar', $output); FilesystemHelper::removeDir($dir); } public function testAutoReloadCacheMiss() { $templateName = __FUNCTION__; $templateContent = __FUNCTION__; $cache = $this->createMock(CacheInterface::class); $loader = $this->getMockLoader($templateName, $templateContent); $twig = new Environment($loader, ['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') ->willReturn('key'); $cache->expects($this->once()) ->method('getTimestamp') ->willReturn(0); $loader->expects($this->never()) ->method('isFresh'); $cache->expects($this->once()) ->method('write'); $cache->expects($this->once()) ->method('load'); $twig->load($templateName); } public function testAutoReloadCacheHit() { $templateName = __FUNCTION__; $templateContent = __FUNCTION__; $cache = $this->createMock(CacheInterface::class); $loader = $this->getMockLoader($templateName, $templateContent); $twig = new Environment($loader, ['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') ->willReturn('key'); $cache->expects($this->once()) ->method('getTimestamp') ->willReturn($now); $loader->expects($this->once()) ->method('isFresh') ->willReturn(true); $cache->expects($this->atLeastOnce()) ->method('load'); $twig->load($templateName); } public function testAutoReloadOutdatedCacheHit() { $templateName = __FUNCTION__; $templateContent = __FUNCTION__; $cache = $this->createMock(CacheInterface::class); $loader = $this->getMockLoader($templateName, $templateContent); $twig = new Environment($loader, ['cache' => $cache, 'auto_reload' => true, 'debug' => false]); $now = time(); $cache->expects($this->once()) ->method('generateKey') ->willReturn('key'); $cache->expects($this->once()) ->method('getTimestamp') ->willReturn($now); $loader->expects($this->once()) ->method('isFresh') ->willReturn(false); $cache->expects($this->once()) ->method('write'); $cache->expects($this->once()) ->method('load'); $twig->load($templateName); } public function testHasGetExtensionByClassName() { $twig = new Environment($this->createMock(LoaderInterface::class)); $twig->addExtension($ext = new 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 Environment($this->createMock(LoaderInterface::class)); $twig->addExtension(new 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 EnvironmentTest_NodeVisitor) { $found = true; } } $this->assertTrue($found); } public function testAddMockExtension() { $extension = $this->createMock(ExtensionInterface::class); $loader = new ArrayLoader(['page' => 'hey']); $twig = new Environment($loader); $twig->addExtension($extension); $this->assertInstanceOf(ExtensionInterface::class, $twig->getExtension(\get_class($extension))); $this->assertTrue($twig->isTemplateFresh('page', time())); } /** * @group legacy */ public function testInitRuntimeWithAnExtensionUsingInitRuntimeNoDeprecation() { $loader = $this->createMock(LoaderInterface::class); $twig = new Environment($loader); $loader->expects($this->once())->method('getSourceContext')->willReturn(new Source('', '')); $twig->addExtension(new EnvironmentTest_ExtensionWithoutDeprecationInitRuntime()); $twig->load(''); // 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); } public function testOverrideExtension() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('Unable to register extension "Twig\Tests\EnvironmentTest_Extension" as it is already registered.'); $twig = new Environment($this->createMock(LoaderInterface::class)); $twig->addExtension(new EnvironmentTest_Extension()); $twig->addExtension(new EnvironmentTest_Extension()); } public function testAddRuntimeLoader() { $runtimeLoader = $this->createMock(RuntimeLoaderInterface::class); $runtimeLoader->expects($this->any())->method('load')->willReturn(new EnvironmentTest_Runtime()); $loader = new ArrayLoader([ '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 Environment($loader); $twig->addExtension(new 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')); } public function testFailLoadTemplate() { $this->expectException(RuntimeError::class); $this->expectExceptionMessage('Failed to load Twig template "testFailLoadTemplate.twig", index "112233": cache might be corrupted in "testFailLoadTemplate.twig".'); $template = 'testFailLoadTemplate.twig'; $twig = new Environment(new ArrayLoader([$template => false])); $twig->loadTemplate($template, 112233); } protected function getMockLoader($templateName, $templateContent) { $loader = $this->createMock(LoaderInterface::class); $loader->expects($this->any()) ->method('getSourceContext') ->with($templateName) ->willReturn(new Source($templateContent, $templateName)); $loader->expects($this->any()) ->method('getCacheKey') ->with($templateName) ->willReturn($templateName); return $loader; } } class EnvironmentTest_Extension_WithGlobals extends AbstractExtension { public function getGlobals() { return [ 'foo_global' => 'foo_global', ]; } } class EnvironmentTest_Extension extends AbstractExtension implements GlobalsInterface { public function getTokenParsers() { return [ new EnvironmentTest_TokenParser(), ]; } public function getNodeVisitors() { return [ new EnvironmentTest_NodeVisitor(), ]; } public function getFilters() { return [ new TwigFilter('foo_filter'), ]; } public function getTests() { return [ new TwigTest('foo_test'), ]; } public function getFunctions() { return [ new TwigFunction('foo_function'), ]; } public function getOperators() { return [ ['foo_unary' => []], ['foo_binary' => []], ]; } public function getGlobals() { return [ 'foo_global' => 'foo_global', ]; } } class_alias('\Twig\Tests\EnvironmentTest_Extension', 'Twig\Tests\EnvironmentTest\Extension', false); class EnvironmentTest_TokenParser extends AbstractTokenParser { public function parse(Token $token) { } public function getTag() { return 'test'; } } class EnvironmentTest_NodeVisitor implements NodeVisitorInterface { public function enterNode(Node $node, Environment $env) { return $node; } public function leaveNode(Node $node, Environment $env) { return $node; } public function getPriority() { return 0; } } class EnvironmentTest_ExtensionWithDeprecationInitRuntime extends AbstractExtension { public function initRuntime(Environment $env) { } } class EnvironmentTest_ExtensionWithoutDeprecationInitRuntime extends AbstractExtension implements InitRuntimeInterface { public function initRuntime(Environment $env) { } } class EnvironmentTest_ExtensionWithoutRuntime extends AbstractExtension { public function getFunctions() { return [ new TwigFunction('from_runtime_array', ['Twig\Tests\EnvironmentTest_Runtime', 'fromRuntime']), new TwigFunction('from_runtime_string', 'Twig\Tests\EnvironmentTest_Runtime::fromRuntime'), ]; } } class EnvironmentTest_Runtime { public function fromRuntime($name = 'bar') { return $name; } } php-twig-2.12.5/tests/ErrorTest.php000066400000000000000000000166561362457344700172010ustar00rootroot00000000000000setSourceContext(new Source('', new \SplFileInfo(__FILE__))); $this->assertStringContainsString('tests'.\DIRECTORY_SEPARATOR.'ErrorTest.php', $error->getMessage()); } public function testTwigExceptionGuessWithMissingVarAndArrayLoader() { $loader = new ArrayLoader([ 'base.html' => '{% block content %}{% endblock %}', 'index.html' => << true, 'debug' => true, 'cache' => false]); $template = $twig->load('index.html'); try { $template->render([]); $this->fail(); } catch (RuntimeError $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 ArrayLoader([ 'base.html' => '{% block content %}{% endblock %}', 'index.html' => << true, 'debug' => true, 'cache' => false]); $template = $twig->load('index.html'); try { $template->render(['foo' => new ErrorTest_Foo()]); $this->fail(); } catch (RuntimeError $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 FilesystemLoader(__DIR__.'/Fixtures/errors'); $twig = new Environment($loader, ['strict_variables' => true, 'debug' => true, 'cache' => false]); $template = $twig->load('index.html'); try { $template->render([]); $this->fail(); } catch (RuntimeError $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 FilesystemLoader(__DIR__.'/Fixtures/errors'); $twig = new Environment($loader, ['strict_variables' => true, 'debug' => true, 'cache' => false]); $template = $twig->load('index.html'); try { $template->render(['foo' => new ErrorTest_Foo()]); $this->fail(); } catch (RuntimeError $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 ArrayLoader($templates); $twig = new Environment($loader, ['strict_variables' => true, 'debug' => true, 'cache' => false]); $template = $twig->load('index'); try { $template->render([]); $this->fail(); } catch (RuntimeError $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(['foo' => new ErrorTest_Foo()]); $this->fail(); } catch (RuntimeError $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 [ // error occurs in a template [ [ 'index' => "\n\n{{ foo.bar }}\n\n\n{{ 'foo' }}", ], 'index', 3, ], // error occurs in an included template [ [ 'index' => "{% include 'partial' %}", 'partial' => '{{ foo.bar }}', ], 'partial', 1, ], // error occurs in a parent block when called via parent() [ [ 'index' => "{% extends 'base' %} {% block content %} {{ parent() }} {% endblock %}", 'base' => '{% block content %}{{ foo.bar }}{% endblock %}', ], 'base', 1, ], // error occurs in a block from the child [ [ 'index' => "{% extends 'base' %} {% block content %} {{ foo.bar }} {% endblock %} {% block foo %} {{ foo.bar }} {% endblock %}", 'base' => '{% block content %}{% endblock %}', ], 'index', 3, ], ]; } public function testTwigLeakOutputInDebugMode() { $output = exec(sprintf('%s %s debug', \PHP_BINARY, escapeshellarg(__DIR__.'/Fixtures/errors/leak-output.php'))); $this->assertSame('Hello OOPS', $output); } public function testDoesNotTwigLeakOutput() { $output = exec(sprintf('%s %s', \PHP_BINARY, escapeshellarg(__DIR__.'/Fixtures/errors/leak-output.php'))); $this->assertSame('', $output); } } class ErrorTest_Foo { public function bar() { throw new \Exception('Runtime error...'); } } php-twig-2.12.5/tests/ExpressionParserTest.php000066400000000000000000000330131362457344700214060ustar00rootroot00000000000000expectException(SyntaxError::class); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source($template, 'index'))); } public function getFailingTestsForAssignment() { return [ ['{% set false = "foo" %}'], ['{% set FALSE = "foo" %}'], ['{% set true = "foo" %}'], ['{% set TRUE = "foo" %}'], ['{% set none = "foo" %}'], ['{% set NONE = "foo" %}'], ['{% set null = "foo" %}'], ['{% set NULL = "foo" %}'], ['{% set 3 = "foo" %}'], ['{% set 1 + 2 = "foo" %}'], ['{% set "bar" = "foo" %}'], ['{% set %}{% endset %}'], ]; } /** * @dataProvider getTestsForArray */ public function testArrayExpression($template, $expected) { $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $stream = $env->tokenize($source = new Source($template, '')); $parser = new Parser($env); $expected->setSourceContext($source); $this->assertEquals($expected, $parser->parse($stream)->getNode('body')->getNode(0)->getNode('expr')); } /** * @dataProvider getFailingTestsForArray */ public function testArraySyntaxError($template) { $this->expectException(SyntaxError::class); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source($template, 'index'))); } public function getFailingTestsForArray() { return [ ['{{ [1, "a": "b"] }}'], ['{{ {"a": "b", 2} }}'], ]; } public function getTestsForArray() { return [ // simple array ['{{ [1, 2] }}', new ArrayExpression([ new ConstantExpression(0, 1), new ConstantExpression(1, 1), new ConstantExpression(1, 1), new ConstantExpression(2, 1), ], 1), ], // array with trailing , ['{{ [1, 2, ] }}', new ArrayExpression([ new ConstantExpression(0, 1), new ConstantExpression(1, 1), new ConstantExpression(1, 1), new ConstantExpression(2, 1), ], 1), ], // simple hash ['{{ {"a": "b", "b": "c"} }}', new ArrayExpression([ new ConstantExpression('a', 1), new ConstantExpression('b', 1), new ConstantExpression('b', 1), new ConstantExpression('c', 1), ], 1), ], // hash with trailing , ['{{ {"a": "b", "b": "c", } }}', new ArrayExpression([ new ConstantExpression('a', 1), new ConstantExpression('b', 1), new ConstantExpression('b', 1), new ConstantExpression('c', 1), ], 1), ], // hash in an array ['{{ [1, {"a": "b", "b": "c"}] }}', new ArrayExpression([ new ConstantExpression(0, 1), new ConstantExpression(1, 1), new ConstantExpression(1, 1), new ArrayExpression([ new ConstantExpression('a', 1), new ConstantExpression('b', 1), new ConstantExpression('b', 1), new ConstantExpression('c', 1), ], 1), ], 1), ], // array in a hash ['{{ {"a": [1, 2], "b": "c"} }}', new ArrayExpression([ new ConstantExpression('a', 1), new ArrayExpression([ new ConstantExpression(0, 1), new ConstantExpression(1, 1), new ConstantExpression(1, 1), new ConstantExpression(2, 1), ], 1), new ConstantExpression('b', 1), new ConstantExpression('c', 1), ], 1), ], ]; } public function testStringExpressionDoesNotConcatenateTwoConsecutiveStrings() { $this->expectException(SyntaxError::class); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); $stream = $env->tokenize(new Source('{{ "a" "b" }}', 'index')); $parser = new Parser($env); $parser->parse($stream); } /** * @dataProvider getTestsForString */ public function testStringExpression($template, $expected) { $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false, 'optimizations' => 0]); $stream = $env->tokenize($source = new Source($template, '')); $parser = new Parser($env); $expected->setSourceContext($source); $this->assertEquals($expected, $parser->parse($stream)->getNode('body')->getNode(0)->getNode('expr')); } public function getTestsForString() { return [ [ '{{ "foo" }}', new ConstantExpression('foo', 1), ], [ '{{ "foo #{bar}" }}', new ConcatBinary( new ConstantExpression('foo ', 1), new NameExpression('bar', 1), 1 ), ], [ '{{ "foo #{bar} baz" }}', new ConcatBinary( new ConcatBinary( new ConstantExpression('foo ', 1), new NameExpression('bar', 1), 1 ), new ConstantExpression(' baz', 1), 1 ), ], [ '{{ "foo #{"foo #{bar} baz"} baz" }}', new ConcatBinary( new ConcatBinary( new ConstantExpression('foo ', 1), new ConcatBinary( new ConcatBinary( new ConstantExpression('foo ', 1), new NameExpression('bar', 1), 1 ), new ConstantExpression(' baz', 1), 1 ), 1 ), new ConstantExpression(' baz', 1), 1 ), ], ]; } public function testAttributeCallDoesNotSupportNamedArguments() { $this->expectException(SyntaxError::class); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{{ foo.bar(name="Foo") }}', 'index'))); } public function testMacroCallDoesNotSupportNamedArguments() { $this->expectException(SyntaxError::class); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{% from _self import foo %}{% macro foo() %}{% endmacro %}{{ foo(name="Foo") }}', 'index'))); } public function testMacroDefinitionDoesNotSupportNonNameVariableName() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('An argument must be a name. Unexpected token "string" of value "a" ("name" expected) in "index" at line 1.'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{% macro foo("a") %}{% endmacro %}', 'index'))); } /** * @dataProvider getMacroDefinitionDoesNotSupportNonConstantDefaultValues */ public function testMacroDefinitionDoesNotSupportNonConstantDefaultValues($template) { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('A default value for an argument must be a constant (a boolean, a string, a number, or an array) in "index" at line 1'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source($template, 'index'))); } public function getMacroDefinitionDoesNotSupportNonConstantDefaultValues() { return [ ['{% macro foo(name = "a #{foo} a") %}{% endmacro %}'], ['{% macro foo(name = [["b", "a #{foo} a"]]) %}{% endmacro %}'], ]; } /** * @dataProvider getMacroDefinitionSupportsConstantDefaultValues */ public function testMacroDefinitionSupportsConstantDefaultValues($template) { $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new 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 [ ['{% macro foo(name = "aa") %}{% endmacro %}'], ['{% macro foo(name = 12) %}{% endmacro %}'], ['{% macro foo(name = true) %}{% endmacro %}'], ['{% macro foo(name = ["a"]) %}{% endmacro %}'], ['{% macro foo(name = [["a"]]) %}{% endmacro %}'], ['{% macro foo(name = {a: "a"}) %}{% endmacro %}'], ['{% macro foo(name = {a: {b: "a"}}) %}{% endmacro %}'], ]; } public function testUnknownFunction() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "cycl" function. Did you mean "cycle" in "index" at line 1?'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{{ cycl() }}', 'index'))); } public function testUnknownFunctionWithoutSuggestions() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "foobar" function in "index" at line 1.'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{{ foobar() }}', 'index'))); } public function testUnknownFilter() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "lowe" filter. Did you mean "lower" in "index" at line 1?'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{{ 1|lowe }}', 'index'))); } public function testUnknownFilterWithoutSuggestions() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "foobar" filter in "index" at line 1.'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{{ 1|foobar }}', 'index'))); } public function testUnknownTest() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "nul" test. Did you mean "null" in "index" at line 1'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $stream = $env->tokenize(new Source('{{ 1 is nul }}', 'index')); $parser->parse($stream); } public function testUnknownTestWithoutSuggestions() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "foobar" test in "index" at line 1.'); $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $parser = new Parser($env); $parser->parse($env->tokenize(new Source('{{ 1 is foobar }}', 'index'))); } } php-twig-2.12.5/tests/Extension/000077500000000000000000000000001362457344700164755ustar00rootroot00000000000000php-twig-2.12.5/tests/Extension/CoreTest.php000066400000000000000000000234241362457344700207430ustar00rootroot00000000000000createMock(LoaderInterface::class)); for ($i = 0; $i < 100; ++$i) { $this->assertTrue(\in_array(twig_random($env, $value1, $value2), $expectedInArray, true)); // assertContains() would not consider the type } } public function getRandomFunctionTestData() { return [ 'array' => [ ['apple', 'orange', 'citrus'], ['apple', 'orange', 'citrus'], ], 'Traversable' => [ ['apple', 'orange', 'citrus'], new \ArrayObject(['apple', 'orange', 'citrus']), ], 'unicode string' => [ ['Ä', '€', 'é'], 'Ä€é', ], 'numeric but string' => [ ['1', '2', '3'], '123', ], 'integer' => [ range(0, 5, 1), 5, ], 'float' => [ range(0, 5, 1), 5.9, ], 'negative' => [ [0, -1, -2], -2, ], 'min max int' => [ range(50, 100), 50, 100, ], 'min max float' => [ range(-10, 10), -9.5, 9.5, ], 'min null' => [ range(0, 100), null, 100, ], ]; } public function testRandomFunctionWithoutParameter() { $max = mt_getrandmax(); for ($i = 0; $i < 100; ++$i) { $val = twig_random(new Environment($this->createMock(LoaderInterface::class))); $this->assertTrue(\is_int($val) && $val >= 0 && $val <= $max); } } public function testRandomFunctionReturnsAsIs() { $this->assertSame('', twig_random(new Environment($this->createMock(LoaderInterface::class)), '')); $this->assertSame('', twig_random(new Environment($this->createMock(LoaderInterface::class), ['charset' => null]), '')); $instance = new \stdClass(); $this->assertSame($instance, twig_random(new Environment($this->createMock(LoaderInterface::class)), $instance)); } public function testRandomFunctionOfEmptyArrayThrowsException() { $this->expectException(RuntimeError::class); twig_random(new Environment($this->createMock(LoaderInterface::class)), []); } public function testRandomFunctionOnNonUTF8String() { $twig = new Environment($this->createMock(LoaderInterface::class)); $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), ['Ä', 'é'], true)); } } public function testReverseFilterOnNonUTF8String() { $twig = new Environment($this->createMock(LoaderInterface::class)); $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 provideTwigFirstCases */ public function testTwigFirst($expected, $input) { $twig = new Environment($this->createMock(LoaderInterface::class)); $this->assertSame($expected, twig_first($twig, $input)); } public function provideTwigFirstCases() { $i = [1 => 'a', 2 => 'b', 3 => 'c']; return [ ['a', 'abc'], [1, [1, 2, 3]], ['', null], ['', ''], ['a', new CoreTestIterator($i, array_keys($i), true, 3)], ]; } /** * @dataProvider provideTwigLastCases */ public function testTwigLast($expected, $input) { $twig = new Environment($this->createMock(LoaderInterface::class)); $this->assertSame($expected, twig_last($twig, $input)); } public function provideTwigLastCases() { $i = [1 => 'a', 2 => 'b', 3 => 'c']; return [ ['c', 'abc'], [3, [1, 2, 3]], ['', null], ['', ''], ['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 = ['a' => 'a1', 'b' => 'b1', 'c' => 'c1']; $keys = array_keys($array); return [ [$keys, $array], [$keys, new CoreTestIterator($array, $keys)], [$keys, new CoreTestIteratorAggregate($array, $keys)], [$keys, new CoreTestIteratorAggregateAggregate($array, $keys)], [[], null], [['a'], new \SimpleXMLElement('')], ]; } /** * @dataProvider provideInFilterCases */ public function testInFilter($expected, $value, $compare) { $this->assertSame($expected, twig_in_filter($value, $compare)); } public function provideInFilterCases() { $array = [1, 2, 'a' => 3, 5, 6, 7]; $keys = array_keys($array); return [ [true, 1, $array], [true, '3', $array], [true, '3', 'abc3def'], [true, 1, new CoreTestIterator($array, $keys, true, 1)], [true, '3', new CoreTestIterator($array, $keys, true, 3)], [true, '3', new CoreTestIteratorAggregateAggregate($array, $keys, true, 3)], [false, 4, $array], [false, 4, new CoreTestIterator($array, $keys, true)], [false, 4, new CoreTestIteratorAggregateAggregate($array, $keys, true)], [false, 1, 1], [true, 'b', new \SimpleXMLElement('b')], ]; } /** * @dataProvider provideSliceFilterCases */ public function testSliceFilter($expected, $input, $start, $length = null, $preserveKeys = false) { $twig = new Environment($this->createMock(LoaderInterface::class)); $this->assertSame($expected, twig_slice($twig, $input, $start, $length, $preserveKeys)); } public function provideSliceFilterCases() { $i = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; $keys = array_keys($i); return [ [['a' => 1], $i, 0, 1, true], [['a' => 1], $i, 0, 1, false], [['b' => 2, 'c' => 3], $i, 1, 2], [[1], [1, 2, 3, 4], 0, 1], [[2, 3], [1, 2, 3, 4], 1, 2], [[2, 3], new CoreTestIterator($i, $keys, true), 1, 2], [['c' => 3, 'd' => 4], new CoreTestIteratorAggregate($i, $keys, true), 2, null, true], [$i, new CoreTestIterator($i, $keys, true), 0, \count($keys) + 10, true], [[], new CoreTestIterator($i, $keys, true), \count($keys) + 10], ['de', 'abcdef', 3, 2], [[], new \SimpleXMLElement('12'), 3], [[], new \ArrayIterator([1, 2]), 3], ]; } } 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]); } } php-twig-2.12.5/tests/Extension/EscaperTest.php000066400000000000000000000323501362457344700214330ustar00rootroot00000000000000 ''', '"' => '"', '<' => '<', '>' => '>', '&' => '&', ]; protected $htmlAttrSpecialChars = [ '\'' => ''', /* 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 = [ /* HTML special chars - escape without exception to hex */ '<' => '\\u003C', '>' => '\\u003E', '\'' => '\\u0027', '"' => '\\u0022', '&' => '\\u0026', '/' => '\\/', /* Characters beyond ASCII value 255 to unicode escape */ 'Ā' => '\\u0100', '😀' => '\\uD83D\\uDE00', /* Immune chars excluded */ ',' => ',', '.' => '.', '_' => '_', /* Basic alnums excluded */ 'a' => 'a', 'A' => 'A', 'z' => 'z', 'Z' => 'Z', '0' => '0', '9' => '9', /* Basic control characters and null */ "\r" => '\r', "\n" => '\n', "\x08" => '\b', "\t" => '\t', "\x0C" => '\f', "\0" => '\\u0000', /* Encode spaces for quoteless attribute protection */ ' ' => '\\u0020', ]; protected $urlSpecialChars = [ /* 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 = [ /* 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 ', ]; public function testHtmlEscapingConvertsSpecialChars() { $twig = new Environment($this->createMock(LoaderInterface::class)); foreach ($this->htmlSpecialChars as $key => $value) { $this->assertEquals($value, twig_escape_filter($twig, $key, 'html'), 'Failed to escape: '.$key); } } public function testHtmlAttributeEscapingConvertsSpecialChars() { $twig = new Environment($this->createMock(LoaderInterface::class)); foreach ($this->htmlAttrSpecialChars as $key => $value) { $this->assertEquals($value, twig_escape_filter($twig, $key, 'html_attr'), 'Failed to escape: '.$key); } } public function testJavascriptEscapingConvertsSpecialChars() { $twig = new Environment($this->createMock(LoaderInterface::class)); foreach ($this->jsSpecialChars as $key => $value) { $this->assertEquals($value, twig_escape_filter($twig, $key, 'js'), 'Failed to escape: '.$key); } } public function testJavascriptEscapingReturnsStringIfZeroLength() { $twig = new Environment($this->createMock(LoaderInterface::class)); $this->assertEquals('', twig_escape_filter($twig, '', 'js')); } public function testJavascriptEscapingReturnsStringIfContainsOnlyDigits() { $twig = new Environment($this->createMock(LoaderInterface::class)); $this->assertEquals('123', twig_escape_filter($twig, '123', 'js')); } public function testCssEscapingConvertsSpecialChars() { $twig = new Environment($this->createMock(LoaderInterface::class)); foreach ($this->cssSpecialChars as $key => $value) { $this->assertEquals($value, twig_escape_filter($twig, $key, 'css'), 'Failed to escape: '.$key); } } public function testCssEscapingReturnsStringIfZeroLength() { $twig = new Environment($this->createMock(LoaderInterface::class)); $this->assertEquals('', twig_escape_filter($twig, '', 'css')); } public function testCssEscapingReturnsStringIfContainsOnlyDigits() { $twig = new Environment($this->createMock(LoaderInterface::class)); $this->assertEquals('123', twig_escape_filter($twig, '123', 'css')); } public function testUrlEscapingConvertsSpecialChars() { $twig = new Environment($this->createMock(LoaderInterface::class)); foreach ($this->urlSpecialChars as $key => $value) { $this->assertEquals($value, twig_escape_filter($twig, $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 = [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() { $twig = new Environment($this->createMock(LoaderInterface::class)); $immune = [',', '.', '_']; // 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($twig, $literal, 'js')); } else { $literal = $this->codepointToUtf8($chr); if (\in_array($literal, $immune)) { $this->assertEquals($literal, twig_escape_filter($twig, $literal, 'js')); } else { $this->assertNotEquals( $literal, twig_escape_filter($twig, $literal, 'js'), "$literal should be escaped!"); } } } } public function testHtmlAttributeEscapingEscapesOwaspRecommendedRanges() { $twig = new Environment($this->createMock(LoaderInterface::class)); $immune = [',', '.', '-', '_']; // 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($twig, $literal, 'html_attr')); } else { $literal = $this->codepointToUtf8($chr); if (\in_array($literal, $immune)) { $this->assertEquals($literal, twig_escape_filter($twig, $literal, 'html_attr')); } else { $this->assertNotEquals( $literal, twig_escape_filter($twig, $literal, 'html_attr'), "$literal should be escaped!"); } } } } public function testCssEscapingEscapesOwaspRecommendedRanges() { $twig = new Environment($this->createMock(LoaderInterface::class)); // 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($twig, $literal, 'css')); } else { $literal = $this->codepointToUtf8($chr); $this->assertNotEquals( $literal, twig_escape_filter($twig, $literal, 'css'), "$literal should be escaped!"); } } } /** * @dataProvider provideCustomEscaperCases */ public function testCustomEscaper($expected, $string, $strategy) { $twig = new Environment($this->createMock(LoaderInterface::class)); $twig->getExtension(EscaperExtension::class)->setEscaper('foo', 'Twig\Tests\foo_escaper_for_test'); $this->assertSame($expected, twig_escape_filter($twig, $string, $strategy)); } public function provideCustomEscaperCases() { return [ ['fooUTF-8', 'foo', 'foo'], ['UTF-8', null, 'foo'], ['42UTF-8', 42, 'foo'], ]; } public function testUnknownCustomEscaper() { $this->expectException(RuntimeError::class); twig_escape_filter(new Environment($this->createMock(LoaderInterface::class)), 'foo', 'bar'); } /** * @dataProvider provideObjectsForEscaping */ public function testObjectEscaping(string $escapedHtml, string $escapedJs, array $safeClasses) { $obj = new Extension_TestClass(); $twig = new Environment($this->createMock(LoaderInterface::class)); $twig->getExtension('\Twig\Extension\EscaperExtension')->setSafeClasses($safeClasses); $this->assertSame($escapedHtml, twig_escape_filter($twig, $obj, 'html', null, true)); $this->assertSame($escapedJs, twig_escape_filter($twig, $obj, 'js', null, true)); } public function provideObjectsForEscaping() { return [ ['<br />', '
    ', ['\Twig\Tests\Extension_TestClass' => ['js']]], ['
    ', '\u003Cbr\u0020\/\u003E', ['\Twig\Tests\Extension_TestClass' => ['html']]], ['<br />', '
    ', ['\Twig\Tests\Extension_SafeHtmlInterface' => ['js']]], ['
    ', '
    ', ['\Twig\Tests\Extension_SafeHtmlInterface' => ['all']]], ]; } } function foo_escaper_for_test(Environment $twig, $string, $charset) { return $string.$charset; } interface Extension_SafeHtmlInterface { } class Extension_TestClass implements Extension_SafeHtmlInterface { public function __toString() { return '
    '; } } php-twig-2.12.5/tests/Extension/SandboxTest.php000066400000000000000000000375241362457344700214570ustar00rootroot00000000000000 'Fabien', 'obj' => new FooObject(), 'arr' => ['obj' => new FooObject()], ]; self::$templates = [ '1_basic1' => '{{ obj.foo }}', '1_basic2' => '{{ name|upper }}', '1_basic3' => '{% if name %}foo{% endif %}', '1_basic4' => '{{ obj.bar }}', '1_basic5' => '{{ obj }}', '1_basic7' => '{{ cycle(["foo","bar"], 1) }}', '1_basic8' => '{{ obj.getfoobar }}{{ obj.getFooBar }}', '1_basic9' => '{{ obj.foobar }}{{ obj.fooBar }}', '1_basic' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}', '1_layout' => '{% block content %}{% endblock %}', '1_child' => "{% extends \"1_layout\" %}\n{% block content %}\n{{ \"a\"|json_encode }}\n{% endblock %}", '1_include' => '{{ include("1_basic1", sandboxed=true) }}', '1_range_operator' => '{{ (1..2)[0] }}', ]; } public function testSandboxWithInheritance() { $this->expectException(SecurityError::class); $this->expectExceptionMessage('Filter "json_encode" is not allowed in "1_child" at line 3.'); $twig = $this->getEnvironment(true, [], self::$templates, ['block']); $twig->load('1_child')->render([]); } public function testSandboxGloballySet() { $twig = $this->getEnvironment(false, [], self::$templates); $this->assertEquals('FOO', $twig->load('1_basic')->render(self::$params), 'Sandbox does nothing if it is disabled globally'); } public function testSandboxUnallowedMethodAccessor() { $twig = $this->getEnvironment(true, [], self::$templates); try { $twig->load('1_basic1')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception if an unallowed method is called'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedMethodError::class, $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedMethodError'); $this->assertEquals('Twig\Tests\Extension\FooObject', $e->getClassName(), 'Exception should be raised on the "Twig\Tests\Extension\FooObject" class'); $this->assertEquals('foo', $e->getMethodName(), 'Exception should be raised on the "foo" method'); } } public function testSandboxUnallowedFilter() { $twig = $this->getEnvironment(true, [], self::$templates); try { $twig->load('1_basic2')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception if an unallowed filter is called'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedFilterError::class, $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, [], self::$templates); try { $twig->load('1_basic3')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception if an unallowed tag is used in the template'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedTagError::class, $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, [], self::$templates); try { $twig->load('1_basic4')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception if an unallowed property is called in the template'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedPropertyError::class, $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedPropertyError'); $this->assertEquals('Twig\Tests\Extension\FooObject', $e->getClassName(), 'Exception should be raised on the "Twig\Tests\Extension\FooObject" class'); $this->assertEquals('bar', $e->getPropertyName(), 'Exception should be raised on the "bar" property'); } } /** * @dataProvider getSandboxUnallowedToStringTests */ public function testSandboxUnallowedToString($template) { $twig = $this->getEnvironment(true, [], ['index' => $template], [], ['upper'], ['Twig\Tests\Extension\FooObject' => 'getAnotherFooObject'], [], ['random']); try { $twig->load('index')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception if an unallowed method (__toString()) is called in the template'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedMethodError::class, $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedMethodError'); $this->assertEquals('Twig\Tests\Extension\FooObject', $e->getClassName(), 'Exception should be raised on the "Twig\Tests\Extension\FooObject" class'); $this->assertEquals('__tostring', $e->getMethodName(), 'Exception should be raised on the "__toString" method'); } } public function getSandboxUnallowedToStringTests() { return [ 'simple' => ['{{ obj }}'], 'object_from_array' => ['{{ arr.obj }}'], 'object_chain' => ['{{ obj.anotherFooObject }}'], 'filter' => ['{{ obj|upper }}'], 'filter_from_array' => ['{{ arr.obj|upper }}'], 'function' => ['{{ random(obj) }}'], 'function_from_array' => ['{{ random(arr.obj) }}'], 'function_and_filter' => ['{{ random(obj|upper) }}'], 'function_and_filter_from_array' => ['{{ random(arr.obj|upper) }}'], 'object_chain_and_filter' => ['{{ obj.anotherFooObject|upper }}'], 'object_chain_and_function' => ['{{ random(obj.anotherFooObject) }}'], 'concat' => ['{{ obj ~ "" }}'], 'concat_again' => ['{{ "" ~ obj }}'], ]; } /** * @dataProvider getSandboxAllowedToStringTests */ public function testSandboxAllowedToString($template, $output) { $twig = $this->getEnvironment(true, [], ['index' => $template], ['set'], [], ['Twig\Tests\Extension\FooObject' => ['foo', 'getAnotherFooObject']]); $this->assertEquals($output, $twig->load('index')->render(self::$params)); } public function getSandboxAllowedToStringTests() { return [ 'constant_test' => ['{{ obj is constant("PHP_INT_MAX") }}', ''], 'set_object' => ['{% set a = obj.anotherFooObject %}{{ a.foo }}', 'foo'], 'is_defined' => ['{{ obj.anotherFooObject is defined }}', '1'], 'is_null' => ['{{ obj is null }}', ''], 'is_sameas' => ['{{ obj is same as(obj) }}', '1'], 'is_sameas_from_array' => ['{{ arr.obj is same as(arr.obj) }}', '1'], 'is_sameas_from_another_method' => ['{{ obj.anotherFooObject is same as(obj.anotherFooObject) }}', ''], ]; } public function testSandboxAllowMethodToString() { $twig = $this->getEnvironment(true, [], self::$templates, [], [], ['Twig\Tests\Extension\FooObject' => '__toString']); FooObject::reset(); $this->assertEquals('foo', $twig->load('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, [], self::$templates); FooObject::reset(); $this->assertEquals('foo', $twig->load('1_basic5')->render(self::$params), 'Sandbox allows __toString when sandbox disabled'); $this->assertEquals(1, FooObject::$called['__toString'], 'Sandbox only calls method once'); } public function testSandboxUnallowedFunction() { $twig = $this->getEnvironment(true, [], self::$templates); try { $twig->load('1_basic7')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception if an unallowed function is called in the template'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedFunctionError::class, $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedFunctionError'); $this->assertEquals('cycle', $e->getFunctionName(), 'Exception should be raised on the "cycle" function'); } } public function testSandboxUnallowedRangeOperator() { $twig = $this->getEnvironment(true, [], self::$templates); try { $twig->load('1_range_operator')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception if the unallowed range operator is called'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedFunctionError::class, $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedFunctionError'); $this->assertEquals('range', $e->getFunctionName(), 'Exception should be raised on the "range" function'); } } public function testSandboxAllowMethodFoo() { $twig = $this->getEnvironment(true, [], self::$templates, [], [], ['Twig\Tests\Extension\FooObject' => 'foo']); FooObject::reset(); $this->assertEquals('foo', $twig->load('1_basic1')->render(self::$params), 'Sandbox allow some methods'); $this->assertEquals(1, FooObject::$called['foo'], 'Sandbox only calls method once'); } public function testSandboxAllowFilter() { $twig = $this->getEnvironment(true, [], self::$templates, [], ['upper']); $this->assertEquals('FABIEN', $twig->load('1_basic2')->render(self::$params), 'Sandbox allow some filters'); } public function testSandboxAllowTag() { $twig = $this->getEnvironment(true, [], self::$templates, ['if']); $this->assertEquals('foo', $twig->load('1_basic3')->render(self::$params), 'Sandbox allow some tags'); } public function testSandboxAllowProperty() { $twig = $this->getEnvironment(true, [], self::$templates, [], [], [], ['Twig\Tests\Extension\FooObject' => 'bar']); $this->assertEquals('bar', $twig->load('1_basic4')->render(self::$params), 'Sandbox allow some properties'); } public function testSandboxAllowFunction() { $twig = $this->getEnvironment(true, [], self::$templates, [], [], [], [], ['cycle']); $this->assertEquals('bar', $twig->load('1_basic7')->render(self::$params), 'Sandbox allow some functions'); } public function testSandboxAllowRangeOperator() { $twig = $this->getEnvironment(true, [], self::$templates, [], [], [], [], ['range']); $this->assertEquals('1', $twig->load('1_range_operator')->render(self::$params), 'Sandbox allow the range operator'); } public function testSandboxAllowFunctionsCaseInsensitive() { foreach (['getfoobar', 'getFoobar', 'getFooBar'] as $name) { $twig = $this->getEnvironment(true, [], self::$templates, [], [], ['Twig\Tests\Extension\FooObject' => $name]); FooObject::reset(); $this->assertEquals('foobarfoobar', $twig->load('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->load('1_basic9')->render(self::$params), 'Sandbox allow methods via shortcut names (ie. without get/set)'); } } public function testSandboxLocallySetForAnInclude() { self::$templates = [ '2_basic' => '{{ obj.foo }}{% include "2_included" %}{{ obj.foo }}', '2_included' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}', ]; $twig = $this->getEnvironment(false, [], self::$templates); $this->assertEquals('fooFOOfoo', $twig->load('2_basic')->render(self::$params), 'Sandbox does nothing if disabled globally and sandboxed not used for the include'); self::$templates = [ '3_basic' => '{{ obj.foo }}{% sandbox %}{% include "3_included" %}{% endsandbox %}{{ obj.foo }}', '3_included' => '{% if obj.foo %}{{ obj.foo|upper }}{% endif %}', ]; $twig = $this->getEnvironment(true, [], self::$templates); try { $twig->load('3_basic')->render(self::$params); $this->fail('Sandbox throws a SecurityError exception when the included file is sandboxed'); } catch (SecurityError $e) { $this->assertInstanceOf(SecurityNotAllowedTagError::class, $e, 'Exception should be an instance of Twig_Sandbox_SecurityNotAllowedTagError'); $this->assertEquals('sandbox', $e->getTagName()); } } public function testMacrosInASandbox() { $twig = $this->getEnvironment(true, ['autoescape' => 'html'], ['index' => <<{{ text }}

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

    username

    ', $twig->load('index')->render([])); } public function testSandboxDisabledAfterIncludeFunctionError() { $twig = $this->getEnvironment(false, [], self::$templates); $e = null; try { $twig->load('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(SandboxExtension::class)->isSandboxed(), 'Sandboxed include() function call should not leave Sandbox enabled when an error occurs.'); } protected function getEnvironment($sandboxed, $options, $templates, $tags = [], $filters = [], $methods = [], $properties = [], $functions = []) { $loader = new ArrayLoader($templates); $twig = new Environment($loader, array_merge(['debug' => true, 'cache' => false, 'autoescape' => false], $options)); $policy = new SecurityPolicy($tags, $filters, $methods, $properties, $functions); $twig->addExtension(new SandboxExtension($policy, $sandboxed)); return $twig; } } class FooObject { public static $called = ['__toString' => 0, 'foo' => 0, 'getFooBar' => 0]; public $bar = 'bar'; public static function reset() { self::$called = ['__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'; } public function getAnotherFooObject() { return new self(); } } php-twig-2.12.5/tests/FactoryRuntimeLoaderTest.php000066400000000000000000000014221362457344700221730ustar00rootroot00000000000000 '\Twig\Tests\getRuntime']); $this->assertInstanceOf('stdClass', $loader->load('stdClass')); } public function testLoadReturnsNullForUnmappedRuntime() { $loader = new FactoryRuntimeLoader(); $this->assertNull($loader->load('stdClass')); } } function getRuntime() { return new \stdClass(); } php-twig-2.12.5/tests/FileExtensionEscapingStrategyTest.php000066400000000000000000000024641362457344700240510ustar00rootroot00000000000000assertSame($strategy, FileExtensionEscapingStrategy::guess($filename)); } public function getGuessData() { return [ // default ['html', 'foo.html'], ['html', 'foo.html.twig'], ['html', 'foo'], ['html', 'foo.bar.twig'], ['html', 'foo.txt/foo'], ['html', 'foo.txt/foo.js/'], // css ['css', 'foo.css'], ['css', 'foo.css.twig'], ['css', 'foo.twig.css'], ['css', 'foo.js.css'], ['css', 'foo.js.css.twig'], // js ['js', 'foo.js'], ['js', 'foo.js.twig'], ['js', 'foo.txt/foo.js'], ['js', 'foo.txt.twig/foo.js'], // txt [false, 'foo.txt'], [false, 'foo.txt.twig'], ]; } } php-twig-2.12.5/tests/FilesystemHelper.php000066400000000000000000000012741362457344700205220ustar00rootroot00000000000000 $fileInfo) { if ($fileInfo->isDir()) { rmdir($filename); } else { unlink($filename); } } rmdir($dir); } } php-twig-2.12.5/tests/Fixtures/000077500000000000000000000000001362457344700163325ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/autoescape/000077500000000000000000000000001362457344700204635ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/autoescape/block.test000066400000000000000000000007521362457344700224620ustar00rootroot00000000000000--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 ['br' => '
    '] --CONFIG-- return ['autoescape' => 'name'] --EXPECT-- <br /> php-twig-2.12.5/tests/Fixtures/autoescape/name.test000066400000000000000000000006441362457344700223100ustar00rootroot00000000000000--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 ['br' => '
    '] --CONFIG-- return ['autoescape' => 'name'] --EXPECT-- <br /> \u003Cbr\u0020\/\u003E <br />
    php-twig-2.12.5/tests/Fixtures/errors/000077500000000000000000000000001362457344700176465ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/errors/base.html000066400000000000000000000000421362457344700214420ustar00rootroot00000000000000{% block content %}{% endblock %} php-twig-2.12.5/tests/Fixtures/errors/index.html000066400000000000000000000002001362457344700216330ustar00rootroot00000000000000{% extends 'base.html' %} {% block content %} {{ foo.bar }} {% endblock %} {% block foo %} {{ foo.bar }} {% endblock %} php-twig-2.12.5/tests/Fixtures/errors/leak-output.php000066400000000000000000000012601362457344700226300ustar00rootroot00000000000000 'Hello {{ "world"|broken }}', ]); $twig = new Environment($loader, ['debug' => isset($argv[1])]); $twig->addExtension(new BrokenExtension()); echo $twig->render('index.html.twig'); php-twig-2.12.5/tests/Fixtures/exceptions/000077500000000000000000000000001362457344700205135ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/exceptions/child_contents_outside_blocks.test000066400000000000000000000007411362457344700275070ustar00rootroot00000000000000--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\SyntaxError: 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? php-twig-2.12.5/tests/Fixtures/exceptions/exception_in_extension_extends.test000066400000000000000000000004301362457344700277230ustar00rootroot00000000000000--TEST-- Exception thrown from a child for an extension error --TEMPLATE-- {% extends 'base.twig' %} --TEMPLATE(base.twig)-- {{ random([]) }} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: The random function cannot pick from an empty array in "base.twig" at line 4. php-twig-2.12.5/tests/Fixtures/exceptions/exception_in_extension_include.test000066400000000000000000000004441362457344700277010ustar00rootroot00000000000000--TEST-- Exception thrown from an include for an extension error --TEMPLATE-- {% include 'content.twig' %} --TEMPLATE(content.twig)-- {{ random([]) }} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: The random function cannot pick from an empty array in "content.twig" at line 4. php-twig-2.12.5/tests/Fixtures/exceptions/multiline_array_with_undefined_variable.test000066400000000000000000000004561362457344700315420ustar00rootroot00000000000000--TEST-- Exception for multiline array with undefined variable --TEMPLATE-- {% set foo = { foo: 'foo', bar: 'bar', foobar: foobar, foo2: foo2, } %} --DATA-- return ['foobar' => 'foobar'] --EXCEPTION-- Twig\Error\RuntimeError: Variable "foo2" does not exist in "index.twig" at line 11. php-twig-2.12.5/tests/Fixtures/exceptions/multiline_array_with_undefined_variable_again.test000066400000000000000000000004331362457344700326740ustar00rootroot00000000000000--TEST-- Exception for multiline array with undefined variable --TEMPLATE-- {% set foo = { foo: 'foo', bar: 'bar', foobar: foobar, foo2: foo2, } %} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "foobar" does not exist in "index.twig" at line 7. php-twig-2.12.5/tests/Fixtures/exceptions/multiline_function_with_undefined_variable.test000066400000000000000000000004231362457344700322430ustar00rootroot00000000000000--TEST-- Exception for multile function with undefined variable --TEMPLATE-- {{ include('foo', with_context=with_context ) }} --TEMPLATE(foo)-- Foo --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "with_context" does not exist in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/exceptions/multiline_function_with_unknown_argument.test000066400000000000000000000004741362457344700320440ustar00rootroot00000000000000--TEST-- Exception for multiline function with unknown argument --TEMPLATE-- {{ include('foo', with_context=True, invalid=False ) }} --EXCEPTION-- Twig\Error\SyntaxError: Unknown argument "invalid" for function "include(template, variables, with_context, ignore_missing, sandboxed)" in "index.twig" at line 4. php-twig-2.12.5/tests/Fixtures/exceptions/multiline_tag_with_undefined_variable.test000066400000000000000000000003651362457344700311760ustar00rootroot00000000000000--TEST-- Exception for multiline tag with undefined variable --TEMPLATE-- {% include 'foo' with vars %} --TEMPLATE(foo)-- Foo --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "vars" does not exist in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/exceptions/strict_comparison_operator.test000066400000000000000000000004301362457344700270660ustar00rootroot00000000000000--TEST-- The PHP === strict comparison operator is not supported --TEMPLATE-- {{ 1 === 2 }} --EXCEPTION-- Twig\Error\SyntaxError: 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. php-twig-2.12.5/tests/Fixtures/exceptions/syntax_error_in_reused_template.test000066400000000000000000000004661362457344700301110ustar00rootroot00000000000000--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\SyntaxError: Unexpected token "operator" of value "=" ("end of statement block" expected) in "foo.twig" at line 3. php-twig-2.12.5/tests/Fixtures/exceptions/unclosed_tag.test000066400000000000000000000004711362457344700240650ustar00rootroot00000000000000--TEST-- Exception for an unclosed tag --TEMPLATE-- {% block foo %} {% if foo %} {% for i in fo %} {% endfor %} {% endblock %} --EXCEPTION-- Twig\Error\SyntaxError: Unexpected "endblock" tag (expecting closing tag for the "if" tag defined near line 4) in "index.twig" at line 16. php-twig-2.12.5/tests/Fixtures/exceptions/undefined_parent.test000066400000000000000000000003371362457344700247310ustar00rootroot00000000000000--TEST-- Exception for an undefined parent --TEMPLATE-- {% extends 'foo.html' %} {% set foo = "foo" %} --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "foo.html" is not defined in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/exceptions/undefined_template_in_child_template.test000066400000000000000000000005441362457344700307770ustar00rootroot00000000000000--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 [] --EXCEPTION-- Twig\Error\LoaderError: Template "include.twig" is not defined in "index.twig" at line 5. php-twig-2.12.5/tests/Fixtures/exceptions/undefined_trait.test000066400000000000000000000003721362457344700245620ustar00rootroot00000000000000--TEST-- Exception for an undefined trait --TEMPLATE-- {% use 'foo' with foobar as bar %} --TEMPLATE(foo)-- {% block bar %} {% endblock %} --EXCEPTION-- Twig\Error\RuntimeError: Block "foobar" is not defined in trait "foo" in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/expressions/000077500000000000000000000000001362457344700207145ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/expressions/_self.test000066400000000000000000000001531362457344700227040ustar00rootroot00000000000000--TEST-- _self returns the template name --TEMPLATE-- {{ _self }} --DATA-- return [] --EXPECT-- index.twig php-twig-2.12.5/tests/Fixtures/expressions/array.test000066400000000000000000000030571362457344700227400ustar00rootroot00000000000000--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'] }} {# array that does not exist #} {{ does_not_exist[0]|default('ok') }} {{ does_not_exist[0].does_not_exist_either|default('ok') }} {{ does_not_exist[0]['does_not_exist_either']|default('ok') }} --DATA-- return ['bar' => 'bar', 'foo' => ['bar' => 'bar'], 'array_access' => new \ArrayObject(['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 ok ok ok --DATA-- return ['bar' => 'bar', 'foo' => ['bar' => 'bar'], 'array_access' => new \ArrayObject(['a' => 'b'])] --CONFIG-- return ['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 ok ok ok php-twig-2.12.5/tests/Fixtures/expressions/array_call.test000066400000000000000000000003461362457344700237310ustar00rootroot00000000000000--TEST-- Twig supports method calls --TEMPLATE-- {{ items.foo }} {{ items['foo'] }} {{ items[foo] }} {{ items[items[foo]] }} --DATA-- return ['foo' => 'bar', 'items' => ['foo' => 'bar', 'bar' => 'foo']] --EXPECT-- bar bar foo bar php-twig-2.12.5/tests/Fixtures/expressions/binary.test000066400000000000000000000007511362457344700231040ustar00rootroot00000000000000--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 ['foo' => 'bar', 'bar' => 'foo'] --EXPECT-- 2 1 4 1 1 1 1 1 1 1 foobar barbar foofoo barfoo 2 php-twig-2.12.5/tests/Fixtures/expressions/bitwise.test000066400000000000000000000003171362457344700232640ustar00rootroot00000000000000--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 [] --EXPECT-- 1 5 4 ok php-twig-2.12.5/tests/Fixtures/expressions/call_argument_defined_twice.test000066400000000000000000000003451362457344700273050ustar00rootroot00000000000000--TEST-- Argument is defined twice in a call --TEMPLATE-- {{ date(987654, date = 123456) }} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Argument "date" is defined twice for function "date" in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/expressions/call_positional_arg_after_named_arg.test000066400000000000000000000004201362457344700307740ustar00rootroot00000000000000--TEST-- Positional arguments after named arguments in a call --TEMPLATE-- {{ date(date = 123456, 'Y-m-d') }} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Positional arguments cannot be used after named arguments for function "date" in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/expressions/comparison.test000066400000000000000000000004301362457344700237640ustar00rootroot00000000000000--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 [] --EXPECT-- ///1 1//1/1 1/ /1 php-twig-2.12.5/tests/Fixtures/expressions/divisibleby.test000066400000000000000000000004141362457344700241210ustar00rootroot00000000000000--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 [] --EXPECT-- OK OK OK OK php-twig-2.12.5/tests/Fixtures/expressions/dotdot.test000066400000000000000000000010261362457344700231110ustar00rootroot00000000000000--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 ['foo' => [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 php-twig-2.12.5/tests/Fixtures/expressions/ends_with.test000066400000000000000000000010321362457344700235750ustar00rootroot00000000000000--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 [] --EXPECT-- OK OK OK OK KO KO KO KO KO KO php-twig-2.12.5/tests/Fixtures/expressions/exponential_numbers.test000066400000000000000000000001621362457344700256750ustar00rootroot00000000000000--TEST-- Twig manages exponentiel numbers correctly --TEMPLATE-- {{ 1.99E+3 }} --DATA-- return [] --EXPECT-- 1990 php-twig-2.12.5/tests/Fixtures/expressions/floats.test000066400000000000000000000004001362457344700230770ustar00rootroot00000000000000--TEST-- Twig compiles floats properly --TEMPLATE-- {% set val2 = 0.0 %} {{ val is same as (0.0) ? 'Yes' : 'No' }} {{ val2 is same as (0.0) ? 'Yes' : 'No' }} {{ val is same as (val2) ? 'Yes' : 'No' }} --DATA-- return ['val' => 0.0] --EXPECT-- Yes Yes Yes php-twig-2.12.5/tests/Fixtures/expressions/grouping.test000066400000000000000000000001561362457344700234510ustar00rootroot00000000000000--TEST-- Twig supports grouping of expressions --TEMPLATE-- {{ (2 + 2) / 2 }} --DATA-- return [] --EXPECT-- 2 php-twig-2.12.5/tests/Fixtures/expressions/literals.test000066400000000000000000000003171362457344700234350ustar00rootroot00000000000000--TEST-- Twig supports literals --TEMPLATE-- 1 {{ true }} 2 {{ TRUE }} 3 {{ false }} 4 {{ FALSE }} 5 {{ none }} 6 {{ NONE }} 7 {{ null }} 8 {{ NULL }} --DATA-- return [] --EXPECT-- 1 1 2 1 3 4 5 6 7 8 php-twig-2.12.5/tests/Fixtures/expressions/magic_call.test000066400000000000000000000007331362457344700236730ustar00rootroot00000000000000--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 ['foo' => new TestClassForMagicCallAttributes()] --EXPECT-- foo_from_call bar_from_getbar php-twig-2.12.5/tests/Fixtures/expressions/matches.test000066400000000000000000000003351362457344700232420ustar00rootroot00000000000000--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 [] --EXPECT-- OK OK OK php-twig-2.12.5/tests/Fixtures/expressions/method_call.test000066400000000000000000000007401362457344700240710ustar00rootroot00000000000000--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 ['foo' => 'bar', 'items' => ['foo' => new Twig\Tests\TwigTestFoo(), 'bar' => 'foo']] --CONFIG-- return ['strict_variables' => false] --EXPECT-- foo foo bar bar_a-43 bar_bar foo is in not php-twig-2.12.5/tests/Fixtures/expressions/negative_numbers.test000066400000000000000000000002561362457344700251550ustar00rootroot00000000000000--TEST-- Twig manages negative numbers correctly --TEMPLATE-- {{ -1 }} {{ - 1 }} {{ 5 - 1 }} {{ 5-1 }} {{ 5 + -1 }} {{ 5 + - 1 }} --DATA-- return [] --EXPECT-- -1 -1 4 4 4 4 php-twig-2.12.5/tests/Fixtures/expressions/not_arrow_fn.test000066400000000000000000000002371362457344700243140ustar00rootroot00000000000000--TEST-- A string in parentheses cannot be confused with an arrow function --TEMPLATE-- {{ ["foo", "bar"]|join(("f")) }} --DATA-- return [] --EXPECT-- foofbar php-twig-2.12.5/tests/Fixtures/expressions/operators_as_variables.test000066400000000000000000000003621362457344700263470ustar00rootroot00000000000000--TEST-- Twig allows to use named operators as variable names --TEMPLATE-- {% for match in matches %} {{- match }} {% endfor %} {{ in }} {{ is }} --DATA-- return ['matches' => [1, 2, 3], 'in' => 'in', 'is' => 'is'] --EXPECT-- 1 2 3 in is php-twig-2.12.5/tests/Fixtures/expressions/postfix.test000066400000000000000000000004121362457344700233060ustar00rootroot00000000000000--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 [] --EXPECT-- a A A -1 foo foo php-twig-2.12.5/tests/Fixtures/expressions/power.test000066400000000000000000000003421362457344700227500ustar00rootroot00000000000000--TEST-- Twig parses power expressions --TEMPLATE-- {{ 2**3 }} {{ (-2)**3 }} {{ (-2)**(-3) }} {{ a ** a }} {{ a ** b }} {{ b ** a }} {{ b ** b }} --DATA-- return ['a' => 4, 'b' => -2] --EXPECT-- 8 -8 -0.125 256 0.0625 16 0.25 php-twig-2.12.5/tests/Fixtures/expressions/sameas.test000066400000000000000000000005031362457344700230640ustar00rootroot00000000000000--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 [] --EXPECT-- OK OK OK OK OK OK php-twig-2.12.5/tests/Fixtures/expressions/starts_with.test000066400000000000000000000010711362457344700241670ustar00rootroot00000000000000--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 [] --EXPECT-- OK OK OK OK OK OK KO KO KO KO php-twig-2.12.5/tests/Fixtures/expressions/string_operator_as_var_assignment.test000066400000000000000000000003351362457344700306220ustar00rootroot00000000000000--TEST-- Twig supports the string operators as variable names in assignments --TEMPLATE-- {% for matches in [1, 2] %} {{- matches }} {% endfor %} {% set matches = [1, 2] %} OK --DATA-- return [] --EXPECT-- 1 2 OK php-twig-2.12.5/tests/Fixtures/expressions/strings.test000066400000000000000000000003111362457344700233010ustar00rootroot00000000000000--TEST-- Twig supports string interpolation --TEMPLATE-- {{ "foo #{"foo #{bar} baz"} baz" }} {{ "foo #{bar}#{bar} baz" }} --DATA-- return ['bar' => 'BAR'] --EXPECT-- foo foo BAR baz baz foo BARBAR baz php-twig-2.12.5/tests/Fixtures/expressions/ternary_operator.test000066400000000000000000000005261362457344700252170ustar00rootroot00000000000000--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 ['foo' => 'foo', 'bar' => 'bar'] --EXPECT-- YES NO YES1 NO1 foo
    foo-bar php-twig-2.12.5/tests/Fixtures/expressions/ternary_operator_noelse.test000066400000000000000000000001741362457344700265630ustar00rootroot00000000000000--TEST-- Twig supports the ternary operator --TEMPLATE-- {{ 1 ? 'YES' }} {{ 0 ? 'YES' }} --DATA-- return [] --EXPECT-- YES php-twig-2.12.5/tests/Fixtures/expressions/ternary_operator_nothen.test000066400000000000000000000002021362457344700265610ustar00rootroot00000000000000--TEST-- Twig supports the ternary operator --TEMPLATE-- {{ 'YES' ?: 'NO' }} {{ 0 ?: 'NO' }} --DATA-- return [] --EXPECT-- YES NO php-twig-2.12.5/tests/Fixtures/expressions/two_word_operators_as_variables.test000066400000000000000000000003651362457344700302760ustar00rootroot00000000000000--TEST-- Twig does not allow to use two-word named operators as variable names --TEMPLATE-- {{ starts with }} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Unexpected token "operator" of value "starts with" in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/expressions/unary.test000066400000000000000000000002631362457344700227540ustar00rootroot00000000000000--TEST-- Twig supports unary operators (not, -, +) --TEMPLATE-- {{ not 1 }}/{{ not 0 }} {{ +1 + 1 }}/{{ -1 - 1 }} {{ not (false or true) }} --DATA-- return [] --EXPECT-- /1 2/-2 php-twig-2.12.5/tests/Fixtures/expressions/unary_macro_arguments.test000066400000000000000000000011361362457344700262220ustar00rootroot00000000000000--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 [] --EXPECT-- -1 1 -1 1 1 php-twig-2.12.5/tests/Fixtures/expressions/unary_precedence.test000066400000000000000000000002311362457344700251240ustar00rootroot00000000000000--TEST-- Twig unary operators precedence --TEMPLATE-- {{ -1 - 1 }} {{ -1 - -1 }} {{ -1 * -1 }} {{ 4 / -1 * 5 }} --DATA-- return [] --EXPECT-- -2 0 1 -20 php-twig-2.12.5/tests/Fixtures/extensions/000077500000000000000000000000001362457344700205315ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/extensions/anonymous_functions.test000066400000000000000000000002301362457344700255450ustar00rootroot00000000000000--TEST-- use an anonymous function as a function --TEMPLATE-- {{ anon_foo('bar') }} {{ 'bar'|anon_foo }} --DATA-- return array() --EXPECT-- *bar* *bar* php-twig-2.12.5/tests/Fixtures/filters/000077500000000000000000000000001362457344700200025ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/filters/abs.test000066400000000000000000000006071362457344700214530ustar00rootroot00000000000000--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 ['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 php-twig-2.12.5/tests/Fixtures/filters/batch.test000066400000000000000000000012661362457344700217710ustar00rootroot00000000000000--TEST-- "batch" filter --TEMPLATE-- {% for row in items|batch(3) %}
    {% for column in row %}
    {{ column }}
    {% endfor %}
    {% endfor %} --DATA-- return ['items' => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']] --EXPECT--
    a
    b
    c
    d
    e
    f
    g
    h
    i
    j
    php-twig-2.12.5/tests/Fixtures/filters/batch_float.test000066400000000000000000000012331362457344700231500ustar00rootroot00000000000000--TEST-- "batch" filter --TEMPLATE-- {% for row in items|batch(3.1) %}
    {% for column in row %}
    {{ column }}
    {% endfor %}
    {% endfor %} --DATA-- return ['items' => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']] --EXPECT--
    a
    b
    c
    d
    e
    f
    g
    h
    i
    j
    php-twig-2.12.5/tests/Fixtures/filters/batch_with_empty_fill.test000066400000000000000000000010631362457344700252430ustar00rootroot00000000000000--TEST-- "batch" filter --TEMPLATE-- {% for row in items|batch(3, '') %} {% for column in row %} {% endfor %} {% endfor %}
    {{ column }}
    --DATA-- return ['items' => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']] --EXPECT--
    a b c
    d e f
    g h i
    j
    php-twig-2.12.5/tests/Fixtures/filters/batch_with_exact_elements.test000066400000000000000000000014041362457344700260760ustar00rootroot00000000000000--TEST-- "batch" filter --TEMPLATE-- {% for row in items|batch(3, 'fill') %}
    {% for column in row %}
    {{ column }}
    {% endfor %}
    {% endfor %} --DATA-- return ['items' => ['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
    php-twig-2.12.5/tests/Fixtures/filters/batch_with_fill.test000066400000000000000000000010771362457344700240320ustar00rootroot00000000000000--TEST-- "batch" filter --TEMPLATE-- {% for row in items|batch(3, 'fill') %} {% for column in row %} {% endfor %} {% endfor %}
    {{ column }}
    --DATA-- return ['items' => ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']] --EXPECT--
    a b c
    d e f
    g h i
    j fill fill
    php-twig-2.12.5/tests/Fixtures/filters/batch_with_keys.test000066400000000000000000000003721362457344700240540ustar00rootroot00000000000000--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 [] --EXPECT-- foo,key foo,key,0,1 php-twig-2.12.5/tests/Fixtures/filters/batch_with_more_elements.test000066400000000000000000000010271362457344700257350ustar00rootroot00000000000000--TEST-- "batch" filter --TEMPLATE-- {% for row in items|batch(3, 'fill') %}
    {% for key, column in row %}
    {{ column }}
    {% endfor %}
    {% endfor %} --DATA-- return ['items' => ['a' => 'a', 'b' => 'b', 'c' => 'c', 'd' => 'd', '123' => 'e']] --EXPECT--
    a
    b
    c
    d
    e
    fill
    php-twig-2.12.5/tests/Fixtures/filters/batch_with_zero_elements.test000066400000000000000000000002241362457344700257500ustar00rootroot00000000000000--TEST-- "batch" filter with zero elements --TEMPLATE-- {{ []|batch(3)|length }} {{ []|batch(3, 'fill')|length }} --DATA-- return [] --EXPECT-- 0 0 php-twig-2.12.5/tests/Fixtures/filters/column.test000066400000000000000000000004671362457344700222070ustar00rootroot00000000000000--TEST-- "column" filter --TEMPLATE-- {{ array|column('foo')|join }} {{ traversable|column('foo')|join }} --DATA-- $items = array(array('bar' => 'foo', 'foo' => 'bar'), array('foo' => 'foo', 'bar' => 'bar')); return array('array' => $items, 'traversable' => new ArrayIterator($items)); --EXPECT-- barfoo barfoo php-twig-2.12.5/tests/Fixtures/filters/convert_encoding.test000066400000000000000000000003321362457344700242270ustar00rootroot00000000000000--TEST-- "convert_encoding" filter --TEMPLATE-- {{ "愛していますか?"|convert_encoding('ISO-2022-JP', 'UTF-8')|convert_encoding('UTF-8', 'ISO-2022-JP') }} --DATA-- return [] --EXPECT-- 愛していますか? php-twig-2.12.5/tests/Fixtures/filters/date.test000066400000000000000000000045521362457344700216260ustar00rootroot00000000000000--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 [ '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 php-twig-2.12.5/tests/Fixtures/filters/date_default_format.test000066400000000000000000000004741362457344700247010ustar00rootroot00000000000000--TEST-- "date" filter --TEMPLATE-- {{ date1|date }} {{ date1|date('d/m/Y') }} --DATA-- date_default_timezone_set('UTC'); $twig->getExtension(\Twig\Extension\CoreExtension::class)->setDateFormat('Y-m-d', '%d days %h hours'); return [ 'date1' => mktime(13, 45, 0, 10, 4, 2010), ] --EXPECT-- 2010-10-04 04/10/2010 php-twig-2.12.5/tests/Fixtures/filters/date_default_format_interval.test000066400000000000000000000005131362457344700265770ustar00rootroot00000000000000--TEST-- "date" filter (interval support) --TEMPLATE-- {{ date2|date }} {{ date2|date('%d days') }} --DATA-- date_default_timezone_set('UTC'); $twig->getExtension(\Twig\Extension\CoreExtension::class)->setDateFormat('Y-m-d', '%d days %h hours'); return [ 'date2' => new \DateInterval('P2D'), ] --EXPECT-- 2 days 0 hours 2 days php-twig-2.12.5/tests/Fixtures/filters/date_immutable.test000066400000000000000000000017301362457344700236600ustar00rootroot00000000000000--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 [ '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 php-twig-2.12.5/tests/Fixtures/filters/date_interval.test000066400000000000000000000006441362457344700235300ustar00rootroot00000000000000--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 [ '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 php-twig-2.12.5/tests/Fixtures/filters/date_modify.test000066400000000000000000000005231362457344700231670ustar00rootroot00000000000000--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 [ '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 php-twig-2.12.5/tests/Fixtures/filters/date_namedargs.test000066400000000000000000000006421362457344700236430ustar00rootroot00000000000000--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 ['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 php-twig-2.12.5/tests/Fixtures/filters/default.test000066400000000000000000000103011362457344700223220ustar00rootroot00000000000000--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' }} {{ undefined['undefined'] |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' }} {{ nested['undefinedVar'][0] |default('default') is same as('default') ? 'ok' : 'ko' }} {{ undefined['undefined'][0] |default('default') is same as('default') ? 'ok' : 'ko' }} {{ 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 [ 'definedVar' => 'defined', 'zeroVar' => 0, 'emptyVar' => '', 'nullVar' => null, 'nested' => [ 'definedVar' => 'defined', 'zeroVar' => 0, 'emptyVar' => '', 'nullVar' => null, 'definedArray' => [0], ], 'object' => new Twig\Tests\TwigTestFoo(), ] --CONFIG-- return ['strict_variables' => false] --EXPECT-- Variable: ok ok ok ok ok Array access: ok 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 ok ok --DATA-- return [ 'definedVar' => 'defined', 'zeroVar' => 0, 'emptyVar' => '', 'nullVar' => null, 'nested' => [ 'definedVar' => 'defined', 'zeroVar' => 0, 'emptyVar' => '', 'nullVar' => null, 'definedArray' => [0], ], 'object' => new Twig\Tests\TwigTestFoo(), ] --CONFIG-- return ['strict_variables' => true] --EXPECT-- Variable: ok ok ok ok ok Array access: ok 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 ok ok php-twig-2.12.5/tests/Fixtures/filters/dynamic_filter.test000066400000000000000000000002001362457344700236640ustar00rootroot00000000000000--TEST-- dynamic filter --TEMPLATE-- {{ 'bar'|foo_path }} {{ 'bar'|a_foo_b_bar }} --DATA-- return [] --EXPECT-- foo/bar a/b/bar php-twig-2.12.5/tests/Fixtures/filters/escape.test000066400000000000000000000001521362457344700221410ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {{ "foo
    "|e }} --DATA-- return [] --EXPECT-- foo <br /> php-twig-2.12.5/tests/Fixtures/filters/escape_html_attr.test000066400000000000000000000003071362457344700242210ustar00rootroot00000000000000--TEST-- "escape" filter does not escape with the html strategy when using the html_attr strategy --TEMPLATE-- {{ '
    '|escape('html_attr') }} --DATA-- return [] --EXPECT-- <br /> php-twig-2.12.5/tests/Fixtures/filters/escape_javascript.test000066400000000000000000000002051362457344700243660ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {{ "é ♜ 𝌆"|e('js') }} --DATA-- return [] --EXPECT-- \u00E9\u0020\u265C\u0020\uD834\uDF06 php-twig-2.12.5/tests/Fixtures/filters/escape_non_supported_charset.test000066400000000000000000000002241362457344700266310ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {{ "愛していますか?
    "|e }} --DATA-- return [] --EXPECT-- 愛していますか? <br /> php-twig-2.12.5/tests/Fixtures/filters/filter.test000066400000000000000000000026211362457344700221710ustar00rootroot00000000000000--TEST-- "filter" filter --TEMPLATE-- {% set offset = 3 %} {% for k, v in [1, 5, 3, 4, 5]|filter((v) => v > offset) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in {a: 1, b: 2, c: 5, d: 8}|filter(v => v > offset) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in {a: 1, b: 2, c: 5, d: 8}|filter((v, k) => (v > offset) and (k != "d")) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in [1, 5, 3, 4, 5]|filter(v => v > offset) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in it|filter((v) => v > offset) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in ita|filter(v => v > offset) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in xml|filter(x => true) %} {{ k }}/{{ v }} {% endfor %} {# we can iterate more than once #} {% for k, v in xml|filter(x => true) %} {{ k }}/{{ v }} {% endfor %} {% set coll = ['a', 'b']|filter(v => v is same as('a')) %} {% if coll|length > 0 %} {{- coll|join(', ') }} {% endif %} --DATA-- return [ 'it' => new \ArrayIterator(['a' => 1, 'b' => 2, 'c' => 5, 'd' => 8]), 'ita' => new Twig\Tests\IteratorAggregateStub(['a' => 1, 'b' => 2, 'c' => 5, 'd' => 8]), 'xml' => new \SimpleXMLElement('foobarbaz'), ] --EXPECT-- 1 = 5 3 = 4 4 = 5 c = 5 d = 8 c = 5 1 = 5 3 = 4 4 = 5 c = 5 d = 8 c = 5 d = 8 elem/foo elem/bar elem/baz elem/foo elem/bar elem/baz a php-twig-2.12.5/tests/Fixtures/filters/first.test000066400000000000000000000003731362457344700220350ustar00rootroot00000000000000--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 ['arr' => new \ArrayObject([1, 2, 3, 4])] --EXPECT-- 1 1 1 1 Ä php-twig-2.12.5/tests/Fixtures/filters/force_escape.test000066400000000000000000000004471362457344700233260ustar00rootroot00000000000000--TEST-- "escape" filter --TEMPLATE-- {% set foo %} foo
    {% endset %} {{ foo|e('html') -}} {{ foo|e('js') }} {% autoescape true %} {{ foo }} {% endautoescape %} --DATA-- return [] --EXPECT-- foo<br /> \u0020\u0020\u0020\u0020foo\u003Cbr\u0020\/\u003E\n foo
    php-twig-2.12.5/tests/Fixtures/filters/format.test000066400000000000000000000002111362457344700221650ustar00rootroot00000000000000--TEST-- "format" filter --TEMPLATE-- {{ string|format(foo, 3) }} --DATA-- return ['string' => '%s/%d', 'foo' => 'bar'] --EXPECT-- bar/3 php-twig-2.12.5/tests/Fixtures/filters/join.test000066400000000000000000000014161362457344700216440ustar00rootroot00000000000000--TEST-- "join" filter --TEMPLATE-- {{ ["foo", "bar"]|join(', ') }} {{ foo|join(', ') }} {{ bar|join(', ') }} {{ ["foo", "bar"]|join(', ', ' and ') }} {{ foo|join(', ', ' and ') }} {{ bar|join(', ', ' and ') }} {{ ["one", "two", "three"]|join(', ', ' and ') }} {{ ["a", "b", "c"]|join('','-') }} {{ ["a", "b", "c"]|join('-','-') }} {{ ["a", "b", "c"]|join('-','') }} {{ ["hello"]|join('|','-') }} {{ {"a": "w", "b": "x", "c": "y", "d": "z"}|join }} {{ {"a": "w", "b": "x", "c": "y", "d": "z"}|join(',') }} {{ {"a": "w", "b": "x", "c": "y", "d": "z"}|join(',','-') }} --DATA-- return ['foo' => new Twig\Tests\TwigTestFoo(), 'bar' => new \ArrayObject([3, 4])] --EXPECT-- foo, bar 1, 2 3, 4 foo and bar 1 and 2 3 and 4 one, two and three ab-c a-b-c a-bc hello wxyz w,x,y,z w,x,y-z php-twig-2.12.5/tests/Fixtures/filters/json_encode.test000066400000000000000000000003451362457344700231730ustar00rootroot00000000000000--TEST-- "json_encode" filter --TEMPLATE-- {{ "foo"|json_encode|raw }} {{ foo|json_encode|raw }} {{ [foo, "foo"]|json_encode|raw }} --DATA-- return ['foo' => new \Twig\Markup('foo', 'UTF-8')] --EXPECT-- "foo" "foo" ["foo","foo"] php-twig-2.12.5/tests/Fixtures/filters/last.test000066400000000000000000000003641362457344700216510ustar00rootroot00000000000000--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 ['arr' => new \ArrayObject([1, 2, 3, 4])] --EXPECT-- 4 4 4 4 é php-twig-2.12.5/tests/Fixtures/filters/length.test000066400000000000000000000020641362457344700221660ustar00rootroot00000000000000--TEST-- "length" filter --TEMPLATE-- {{ array|length }} {{ string|length }} {{ number|length }} {{ to_string_able|length }} {{ countable|length }} {{ iterator_aggregate|length }} {{ null|length }} {{ magic|length }} {{ non_countable|length }} {{ simple_xml_element|length }} {{ iterator|length }} --DATA-- return [ 'array' => [1, 4], 'string' => 'foo', 'number' => 1000, 'to_string_able' => new Twig\Tests\ToStringStub('foobar'), 'countable' => new Twig\Tests\CountableStub(42), /* also asserts we do *not* call __toString() */ 'iterator_aggregate' => new Twig\Tests\IteratorAggregateStub(['a', 'b', 'c']), /* also asserts we do *not* call __toString() */ 'null' => null, 'magic' => new Twig\Tests\MagicCallStub(), /* used to assert we do *not* call __call */ 'non_countable' => new \StdClass(), 'simple_xml_element' => new \SimpleXMLElement(''), 'iterator' => new Twig\Tests\SimpleIteratorForTesting() ] --EXPECT-- 2 3 4 6 42 3 0 1 1 2 7 php-twig-2.12.5/tests/Fixtures/filters/length_utf8.test000066400000000000000000000002611362457344700231310ustar00rootroot00000000000000--TEST-- "length" filter --TEMPLATE-- {{ string|length }} {{ markup|length }} --DATA-- return ['string' => 'été', 'markup' => new \Twig\Markup('foo', 'UTF-8')] --EXPECT-- 3 3 php-twig-2.12.5/tests/Fixtures/filters/map.test000066400000000000000000000015501362457344700214610ustar00rootroot00000000000000--TEST-- "map" filter --TEMPLATE-- {% set offset = 3 %} {% for k, v in [1, 2]|map((item) => item + 2 ) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in {a: 1, b: 2}|map((item) => item ~ "*" ) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in {a: 1, b: 2}|map((item, k) => item ~ "*" ~ k ) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in [1, 2]|map(item => item + 2 ) -%} {{ k }} = {{ v }} {% endfor %} {% for k, v in it|map(item => item + 2 ) -%} {{ k }} = {{ v }} {% endfor %} {% macro local_lower(string) %} {{- string|lower }} {% endmacro %} {{ ['A']|map(val => _self.local_lower(val))|join }} {%- from _self import local_lower as renamed_lower %} {{ ['A']|map(val => renamed_lower(val))|join }} --DATA-- return ['it' => new \ArrayIterator([1, 2])] --EXPECT-- 0 = 3 1 = 4 a = 1* b = 2* a = 1*a b = 2*b 0 = 3 1 = 4 0 = 3 1 = 4 a a php-twig-2.12.5/tests/Fixtures/filters/merge.test000066400000000000000000000010511362457344700217770ustar00rootroot00000000000000--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 [ 'items' => ['foo' => 'bar'], 'numerics' => [1, 2, 3], 'traversable' => [ 'a' => new \ArrayObject([0 => 1, 1 => 2, 2 => 3]), 'b' => new \ArrayObject(['a' => 'b']) ] ] --EXPECT-- barfoo foobar foobar barfoo 123456 123b php-twig-2.12.5/tests/Fixtures/filters/nl2br.test000066400000000000000000000005711362457344700217250ustar00rootroot00000000000000--TEST-- "nl2br" filter --TEMPLATE-- {{ "I like Twig.\nYou will like it too.\n\nEverybody like it!"|nl2br }} {{ text|nl2br }} --DATA-- return ['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. php-twig-2.12.5/tests/Fixtures/filters/number_format.test000066400000000000000000000004541362457344700235460ustar00rootroot00000000000000--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 [] --EXPECT-- 20 20 20.25 20,25 1,020,25 1.020,25 php-twig-2.12.5/tests/Fixtures/filters/number_format_default.test000066400000000000000000000006761362457344700252600ustar00rootroot00000000000000--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\CoreExtension::class)->setNumberFormat(2, '!', '='); return [] --EXPECT-- 20!00 20!25 20!3 20,25 1=020!25 1=020,25 1.020,25 php-twig-2.12.5/tests/Fixtures/filters/reduce.test000066400000000000000000000004101362457344700221450ustar00rootroot00000000000000--TEST-- "reduce" filter --TEMPLATE-- {% set offset = 3 %} {{ [1, -1, 4]|reduce((carry, item) => carry + item + offset, 10) }} {{ it|reduce((carry, item) => carry + item + offset, 10) }} --DATA-- return ['it' => new \ArrayIterator([1, -1, 4])] --EXPECT-- 23 23 php-twig-2.12.5/tests/Fixtures/filters/replace.test000066400000000000000000000006761362457344700223270ustar00rootroot00000000000000--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 ['traversable' => new \ArrayObject(['%this%' => 'foo', '%that%' => 'bar'])] --EXPECT-- I liké foo and bar. I like single replace operation only %that%1 I like foo and bar. php-twig-2.12.5/tests/Fixtures/filters/replace_invalid_arg.test000066400000000000000000000004721362457344700246600ustar00rootroot00000000000000--TEST-- Exception for invalid argument type in replace call --TEMPLATE-- {{ 'test %foo%'|replace(stdClass) }} --DATA-- return ['stdClass' => new \stdClass()] --EXCEPTION-- Twig\Error\RuntimeError: The "replace" filter expects an array or "Traversable" as replace values, got "stdClass" in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/filters/reverse.test000066400000000000000000000006531362457344700223620ustar00rootroot00000000000000--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 ['arr' => new \ArrayObject([1, 2, 3, 4])] --EXPECT-- 4321 tnemenèvé4321 4321 a,c a,c a,c php-twig-2.12.5/tests/Fixtures/filters/round.test000066400000000000000000000004011362457344700220250ustar00rootroot00000000000000--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 [] --EXPECT-- 3 2 2.123 3 20 30 20 php-twig-2.12.5/tests/Fixtures/filters/slice.test000066400000000000000000000017441362457344700220100ustar00rootroot00000000000000--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 ['start' => 1, 'length' => 2, 'arr' => new \ArrayObject([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 php-twig-2.12.5/tests/Fixtures/filters/sort.test000066400000000000000000000004051362457344700216710ustar00rootroot00000000000000--TEST-- "sort" filter --TEMPLATE-- {{ array1|sort|join }} {{ array2|sort|join }} {{ traversable|sort|join }} --DATA-- return ['array1' => [4, 1], 'array2' => ['foo', 'bar'], 'traversable' => new \ArrayObject([0 => 3, 1 => 2, 2 => 1])] --EXPECT-- 14 barfoo 123 php-twig-2.12.5/tests/Fixtures/filters/sort_with_arrow.test000066400000000000000000000007521362457344700241430ustar00rootroot00000000000000--TEST-- "sort" filter --TEMPLATE-- {{ fruits|sort((a, b) => a.quantity == b.quantity ? 0 : (a.quantity > b.quantity ? 1 : -1))|column('name')|join(', ') }} {{ fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name')|join(', ') }} --DATA-- return [ 'fruits' => [ [ 'name' => 'Apples', 'quantity' => 5 ], [ 'name' => 'Oranges', 'quantity' => 2 ], [ 'name' => 'Grapes', 'quantity' => 4 ], ], ] --EXPECT-- Oranges, Grapes, Apples Oranges, Grapes, Apples php-twig-2.12.5/tests/Fixtures/filters/spaceless.test000066400000000000000000000002431362457344700226640ustar00rootroot00000000000000--TEST-- "spaceless" filter --TEMPLATE-- {{ "
    foo
    "|spaceless }} --DATA-- return [] --EXPECT--
    foo
    php-twig-2.12.5/tests/Fixtures/filters/special_chars.test000066400000000000000000000001361362457344700235030ustar00rootroot00000000000000--TEST-- "§" custom filter --TEMPLATE-- {{ 'foo'|§ }} --DATA-- return [] --EXPECT-- §foo§ php-twig-2.12.5/tests/Fixtures/filters/split.test000066400000000000000000000010271362457344700220360ustar00rootroot00000000000000--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('-') }} {{ "hello0world"|split('0')|join('-') }} --DATA-- return ['foo' => "one,two,three,four,five", 'baz' => '12345',] --EXPECT-- one-two-three-four-five one-two-three-four-five one-two-three,four,five 1-2-3-4-5 1-2-3-4-5 12-34-5 one-two-three hello-worldphp-twig-2.12.5/tests/Fixtures/filters/split_utf8.test000066400000000000000000000007261362457344700230110ustar00rootroot00000000000000--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 ['foo' => 'Ä,é,Äほ', 'baz' => 'éÄßごa',] --EXPECT-- é Ä-é-Äほ Ä,é,Äほ Ä-é,Äほ Ä-é-Äほ é-Ä-ß-ご-a é-Ä-ß-ご-a éÄ-ßご-aphp-twig-2.12.5/tests/Fixtures/filters/static_calls.test000066400000000000000000000002521362457344700233470ustar00rootroot00000000000000--TEST-- Filters as static method calls --TEMPLATE-- {{ 'foo'|static_call_string }} {{ 'foo'|static_call_array }} --DATA-- return ['foo' => 'foo'] --EXPECT-- *foo* *foo* php-twig-2.12.5/tests/Fixtures/filters/trim.test000066400000000000000000000012561362457344700216620ustar00rootroot00000000000000--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 ['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. php-twig-2.12.5/tests/Fixtures/filters/urlencode.test000066400000000000000000000007541362457344700226710ustar00rootroot00000000000000--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 [] --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 php-twig-2.12.5/tests/Fixtures/functions/000077500000000000000000000000001362457344700203425ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/functions/attribute.test000066400000000000000000000007661362457344700232570ustar00rootroot00000000000000--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 ['obj' => new Twig\Tests\TwigTestFoo(), 'method' => 'foo', 'array' => ['foo' => 'bar'], 'item' => 'foo', 'nonmethod' => 'xxx', 'arguments' => ['a', 'b']] --EXPECT-- foo bar bar_a-b bar_a-b ok ko php-twig-2.12.5/tests/Fixtures/functions/block.test000066400000000000000000000003651362457344700223410ustar00rootroot00000000000000--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 [] --EXPECT-- BARBAR php-twig-2.12.5/tests/Fixtures/functions/block_with_template.test000066400000000000000000000010031362457344700252550ustar00rootroot00000000000000--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 [ 'included_loaded' => $twig->load('included.twig'), 'included_loaded_internal' => $twig->load('included.twig'), ] --EXPECT-- FOO FOO FOO FOO NOT FOO php-twig-2.12.5/tests/Fixtures/functions/block_without_name.test000066400000000000000000000005511362457344700251210ustar00rootroot00000000000000--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 [] --EXCEPTION-- Twig\Error\SyntaxError: The "block" function takes one argument (the block name) in "base.twig" at line 2. php-twig-2.12.5/tests/Fixtures/functions/block_without_parent.test000066400000000000000000000006401362457344700254710ustar00rootroot00000000000000--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\RuntimeError: 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. php-twig-2.12.5/tests/Fixtures/functions/constant.test000066400000000000000000000003521362457344700230740ustar00rootroot00000000000000--TEST-- "constant" function --TEMPLATE-- {{ constant('DATE_W3C') == expect ? 'true' : 'false' }} {{ constant('ARRAY_AS_PROPS', object) }} --DATA-- return ['expect' => DATE_W3C, 'object' => new \ArrayObject(['hi'])] --EXPECT-- true 2 php-twig-2.12.5/tests/Fixtures/functions/cycle.test000066400000000000000000000004471362457344700223470ustar00rootroot00000000000000--TEST-- "cycle" function --TEMPLATE-- {% for i in 0..6 %} {{ cycle(array1, i) }}-{{ cycle(array2, i) }} {% endfor %} --DATA-- return ['array1' => ['odd', 'even'], 'array2' => ['apple', 'orange', 'citrus']] --EXPECT-- odd-apple even-orange odd-citrus even-apple odd-orange even-citrus odd-apple php-twig-2.12.5/tests/Fixtures/functions/date.test000066400000000000000000000017051362457344700221630ustar00rootroot00000000000000--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 [ '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 php-twig-2.12.5/tests/Fixtures/functions/date_namedargs.test000066400000000000000000000005261362457344700242040ustar00rootroot00000000000000--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 ['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 php-twig-2.12.5/tests/Fixtures/functions/dump.test000066400000000000000000000004431362457344700222110ustar00rootroot00000000000000--TEST-- "dump" function --CONDITION-- !extension_loaded('xdebug') --TEMPLATE-- {{ dump('foo') }} {{ dump('foo', 'bar') }} --DATA-- return ['foo' => 'foo', 'bar' => 'bar'] --CONFIG-- return ['debug' => true, 'autoescape' => false] --EXPECT-- string(3) "foo" string(3) "foo" string(3) "bar" php-twig-2.12.5/tests/Fixtures/functions/dump_array.test000066400000000000000000000007301362457344700234060ustar00rootroot00000000000000--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 ['foo' => 'foo', 'bar' => 'bar'] --CONFIG-- return ['debug' => true, 'autoescape' => false] --EXPECT-- array(3) { ["foo"]=> string(3) "foo" ["bar"]=> string(3) "bar" ["global"]=> string(6) "global" } php-twig-2.12.5/tests/Fixtures/functions/dynamic_function.test000066400000000000000000000002041362457344700245700ustar00rootroot00000000000000--TEST-- dynamic function --TEMPLATE-- {{ foo_path('bar') }} {{ a_foo_b_bar('bar') }} --DATA-- return [] --EXPECT-- foo/bar a/b/bar php-twig-2.12.5/tests/Fixtures/functions/include/000077500000000000000000000000001362457344700217655ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/functions/include/assignment.test000066400000000000000000000002501362457344700250330ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {% set tmp = include("foo.twig") %} FOO{{ tmp }}BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return [] --EXPECT-- FOO FOOBARBAR php-twig-2.12.5/tests/Fixtures/functions/include/autoescaping.test000066400000000000000000000002521362457344700253470ustar00rootroot00000000000000--TEST-- "include" function is safe for auto-escaping --TEMPLATE-- {{ include("foo.twig") }} --TEMPLATE(foo.twig)--

    Test

    --DATA-- return [] --EXPECT--

    Test

    php-twig-2.12.5/tests/Fixtures/functions/include/basic.test000066400000000000000000000002311362457344700237430ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- FOO {{ include("foo.twig") }} BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return [] --EXPECT-- FOO FOOBAR BAR php-twig-2.12.5/tests/Fixtures/functions/include/expression.test000066400000000000000000000003241362457344700250640ustar00rootroot00000000000000--TEST-- "include" function allows expressions for the template to include --TEMPLATE-- FOO {{ include(foo) }} BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return ['foo' => 'foo.twig'] --EXPECT-- FOO FOOBAR BAR php-twig-2.12.5/tests/Fixtures/functions/include/ignore_missing.test000066400000000000000000000005161362457344700257040ustar00rootroot00000000000000--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 [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/functions/include/ignore_missing_exists.test000066400000000000000000000004511362457344700273010ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {{ include("included.twig", ignore_missing = true) }} NOT DISPLAYED --TEMPLATE(included.twig)-- {{ include("DOES NOT EXIST") }} --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "DOES NOT EXIST" is not defined in "included.twig" at line 2. php-twig-2.12.5/tests/Fixtures/functions/include/include_missing_extends.test000066400000000000000000000005161362457344700275760ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {{ include(['bad.twig', 'good.twig'], ignore_missing = true) }} NOT DISPLAYED --TEMPLATE(bad.twig)-- {% extends 'DOES NOT EXIST' %} --TEMPLATE(good.twig)-- NOT DISPLAYED --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "DOES NOT EXIST" is not defined in "bad.twig" at line 2. php-twig-2.12.5/tests/Fixtures/functions/include/missing.test000066400000000000000000000002721362457344700243400ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {{ include("foo.twig") }} --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "foo.twig" is not defined in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/functions/include/missing_nested.test000066400000000000000000000005111362457344700256760ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {% extends "base.twig" %} {% block content %} {{ parent() }} {% endblock %} --TEMPLATE(base.twig)-- {% block content %} {{ include("foo.twig") }} {% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "foo.twig" is not defined in "base.twig" at line 3. php-twig-2.12.5/tests/Fixtures/functions/include/sandbox.test000066400000000000000000000004131362457344700243220ustar00rootroot00000000000000--TEST-- "include" tag sandboxed --TEMPLATE-- {{ include("foo.twig", sandboxed = true) }} --TEMPLATE(foo.twig)-- {{ foo|e }} {{ foo|e }} --DATA-- return [] --EXCEPTION-- Twig\Sandbox\SecurityNotAllowedFilterError: Filter "e" is not allowed in "foo.twig" at line 4. php-twig-2.12.5/tests/Fixtures/functions/include/sandbox_disabling.test000066400000000000000000000003721362457344700263420ustar00rootroot00000000000000--TEST-- "include" tag sandboxed --TEMPLATE-- {{ include("foo.twig", sandboxed = true) }} {{ include("bar.twig") }} --TEMPLATE(foo.twig)-- foo --TEMPLATE(bar.twig)-- {{ foo|e }} --DATA-- return ['foo' => 'bar
    '] --EXPECT-- foo bar<br /> php-twig-2.12.5/tests/Fixtures/functions/include/sandbox_disabling_ignore_missing.test000066400000000000000000000003661362457344700314410ustar00rootroot00000000000000--TEST-- "include" tag sandboxed --TEMPLATE-- {{ include("unknown.twig", sandboxed = true, ignore_missing = true) }} {{ include("bar.twig") }} --TEMPLATE(bar.twig)-- {{ foo|e }} --DATA-- return ['foo' => 'bar
    '] --EXPECT-- bar<br /> php-twig-2.12.5/tests/Fixtures/functions/include/template_instance.test000066400000000000000000000003001362457344700263560ustar00rootroot00000000000000--TEST-- "include" function accepts Twig_Template instance --TEMPLATE-- {{ include(foo) }} FOO --TEMPLATE(foo.twig)-- BAR --DATA-- return ['foo' => $twig->load('foo.twig')] --EXPECT-- BAR FOO php-twig-2.12.5/tests/Fixtures/functions/include/templates_as_array.test000066400000000000000000000002731362457344700265470ustar00rootroot00000000000000--TEST-- "include" function --TEMPLATE-- {{ include(["foo.twig", "bar.twig"]) }} {{- include(["bar.twig", "foo.twig"]) }} --TEMPLATE(foo.twig)-- foo --DATA-- return [] --EXPECT-- foo foo php-twig-2.12.5/tests/Fixtures/functions/include/with_context.test000066400000000000000000000007101362457344700254030ustar00rootroot00000000000000--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 ['foo' => 'bar'] --EXPECT-- foo,global,_parent, global,_parent, foo,global,foo1,_parent, foo1,global,_parent, php-twig-2.12.5/tests/Fixtures/functions/include/with_variables.test000066400000000000000000000003461362457344700256740ustar00rootroot00000000000000--TEST-- "include" function accept variables --TEMPLATE-- {{ include("foo.twig", {'foo': 'bar'}) }} {{- include("foo.twig", vars) }} --TEMPLATE(foo.twig)-- {{ foo }} --DATA-- return ['vars' => ['foo' => 'bar']] --EXPECT-- bar bar php-twig-2.12.5/tests/Fixtures/functions/include_template_from_string.test000066400000000000000000000003631362457344700271740ustar00rootroot00000000000000--TEST-- "template_from_string" function works in an "include" --TEMPLATE-- {% set embed = '{% embed "embed.twig" %}{% endembed %}' %} {{ include(template_from_string(embed)) }} --TEMPLATE(embed.twig)-- Cool --DATA-- return [] --EXPECT-- Cool php-twig-2.12.5/tests/Fixtures/functions/magic_call.test000066400000000000000000000001421362457344700233130ustar00rootroot00000000000000--TEST-- __call calls --TEMPLATE-- {{ 'foo'|magic_call }} --DATA-- return [] --EXPECT-- magic_foo php-twig-2.12.5/tests/Fixtures/functions/magic_static_call.test000066400000000000000000000002441362457344700246650ustar00rootroot00000000000000--TEST-- __staticCall calls --TEMPLATE-- {{ 'foo'|magic_call_string }} {{ 'foo'|magic_call_array }} --DATA-- return [] --EXPECT-- static_magic_foo static_magic_foo php-twig-2.12.5/tests/Fixtures/functions/max.test000066400000000000000000000002731362457344700220320ustar00rootroot00000000000000--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 [] --EXPECT-- 5 5 two php-twig-2.12.5/tests/Fixtures/functions/min.test000066400000000000000000000002741362457344700220310ustar00rootroot00000000000000--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 [] --EXPECT-- 1 1 five php-twig-2.12.5/tests/Fixtures/functions/range.test000066400000000000000000000002011362457344700223300ustar00rootroot00000000000000--TEST-- "range" function --TEMPLATE-- {{ range(low=0+1, high=10+0, step=2)|join(',') }} --DATA-- return [] --EXPECT-- 1,3,5,7,9 php-twig-2.12.5/tests/Fixtures/functions/recursive_block_with_inheritance.test000066400000000000000000000021511362457344700300270ustar00rootroot00000000000000--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 ['item' => ['1', '2', ['3.1', ['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"
    php-twig-2.12.5/tests/Fixtures/functions/source.test000066400000000000000000000002511362457344700225410ustar00rootroot00000000000000--TEST-- "source" function --TEMPLATE-- FOO {{ source("foo.twig") }} BAR --TEMPLATE(foo.twig)-- {{ foo }}
    --DATA-- return [] --EXPECT-- FOO {{ foo }}
    BAR php-twig-2.12.5/tests/Fixtures/functions/special_chars.test000066400000000000000000000001411362457344700240370ustar00rootroot00000000000000--TEST-- "§" custom function --TEMPLATE-- {{ §('foo') }} --DATA-- return [] --EXPECT-- §foo§ php-twig-2.12.5/tests/Fixtures/functions/static_calls.test000066400000000000000000000002561362457344700237130ustar00rootroot00000000000000--TEST-- Functions as static method calls --TEMPLATE-- {{ static_call_string('foo') }} {{ static_call_array('foo') }} --DATA-- return ['foo' => 'foo'] --EXPECT-- *foo* *foo* php-twig-2.12.5/tests/Fixtures/functions/template_from_string.test000066400000000000000000000007031362457344700254670ustar00rootroot00000000000000--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 ['name' => 'Fabien', 'template' => "Hello {{ name }}"] --EXPECT-- Hello Fabien Hello Fabien Hello Fabien php-twig-2.12.5/tests/Fixtures/functions/template_from_string_error.test000066400000000000000000000004711362457344700267020ustar00rootroot00000000000000--TEST-- "template_from_string" function --TEMPLATE-- {% include template_from_string("{{ not a Twig template ", "foo.twig") %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Unclosed "variable" in "foo.twig (string template 4900163d56b1af4b704c6b0afee7f98ba53418ce7a93d37a3af1882735baf9cd)" at line 1. php-twig-2.12.5/tests/Fixtures/functions/undefined_block.test000066400000000000000000000006401362457344700243560ustar00rootroot00000000000000--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 [] --EXCEPTION-- Twig\Error\RuntimeError: Block "unknown" on template "base.twig" does not exist in "index.twig" at line 5. php-twig-2.12.5/tests/Fixtures/functions/undefined_block_deep.test000066400000000000000000000010561362457344700253550ustar00rootroot00000000000000--TEST-- "block" function with undefined block on deep inheritance --TEMPLATE-- {% extends "base.twig" %} {% block foo %} {{ parent() }} {{ block('unknown') }} {{ block('bar') }} {% endblock %} --TEMPLATE(base.twig)-- {% extends "layout.twig" %} {% block foo %}Foo{% endblock %} {% block bar %}Bar{% endblock %} --TEMPLATE(layout.twig)-- {% block foo %}Foo{% endblock %} {% block bar %}Bar{% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Block "unknown" on template "layout.twig" does not exist in "index.twig" at line 5. php-twig-2.12.5/tests/Fixtures/macros/000077500000000000000000000000001362457344700176165ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/macros/default_values.test000066400000000000000000000003211362457344700235160ustar00rootroot00000000000000--TEST-- macro --TEMPLATE-- {% from _self import test %} {% macro test(a, b = 'bar') -%} {{ a }}{{ b }} {%- endmacro %} {{ test('foo') }} {{ test('bar', 'foo') }} --DATA-- return [] --EXPECT-- foobar barfoo php-twig-2.12.5/tests/Fixtures/macros/nested_calls.test000066400000000000000000000003401362457344700231540ustar00rootroot00000000000000--TEST-- macro --TEMPLATE-- {% import _self as macros %} {% macro foo(data) %} {{ data }} {% endmacro %} {% macro bar() %}
    {% endmacro %} {{ macros.foo(macros.bar()) }} --DATA-- return [] --EXPECT--
    php-twig-2.12.5/tests/Fixtures/macros/reserved_variables.test000066400000000000000000000002641362457344700243700ustar00rootroot00000000000000--TEST-- macro --TEMPLATE-- {% from _self import test %} {% macro test(this) -%} {{ this }} {%- endmacro %} {{ test(this) }} --DATA-- return ['this' => 'foo'] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/macros/simple.test000066400000000000000000000005411362457344700220100ustar00rootroot00000000000000--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 [] --EXPECT-- a
    b
    a
    b
    1
    c
    1
    c
    php-twig-2.12.5/tests/Fixtures/macros/unknown_macro.test000066400000000000000000000003361362457344700234010ustar00rootroot00000000000000--TEST-- macro --TEMPLATE-- {% import _self as macros %} {{ macros.unknown() }} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Macro "unknown" is not defined in template "index.twig" in "index.twig" at line 4. php-twig-2.12.5/tests/Fixtures/macros/varargs.test000066400000000000000000000005661362457344700221730ustar00rootroot00000000000000--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 [] --EXPECT-- foo: bar, foobar foo, bar, foobar php-twig-2.12.5/tests/Fixtures/macros/varargs_argument.test000066400000000000000000000004301362457344700240630ustar00rootroot00000000000000--TEST-- macro with varargs argument --TEMPLATE-- {% macro test(varargs) %} {% endmacro %} --EXCEPTION-- Twig\Error\SyntaxError: The argument "varargs" in macro "test" cannot be defined because the variable "varargs" is reserved for arbitrary arguments in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/macros/with_filters.test000066400000000000000000000003271362457344700232240ustar00rootroot00000000000000--TEST-- macro with a filter --TEMPLATE-- {% import _self as test %} {% macro test() %} {% apply escape %}foo
    {% endapply %} {% endmacro %} {{ test.test() }} --DATA-- return [] --EXPECT-- foo<br /> php-twig-2.12.5/tests/Fixtures/regression/000077500000000000000000000000001362457344700205125ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/regression/block_names_unicity.test000066400000000000000000000004741362457344700254410ustar00rootroot00000000000000--TEST-- Block names are unique per template --TEMPLATE-- {% extends 'layout' %} {% block content -%} {% apply title -%} second {% endapply %} {% endblock %} --TEMPLATE(layout)-- {% apply title -%} first {% endapply %} {% block content %}{% endblock %} --DATA-- return [] --EXPECT-- First Second php-twig-2.12.5/tests/Fixtures/regression/combined_debug_info.test000066400000000000000000000005141362457344700253540ustar00rootroot00000000000000--TEST-- Exception with bad line number --TEMPLATE-- {% block content %} {{ foo }} {{ include("foo") }} {% endblock %} index --TEMPLATE(foo)-- foo {{ foo.bar }} --DATA-- return ['foo' => 'foo'] --EXCEPTION-- Twig\Error\RuntimeError: Impossible to access an attribute ("bar") on a string variable ("foo") in "foo" at line 3. php-twig-2.12.5/tests/Fixtures/regression/empty_token.test000066400000000000000000000001751362457344700237540ustar00rootroot00000000000000--TEST-- Twig outputs 0 nodes correctly --TEMPLATE-- {{ foo }}0{{ foo }} --DATA-- return ['foo' => 'foo'] --EXPECT-- foo0foo php-twig-2.12.5/tests/Fixtures/regression/issue_1143.test000066400000000000000000000007501362457344700232150ustar00rootroot00000000000000--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 = [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 ['object' => $object] --EXPECT-- house.region.s php-twig-2.12.5/tests/Fixtures/regression/multi_word_tests.test000066400000000000000000000003121362457344700250160ustar00rootroot00000000000000--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 [] --EXPECT-- no yes php-twig-2.12.5/tests/Fixtures/regression/simple_xml_element.test000066400000000000000000000007401362457344700252760ustar00rootroot00000000000000--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 ['images' => new \SimpleXMLElement('foobar')] --EXPECT-- Hello 'foo'! example 2 - foo - bar php-twig-2.12.5/tests/Fixtures/regression/strings_like_numbers.test000066400000000000000000000002461362457344700256450ustar00rootroot00000000000000--TEST-- Twig does not confuse strings with integers in getAttribute() --TEMPLATE-- {{ hash['2e2'] }} --DATA-- return ['hash' => ['2e2' => 'works']] --EXPECT-- works php-twig-2.12.5/tests/Fixtures/tags/000077500000000000000000000000001362457344700172705ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/apply/000077500000000000000000000000001362457344700204155ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/apply/basic.test000066400000000000000000000003001362457344700223700ustar00rootroot00000000000000--TEST-- "apply" tag applies a filter on its children --TEMPLATE-- {% apply upper %} Some text with a {{ var }} {% endapply %} --DATA-- return ['var' => 'var'] --EXPECT-- SOME TEXT WITH A VAR php-twig-2.12.5/tests/Fixtures/tags/apply/json_encode.test000066400000000000000000000002261362457344700236040ustar00rootroot00000000000000--TEST-- "apply" tag applies a filter on its children --TEMPLATE-- {% apply json_encode|raw %}test{% endapply %} --DATA-- return [] --EXPECT-- "test" php-twig-2.12.5/tests/Fixtures/tags/apply/multiple.test000066400000000000000000000002521362457344700231500ustar00rootroot00000000000000--TEST-- "apply" tags accept multiple chained filters --TEMPLATE-- {% apply lower|title %} {{ var }} {% endapply %} --DATA-- return ['var' => 'VAR'] --EXPECT-- Var php-twig-2.12.5/tests/Fixtures/tags/apply/nested.test000066400000000000000000000003571362457344700226050ustar00rootroot00000000000000--TEST-- "apply" tags can be nested at will --TEMPLATE-- {% apply lower|title %} {{ var }} {% apply upper %} {{ var }} {% endapply %} {{ var }} {% endapply %} --DATA-- return ['var' => 'var'] --EXPECT-- Var Var Var php-twig-2.12.5/tests/Fixtures/tags/apply/scope.test000066400000000000000000000004511362457344700224270ustar00rootroot00000000000000--TEST-- "apply" tag does not create a new scope --TEMPLATE-- {% set foo = 'baz' %} {% apply spaceless %} {% set foo = 'foo' %} {% set bar = 'bar' %} {% endapply %} {{ 'foo' == foo ? 'OK ' ~ foo : 'KO' }} {{ 'bar' == bar ? 'OK ' ~ bar : 'KO' }} --DATA-- return [] --EXPECT-- OK foo OK bar php-twig-2.12.5/tests/Fixtures/tags/apply/with_for_tag.test000066400000000000000000000003131362457344700237670ustar00rootroot00000000000000--TEST-- "apply" tag applies the filter on "for" tags --TEMPLATE-- {% apply upper %} {% for item in items %} {{ item }} {% endfor %} {% endapply %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- A B php-twig-2.12.5/tests/Fixtures/tags/apply/with_if_tag.test000066400000000000000000000005521362457344700236040ustar00rootroot00000000000000--TEST-- "apply" tag applies the filter on "if" tags --TEMPLATE-- {% apply 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 %} {% endapply %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- A, B B A php-twig-2.12.5/tests/Fixtures/tags/autoescape/000077500000000000000000000000001362457344700214215ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/autoescape/basic.test000066400000000000000000000006361362457344700234100ustar00rootroot00000000000000--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 ['var' => '
    '] --EXPECT-- <br />
    <br />




    php-twig-2.12.5/tests/Fixtures/tags/autoescape/blocks.test000066400000000000000000000003441362457344700236000ustar00rootroot00000000000000--TEST-- "autoescape" tag applies escaping on embedded blocks --TEMPLATE-- {% autoescape 'html' %} {% block foo %} {{ var }} {% endblock %} {% endautoescape %} --DATA-- return ['var' => '
    '] --EXPECT-- <br /> php-twig-2.12.5/tests/Fixtures/tags/autoescape/double_escaping.test000066400000000000000000000002671362457344700254520ustar00rootroot00000000000000--TEST-- "autoescape" tag does not double-escape --TEMPLATE-- {% autoescape 'html' %} {{ var|escape }} {% endautoescape %} --DATA-- return ['var' => '
    '] --EXPECT-- <br /> php-twig-2.12.5/tests/Fixtures/tags/autoescape/functions.test000066400000000000000000000015411362457344700243330ustar00rootroot00000000000000--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 [] --EXPECT-- autoescape false safe_br
    unsafe_br
    autoescape 'html' safe_br
    unsafe_br <br /> unsafe_br()|raw
    safe_br()|escape <br /> safe_br()|raw
    unsafe_br()|escape <br /> autoescape js safe_br \u003Cbr\u0020\/\u003E php-twig-2.12.5/tests/Fixtures/tags/autoescape/literal.test000066400000000000000000000035461362457344700237660ustar00rootroot00000000000000--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 }} {{ false ? "
    " : someVar }} {{ true ? someVar : "
    " }} {{ false ? someVar : "
    " }} 4. Nested conditionals with only literals {{ true ? (true ? "
    " : "
    ") : "\n" }} 5. Nested conditionals with a variable {{ true ? (true ? "
    " : someVar) : "\n" }} {{ true ? (false ? "
    " : someVar) : "\n" }} {{ true ? (true ? someVar : "
    ") : "\n" }} {{ true ? (false ? someVar : "
    ") : "\n" }} {{ false ? "\n" : (true ? someVar : "
    ") }} {{ false ? "\n" : (false ? someVar : "
    ") }} 6. Nested conditionals with a variable marked safe {{ true ? (true ? "
    " : someVar|raw) : "\n" }} {{ true ? (false ? "
    " : someVar|raw) : "\n" }} {{ true ? (true ? someVar|raw : "
    ") : "\n" }} {{ true ? (false ? someVar|raw : "
    ") : "\n" }} {{ false ? "\n" : (true ? someVar|raw : "
    ") }} {{ false ? "\n" : (false ? someVar|raw : "
    ") }} 7. Without then clause {{ "
    " ?: someVar }} {{ someFalseVar ?: "
    " }} 8. NullCoalesce {{ aaaa ?? "
    " }} {{ "
    " ?? someVar }} {% endautoescape %} --DATA-- return ['someVar' => '
    ', 'someFalseVar' => false] --EXPECT-- 1. Simple literal
    2. Conditional expression with only literals
    3. Conditional expression with a variable
    <br /> <br />
    4. Nested conditionals with only literals
    5. Nested conditionals with a variable
    <br /> <br />
    <br />
    6. Nested conditionals with a variable marked safe





    7. Without then clause

    8. NullCoalesce

    php-twig-2.12.5/tests/Fixtures/tags/autoescape/nested.test000066400000000000000000000007011362457344700236020ustar00rootroot00000000000000--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 ['var' => '
    '] --EXPECT-- <br /> <br />
    <br />
    <br /> <br /> php-twig-2.12.5/tests/Fixtures/tags/autoescape/objects.test000066400000000000000000000007131362457344700237540ustar00rootroot00000000000000--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 ['user' => new UserForAutoEscapeTest()] --EXPECT-- Fabien<br /> fabien<br /> Fabien<br /> php-twig-2.12.5/tests/Fixtures/tags/autoescape/raw.test000066400000000000000000000003041362457344700231100ustar00rootroot00000000000000--TEST-- "autoescape" tag does not escape when raw is used as a filter --TEMPLATE-- {% autoescape 'html' %} {{ var|raw }} {% endautoescape %} --DATA-- return ['var' => '
    '] --EXPECT--
    php-twig-2.12.5/tests/Fixtures/tags/autoescape/strategy.test000066400000000000000000000004131362457344700241620ustar00rootroot00000000000000--TEST-- "autoescape" tag accepts an escaping strategy --TEMPLATE-- {% autoescape 'js' %}{{ var }}{% endautoescape %} {% autoescape 'html' %}{{ var }}{% endautoescape %} --DATA-- return ['var' => '
    "'] --EXPECT-- \u003Cbr\u0020\/\u003E\u0022 <br />" php-twig-2.12.5/tests/Fixtures/tags/autoescape/type.test000066400000000000000000000027411362457344700233070ustar00rootroot00000000000000--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 ['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') php-twig-2.12.5/tests/Fixtures/tags/autoescape/with_filters.test000066400000000000000000000075201362457344700250310ustar00rootroot00000000000000--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 ['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 php-twig-2.12.5/tests/Fixtures/tags/autoescape/with_filters_arguments.test000066400000000000000000000007341362457344700271160ustar00rootroot00000000000000--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 ['var' => "\nTwig", 'sep' => '
    '] --EXPECT-- <Fabien>
    Twig <Fabien><br /> Twig <Fabien>
    Twig <Fabien>
    Twig <Fabien><br /> Twig php-twig-2.12.5/tests/Fixtures/tags/autoescape/with_pre_escape_filters.test000066400000000000000000000026441362457344700272210ustar00rootroot00000000000000--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 ['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 php-twig-2.12.5/tests/Fixtures/tags/autoescape/with_preserves_safety_filters.test000066400000000000000000000023571362457344700305050ustar00rootroot00000000000000--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 ['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 php-twig-2.12.5/tests/Fixtures/tags/block/000077500000000000000000000000001362457344700203625ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/block/basic.test000066400000000000000000000003171362457344700223450ustar00rootroot00000000000000--TEST-- "block" tag --TEMPLATE-- {% block title1 %}FOO{% endblock %} {% block title2 foo|lower %} --TEMPLATE(foo.twig)-- {% block content %}{% endblock %} --DATA-- return ['foo' => 'bar'] --EXPECT-- FOObar php-twig-2.12.5/tests/Fixtures/tags/block/block_unique_name.test000066400000000000000000000003701362457344700247430ustar00rootroot00000000000000--TEST-- "block" tag --TEMPLATE-- {% block content %} {% block content %} {% endblock %} {% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: The block 'content' has already been defined line 2 in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/tags/block/capturing_block.test000066400000000000000000000007161362457344700244350ustar00rootroot00000000000000--TEST-- capturing "block" tag --DEPRECATION-- The spaceless tag in "index.twig" at line 4 is deprecated since Twig 2.7, use the "spaceless" filter with the "apply" tag instead. --TEMPLATE-- {% set foo %}{% block foo %}FOO{% endblock %}{% endset %} {{ foo }} {% spaceless %} {% block bar %}

    Title

    {% endblock %} {% endspaceless %} {{ block('bar') }} --DATA-- return array() --EXPECT-- FOO

    Title

    Title

    php-twig-2.12.5/tests/Fixtures/tags/block/conditional_block.test000066400000000000000000000003101362457344700247320ustar00rootroot00000000000000--TEST-- conditional "block" tag --TEMPLATE-- {% if false %}{% block foo %}FOO{% endblock %}{% endif %} {% if true %}{% block bar %}BAR{% endblock %}{% endif %} --DATA-- return array() --EXPECT-- BAR php-twig-2.12.5/tests/Fixtures/tags/block/special_chars.test000066400000000000000000000001761362457344700240670ustar00rootroot00000000000000--TEST-- "§" special chars in a block name --TEMPLATE-- {% block § %} § {% endblock § %} --DATA-- return [] --EXPECT-- § php-twig-2.12.5/tests/Fixtures/tags/deprecated/000077500000000000000000000000001362457344700213705ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/deprecated/block.legacy.test000066400000000000000000000005621362457344700246310ustar00rootroot00000000000000--TEST-- Deprecating a block with "deprecated" tag --TEMPLATE-- {% use 'greeting.twig' %} {{ block('welcome') }} --TEMPLATE(greeting.twig)-- {% block welcome %} {% deprecated 'The "welcome" block is deprecated, use "hello" instead.' %} {{ block('hello') }} {% endblock %} {% block hello %} Hello Fabien {% endblock %} --DATA-- return [] --EXPECT-- Hello Fabien php-twig-2.12.5/tests/Fixtures/tags/deprecated/macro.legacy.test000066400000000000000000000006721362457344700246420ustar00rootroot00000000000000--TEST-- Deprecating a macro with "deprecated" tag --TEMPLATE-- {% import 'greeting.twig' as greeting %} {{ greeting.welcome('Fabien') }} --TEMPLATE(greeting.twig)-- {% macro welcome(name) %} {% deprecated 'The "welcome" macro is deprecated, use "hello" instead.' %} {% import _self as self %} {{ self.hello(name) }} {% endmacro %} {% macro hello(name) %} Hello {{ name }} {% endmacro %} --DATA-- return [] --EXPECT-- Hello Fabien php-twig-2.12.5/tests/Fixtures/tags/deprecated/template.legacy.test000066400000000000000000000004171362457344700253510ustar00rootroot00000000000000--TEST-- Deprecating a template with "deprecated" tag --TEMPLATE-- {% extends 'greeting.twig' %} {% deprecated 'The "index.twig" template is deprecated, use "greeting.twig" instead.' %} --TEMPLATE(greeting.twig)-- Hello Fabien --DATA-- return [] --EXPECT-- Hello Fabien php-twig-2.12.5/tests/Fixtures/tags/embed/000077500000000000000000000000001362457344700203445ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/embed/basic.test000066400000000000000000000005731362457344700223330ustar00rootroot00000000000000--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 [] --EXPECT-- FOO A block1 block1extended B block2 C BAR php-twig-2.12.5/tests/Fixtures/tags/embed/complex_dynamic_parent.test000066400000000000000000000006141362457344700257720ustar00rootroot00000000000000--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 ['foo' => 'foo'] --EXPECT-- FOO A block1 block1extended B block2 C BAR php-twig-2.12.5/tests/Fixtures/tags/embed/dynamic_parent.test000066400000000000000000000006071362457344700242450ustar00rootroot00000000000000--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 ['foo' => 'foo.twig'] --EXPECT-- FOO A block1 block1extended B block2 C BAR php-twig-2.12.5/tests/Fixtures/tags/embed/error_line.test000066400000000000000000000005031362457344700234030ustar00rootroot00000000000000--TEST-- "embed" tag --TEMPLATE(index.twig)-- FOO {% embed "foo.twig" %} {% block c1 %} {{ nothing }} {% endblock %} {% endembed %} BAR --TEMPLATE(foo.twig)-- {% block c1 %}{% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "nothing" does not exist in "index.twig" at line 5. php-twig-2.12.5/tests/Fixtures/tags/embed/multiple.test000066400000000000000000000010671362457344700231040ustar00rootroot00000000000000--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 [] --EXPECT-- FOO A block1 block1extended B block2 C A block1 block1extended B block2 C BAR php-twig-2.12.5/tests/Fixtures/tags/embed/nested.test000066400000000000000000000011071362457344700225260ustar00rootroot00000000000000--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 [] --EXPECT-- A block1 A block1 block1extended B block2 C B block2 C php-twig-2.12.5/tests/Fixtures/tags/embed/with_extends.test000066400000000000000000000014161362457344700237540ustar00rootroot00000000000000--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 [] --EXPECT-- A blockc1base blockc1baseextended blockc2base A block1 block1extended B block2 C blockc2base Bphp-twig-2.12.5/tests/Fixtures/tags/filter/000077500000000000000000000000001362457344700205555ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/filter/basic.legacy.test000066400000000000000000000004711362457344700240040ustar00rootroot00000000000000--TEST-- "filter" tag applies a filter on its children --DEPRECATION-- The "filter" tag in "index.twig" at line 2 is deprecated since Twig 2.9, use the "apply" tag instead. --TEMPLATE-- {% filter upper %} Some text with a {{ var }} {% endfilter %} --DATA-- return ['var' => 'var'] --EXPECT-- SOME TEXT WITH A VAR php-twig-2.12.5/tests/Fixtures/tags/filter/json_encode.legacy.test000066400000000000000000000004171362457344700252110ustar00rootroot00000000000000--TEST-- "filter" tag applies a filter on its children --DEPRECATION-- The "filter" tag in "index.twig" at line 2 is deprecated since Twig 2.9, use the "apply" tag instead. --TEMPLATE-- {% filter json_encode|raw %}test{% endfilter %} --DATA-- return [] --EXPECT-- "test" php-twig-2.12.5/tests/Fixtures/tags/filter/multiple.legacy.test000066400000000000000000000004431362457344700245550ustar00rootroot00000000000000--TEST-- "filter" tags accept multiple chained filters --DEPRECATION-- The "filter" tag in "index.twig" at line 2 is deprecated since Twig 2.9, use the "apply" tag instead. --TEMPLATE-- {% filter lower|title %} {{ var }} {% endfilter %} --DATA-- return ['var' => 'VAR'] --EXPECT-- Var php-twig-2.12.5/tests/Fixtures/tags/filter/nested.legacy.test000066400000000000000000000007201362457344700242020ustar00rootroot00000000000000--TEST-- "filter" tags can be nested at will --DEPRECATION-- The "filter" tag in "index.twig" at line 2 is deprecated since Twig 2.9, use the "apply" tag instead. The "filter" tag in "index.twig" at line 4 is deprecated since Twig 2.9, use the "apply" tag instead. --TEMPLATE-- {% filter lower|title %} {{ var }} {% filter upper %} {{ var }} {% endfilter %} {{ var }} {% endfilter %} --DATA-- return ['var' => 'var'] --EXPECT-- Var Var Var php-twig-2.12.5/tests/Fixtures/tags/filter/scope.legacy.test000066400000000000000000000005511362457344700240330ustar00rootroot00000000000000--TEST-- "scope" tag creates a new scope --DEPRECATION-- The "filter" tag in "index.twig" at line 2 is deprecated since Twig 2.9, use the "apply" tag instead. --TEMPLATE-- {% filter spaceless %} {% set item = 'foo' %} {% endfilter %} {{ item }} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "item" does not exist in "index.twig" at line 5. php-twig-2.12.5/tests/Fixtures/tags/filter/with_for_tag.legacy.test000066400000000000000000000005041362457344700253740ustar00rootroot00000000000000--TEST-- "filter" tag applies the filter on "for" tags --DEPRECATION-- The "filter" tag in "index.twig" at line 2 is deprecated since Twig 2.9, use the "apply" tag instead. --TEMPLATE-- {% filter upper %} {% for item in items %} {{ item }} {% endfor %} {% endfilter %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- A B php-twig-2.12.5/tests/Fixtures/tags/filter/with_if_tag.legacy.test000066400000000000000000000007431362457344700252110ustar00rootroot00000000000000--TEST-- "filter" tag applies the filter on "if" tags --DEPRECATION-- The "filter" tag in "index.twig" at line 2 is deprecated since Twig 2.9, use the "apply" tag instead. --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 ['items' => ['a', 'b']] --EXPECT-- A, B B A php-twig-2.12.5/tests/Fixtures/tags/for/000077500000000000000000000000001362457344700200565ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/for/condition.legacy.test000066400000000000000000000007721362457344700242160ustar00rootroot00000000000000--TEST-- "for" tag takes a condition --DEPRECATION-- Using an "if" condition on "for" tag in "index.twig" at line 2 is deprecated since Twig 2.10.0, use a "filter" filter or an "if" condition inside the "for" body instead (if your condition depends on a variable updated inside the loop). --TEMPLATE-- {% for i in 1..5 if i is odd -%} {{ loop.index }}.{{ i }}{{ foo.bar }} {% endfor %} --DATA-- return ['foo' => ['bar' => 'X']] --CONFIG-- return ['strict_variables' => false] --EXPECT-- 1.1X 2.3X 3.5X php-twig-2.12.5/tests/Fixtures/tags/for/context.test000066400000000000000000000004201362457344700224370ustar00rootroot00000000000000--TEST-- "for" tag keeps the context safe --TEMPLATE-- {% for item in items %} {% for item in items %} * {{ item }} {% endfor %} * {{ item }} {% endfor %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- * a * b * a * a * b * b php-twig-2.12.5/tests/Fixtures/tags/for/else.test000066400000000000000000000005161362457344700217110ustar00rootroot00000000000000--TEST-- "for" tag can use an "else" clause --TEMPLATE-- {% for item in items %} * {{ item }} {% else %} no item {% endfor %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- * a * b --DATA-- return ['items' => []] --EXPECT-- no item --DATA-- return [] --CONFIG-- return ['strict_variables' => false] --EXPECT-- no item php-twig-2.12.5/tests/Fixtures/tags/for/inner_variables.test000066400000000000000000000004411362457344700241210ustar00rootroot00000000000000--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 ['k' => 0] --EXPECT-- 0 1 1 1 2 1 3 2 4 2 5 2 php-twig-2.12.5/tests/Fixtures/tags/for/keys.test000066400000000000000000000002541362457344700217330ustar00rootroot00000000000000--TEST-- "for" tag can iterate over keys --TEMPLATE-- {% for key in items|keys %} * {{ key }} {% endfor %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- * 0 * 1 php-twig-2.12.5/tests/Fixtures/tags/for/keys_and_values.test000066400000000000000000000003071362457344700241330ustar00rootroot00000000000000--TEST-- "for" tag can iterate over keys and values --TEMPLATE-- {% for key, item in items %} * {{ key }}/{{ item }} {% endfor %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- * 0/a * 1/b php-twig-2.12.5/tests/Fixtures/tags/for/loop_context.test000066400000000000000000000005331362457344700234750ustar00rootroot00000000000000--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 ['items' => ['a', 'b']] --EXPECT-- * 1/0 * 2/1 * 1//2 * 2/1 * 1/0 * /1/2 php-twig-2.12.5/tests/Fixtures/tags/for/loop_context_local.test000066400000000000000000000003171362457344700246470ustar00rootroot00000000000000--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 ['items' => []] --EXPECT-- WORKS php-twig-2.12.5/tests/Fixtures/tags/for/loop_not_defined.test000066400000000000000000000004241362457344700242660ustar00rootroot00000000000000--TEST-- "for" tag --TEMPLATE-- {% for i, item in items if i > 0 %} {{ loop.last }} {% endfor %} --DATA-- return ['items' => ['a', 'b']] --EXCEPTION-- Twig\Error\SyntaxError: The "loop.last" variable is not defined when looping with a condition in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/tags/for/loop_not_defined_cond.test000066400000000000000000000003741362457344700252750ustar00rootroot00000000000000--TEST-- "for" tag --TEMPLATE-- {% for i, item in items if loop.last > 0 %} {% endfor %} --DATA-- return ['items' => ['a', 'b']] --EXCEPTION-- Twig\Error\SyntaxError: The "loop" variable cannot be used in a looping condition in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tags/for/nested_else.test000066400000000000000000000004431362457344700232520ustar00rootroot00000000000000--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 ['items' => ['a', 'b'], 'items1' => []] --EXPECT-- no a no b php-twig-2.12.5/tests/Fixtures/tags/for/objects.test000066400000000000000000000015301362457344700224070ustar00rootroot00000000000000--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 = ['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 ['items' => new ItemsIterator()] --EXPECT-- * bar * 1/0 * 1 * foo * 2/1 * * foo/bar * bar/foo * foo * bar php-twig-2.12.5/tests/Fixtures/tags/for/objects_countable.test000066400000000000000000000020451362457344700244450ustar00rootroot00000000000000--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 = ['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 ['items' => new ItemsIteratorCountable()] --EXPECT-- * bar * 1/0 * 2/1 * 1//2 * foo * 2/1 * 1/0 * /1/2 * foo/bar * bar/foo * foo * bar php-twig-2.12.5/tests/Fixtures/tags/for/recursive.test000066400000000000000000000005241362457344700227670ustar00rootroot00000000000000--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 ['items' => ['a' => ['a1', 'a2', 'a3'], 'b' => ['b1']]] --EXPECT-- * a (2): * a1 (3) * a2 (3) * a3 (3) * b (2): * b1 (1) php-twig-2.12.5/tests/Fixtures/tags/for/values.test000066400000000000000000000002551362457344700222600ustar00rootroot00000000000000--TEST-- "for" tag iterates over item values --TEMPLATE-- {% for item in items %} * {{ item }} {% endfor %} --DATA-- return ['items' => ['a', 'b']] --EXPECT-- * a * b php-twig-2.12.5/tests/Fixtures/tags/from.test000066400000000000000000000003671362457344700211420ustar00rootroot00000000000000--TEST-- global variables --TEMPLATE-- {% include "included.twig" %} {% from "included.twig" import foobar %} {{ foobar() }} --TEMPLATE(included.twig)-- {% macro foobar() %} called foobar {% endmacro %} --DATA-- return [] --EXPECT-- called foobar php-twig-2.12.5/tests/Fixtures/tags/if/000077500000000000000000000000001362457344700176665ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/if/basic.test000066400000000000000000000004241362457344700216500ustar00rootroot00000000000000--TEST-- "if" creates a condition --TEMPLATE-- {% if a is defined %} {{ a }} {% elseif b is defined %} {{ b }} {% else %} NOTHING {% endif %} --DATA-- return ['a' => 'a'] --EXPECT-- a --DATA-- return ['b' => 'b'] --EXPECT-- b --DATA-- return [] --EXPECT-- NOTHING php-twig-2.12.5/tests/Fixtures/tags/if/expression.test000066400000000000000000000004041362457344700227640ustar00rootroot00000000000000--TEST-- "if" takes an expression as a test --TEMPLATE-- {% if a < 2 %} A1 {% elseif a > 10 %} A2 {% else %} A3 {% endif %} --DATA-- return ['a' => 1] --EXPECT-- A1 --DATA-- return ['a' => 12] --EXPECT-- A2 --DATA-- return ['a' => 7] --EXPECT-- A3 php-twig-2.12.5/tests/Fixtures/tags/include/000077500000000000000000000000001362457344700207135ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/include/basic.test000066400000000000000000000002221362457344700226710ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- FOO {% include "foo.twig" %} BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return [] --EXPECT-- FOO FOOBAR BAR php-twig-2.12.5/tests/Fixtures/tags/include/expression.test000066400000000000000000000003151362457344700240120ustar00rootroot00000000000000--TEST-- "include" tag allows expressions for the template to include --TEMPLATE-- FOO {% include foo %} BAR --TEMPLATE(foo.twig)-- FOOBAR --DATA-- return ['foo' => 'foo.twig'] --EXPECT-- FOO FOOBAR BAR php-twig-2.12.5/tests/Fixtures/tags/include/ignore_missing.test000066400000000000000000000004051362457344700246270ustar00rootroot00000000000000--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 [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/include/ignore_missing_exists.test000066400000000000000000000004321362457344700262260ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- {% include "included.twig" ignore missing %} NOT DISPLAYED --TEMPLATE(included.twig)-- {% include "DOES NOT EXIST" %} --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "DOES NOT EXIST" is not defined in "included.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tags/include/include_missing_extends.test000066400000000000000000000005001362457344700265150ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- {% include ['bad.twig', 'good.twig'] ignore missing %} NOT DISPLAYED --TEMPLATE(bad.twig)-- {% extends 'DOES NOT EXIST' %} --TEMPLATE(good.twig)-- NOT DISPLAYED --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "DOES NOT EXIST" is not defined in "bad.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tags/include/missing.test000066400000000000000000000002641362457344700232670ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- {% include "foo.twig" %} --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "foo.twig" is not defined in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tags/include/missing_nested.test000066400000000000000000000005031362457344700246250ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- {% extends "base.twig" %} {% block content %} {{ parent() }} {% endblock %} --TEMPLATE(base.twig)-- {% block content %} {% include "foo.twig" %} {% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\LoaderError: Template "foo.twig" is not defined in "base.twig" at line 3. php-twig-2.12.5/tests/Fixtures/tags/include/only.test000066400000000000000000000011261362457344700225750ustar00rootroot00000000000000--TEST-- "include" tag accept variables and only --TEMPLATE-- {% include "foo.twig" %} {% include "foo.twig" only %} {% include "foo.twig" with vars1 %} {% include "foo.twig" with vars1 only %} {% include "foo.twig" with vars2 %} {% include "foo.twig" with vars2 only %} --TEMPLATE(foo.twig)-- {% for k, v in _context %}{{ k }},{% endfor %} --DATA-- return ['vars1' => ['foo1' => 'bar'], 'vars2' => new ArrayObject(['foo2' => 'bar'])] --EXPECT-- vars1,vars2,global,_parent, global,_parent, vars1,vars2,global,foo1,_parent, foo1,global,_parent, vars1,vars2,global,foo2,_parent, foo2,global,_parent, php-twig-2.12.5/tests/Fixtures/tags/include/template_instance.test000066400000000000000000000003021362457344700253060ustar00rootroot00000000000000--TEST-- "include" tag accepts \Twig\TemplateWrapper instance --TEMPLATE-- {% include foo %} FOO --TEMPLATE(foo.twig)-- BAR --DATA-- return ['foo' => $twig->load('foo.twig')] --EXPECT-- BAR FOO php-twig-2.12.5/tests/Fixtures/tags/include/templates_as_array.test000066400000000000000000000002631362457344700254740ustar00rootroot00000000000000--TEST-- "include" tag --TEMPLATE-- {% include ["foo.twig", "bar.twig"] %} {% include ["bar.twig", "foo.twig"] %} --TEMPLATE(foo.twig)-- foo --DATA-- return [] --EXPECT-- foo foo php-twig-2.12.5/tests/Fixtures/tags/include/with_variables.test000066400000000000000000000004761362457344700246260ustar00rootroot00000000000000--TEST-- "include" tag accept variables --TEMPLATE-- {% include "foo.twig" with {'foo': 'bar'} %} {% include "foo.twig" with vars1 %} {% include "foo.twig" with vars2 %} --TEMPLATE(foo.twig)-- {{ foo }} --DATA-- return ['vars1' => ['foo' => 'bar'], 'vars2' => new ArrayObject(['foo' => 'bar'])] --EXPECT-- bar bar bar php-twig-2.12.5/tests/Fixtures/tags/inheritance/000077500000000000000000000000001362457344700215615ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/inheritance/basic.test000066400000000000000000000003001362457344700235340ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends "foo.twig" %} {% block content %} FOO {% endblock %} --TEMPLATE(foo.twig)-- {% block content %}{% endblock %} --DATA-- return [] --EXPECT-- FOO php-twig-2.12.5/tests/Fixtures/tags/inheritance/block_expr.test000066400000000000000000000010711362457344700246110ustar00rootroot00000000000000--TEST-- block_expr --TEMPLATE-- {% extends "base.twig" %} {% block element -%} Element: {{- parent() -}} {% endblock %} --TEMPLATE(base.twig)-- {% block element -%}
    {%- if item.children is defined %} {%- for item in item.children %} {{- block('element') -}} {% endfor %} {%- endif -%}
    {%- endblock %} --DATA-- return [ 'item' => [ 'children' => [ null, null, ] ] ] --EXPECT-- Element:
    Element:
    Element:
    php-twig-2.12.5/tests/Fixtures/tags/inheritance/block_expr2.test000066400000000000000000000011561362457344700246770ustar00rootroot00000000000000--TEST-- block_expr2 --TEMPLATE-- {% extends "base2.twig" %} {% block element -%} Element: {{- parent() -}} {% endblock %} --TEMPLATE(base2.twig)-- {% extends "base.twig" %} --TEMPLATE(base.twig)-- {% block element -%}
    {%- if item.children is defined %} {%- for item in item.children %} {{- block('element') -}} {% endfor %} {%- endif -%}
    {%- endblock %} --DATA-- return [ 'item' => [ 'children' => [ null, null, ] ] ] --EXPECT-- Element:
    Element:
    Element:
    php-twig-2.12.5/tests/Fixtures/tags/inheritance/capturing_block.test000066400000000000000000000005351362457344700256330ustar00rootroot00000000000000--TEST-- capturing "block" tag with "extends" tag --TEMPLATE-- {% extends "layout.twig" %} {% set foo %} {%- block content %}FOO{% endblock %} {% endset %} {% block content1 %}BAR{{ foo }}{% endblock %} --TEMPLATE(layout.twig)-- {% block content %}{% endblock %} {% block content1 %}{% endblock %} --DATA-- return array() --EXPECT-- FOOBARFOO php-twig-2.12.5/tests/Fixtures/tags/inheritance/conditional.test000066400000000000000000000005121362457344700247630ustar00rootroot00000000000000--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 ['foo' => 'foo.twig', 'standalone' => true] --EXPECT-- FOOFOO php-twig-2.12.5/tests/Fixtures/tags/inheritance/conditional_block.legacy.test000066400000000000000000000006531362457344700274060ustar00rootroot00000000000000--TEST-- conditional "block" tag with "extends" tag --DEPRECATION-- Nesting a block definition under a non-capturing node in "index.twig" at line 5 is deprecated since Twig 2.5.0 and will become a syntax error in 3.0. --TEMPLATE-- {% extends "layout.twig" %} {% if false %} {% block content %}FOO{% endblock %} {% endif %} --TEMPLATE(layout.twig)-- {% block content %}{% endblock %} --DATA-- return array() --EXPECT-- FOO php-twig-2.12.5/tests/Fixtures/tags/inheritance/dynamic.test000066400000000000000000000003141362457344700241040ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends foo %} {% block content %} FOO {% endblock %} --TEMPLATE(foo.twig)-- {% block content %}{% endblock %} --DATA-- return ['foo' => 'foo.twig'] --EXPECT-- FOO php-twig-2.12.5/tests/Fixtures/tags/inheritance/empty.test000066400000000000000000000002331362457344700236160ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends "foo.twig" %} --TEMPLATE(foo.twig)-- {% block content %}FOO{% endblock %} --DATA-- return [] --EXPECT-- FOO php-twig-2.12.5/tests/Fixtures/tags/inheritance/extends_as_array.test000066400000000000000000000002531362457344700260150ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends ["foo.twig", "bar.twig"] %} --TEMPLATE(bar.twig)-- {% block content %} foo {% endblock %} --DATA-- return [] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/tags/inheritance/extends_as_array_with_empty_name.test000066400000000000000000000002431362457344700312650ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends ["", "bar.twig"] %} --TEMPLATE(bar.twig)-- {% block content %} foo {% endblock %} --DATA-- return [] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/tags/inheritance/extends_as_array_with_null_name.test000066400000000000000000000002451362457344700311030ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends [null, "bar.twig"] %} --TEMPLATE(bar.twig)-- {% block content %} foo {% endblock %} --DATA-- return [] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/tags/inheritance/extends_in_block.test000066400000000000000000000003361362457344700257760ustar00rootroot00000000000000--TEST-- "extends" tag in a block --TEMPLATE-- {% block foo %} {% extends "foo.twig" %} {% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Cannot use "extend" in a block in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/tags/inheritance/extends_in_macro.test000066400000000000000000000003401362457344700260000ustar00rootroot00000000000000--TEST-- "extends" tag in a macro --TEMPLATE-- {% macro foo() %} {% extends "foo.twig" %} {% endmacro %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Cannot use "extend" in a macro in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/tags/inheritance/multiple.test000066400000000000000000000005161362457344700243170ustar00rootroot00000000000000--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 [] --EXPECT-- base layout index php-twig-2.12.5/tests/Fixtures/tags/inheritance/multiple_dynamic.test000066400000000000000000000007111362457344700260200ustar00rootroot00000000000000--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 [] --EXPECT-- 1 parent 1 parent 2 parent php-twig-2.12.5/tests/Fixtures/tags/inheritance/nested_blocks.test000066400000000000000000000006071362457344700253040ustar00rootroot00000000000000--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 [] --EXPECT-- SUBSUBCONTENT php-twig-2.12.5/tests/Fixtures/tags/inheritance/nested_blocks_parent_only.test000066400000000000000000000003661362457344700277200ustar00rootroot00000000000000--TEST-- "block" tag --TEMPLATE-- {% block content %} CONTENT {%- block subcontent -%} SUBCONTENT {%- endblock -%} ENDCONTENT {% endblock %} --TEMPLATE(foo.twig)-- --DATA-- return [] --EXPECT-- CONTENTSUBCONTENTENDCONTENT php-twig-2.12.5/tests/Fixtures/tags/inheritance/nested_inheritance.test000066400000000000000000000004621362457344700263170ustar00rootroot00000000000000--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 [] --EXPECT-- INSIDE php-twig-2.12.5/tests/Fixtures/tags/inheritance/parent.test000066400000000000000000000003431362457344700237530ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends "foo.twig" %} {% block content %}{{ parent() }}FOO{{ parent() }}{% endblock %} --TEMPLATE(foo.twig)-- {% block content %}BAR{% endblock %} --DATA-- return [] --EXPECT-- BARFOOBAR php-twig-2.12.5/tests/Fixtures/tags/inheritance/parent_as_template_wrapper.test000066400000000000000000000004171362457344700300730ustar00rootroot00000000000000--TEST-- "extends" tag with a parent as a Twig_TemplateWrapper instance --TEMPLATE-- {% extends foo %} {% block content %}New{% endblock %} --TEMPLATE(foo.twig)-- {% block content %}Default{% endblock %} --DATA-- return ['foo' => $twig->load('foo.twig')] --EXPECT-- New php-twig-2.12.5/tests/Fixtures/tags/inheritance/parent_change.test000066400000000000000000000003451362457344700252620ustar00rootroot00000000000000--TEST-- "extends" tag --TEMPLATE-- {% extends foo ? 'foo.twig' : 'bar.twig' %} --TEMPLATE(foo.twig)-- FOO --TEMPLATE(bar.twig)-- BAR --DATA-- return ['foo' => true] --EXPECT-- FOO --DATA-- return ['foo' => false] --EXPECT-- BAR php-twig-2.12.5/tests/Fixtures/tags/inheritance/parent_isolation.test000066400000000000000000000007131362457344700260350ustar00rootroot00000000000000--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 [] --EXPECT-- Included Content Default Footer Footer php-twig-2.12.5/tests/Fixtures/tags/inheritance/parent_nested.test000066400000000000000000000005161362457344700253170ustar00rootroot00000000000000--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 [] --EXPECT-- INSIDE OVERRIDDEN BEFORE BAR AFTER php-twig-2.12.5/tests/Fixtures/tags/inheritance/parent_without_extends.test000066400000000000000000000003661362457344700272750ustar00rootroot00000000000000--TEST-- "parent" tag --TEMPLATE-- {% block content %} {{ parent() }} {% endblock %} --EXCEPTION-- Twig\Error\SyntaxError: Calling "parent" on a template that does not extend nor "use" another template is forbidden in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/tags/inheritance/parent_without_extends_but_traits.test000066400000000000000000000003151362457344700315270ustar00rootroot00000000000000--TEST-- "parent" tag --TEMPLATE-- {% use 'foo.twig' %} {% block content %} {{ parent() }} {% endblock %} --TEMPLATE(foo.twig)-- {% block content %}BAR{% endblock %} --DATA-- return [] --EXPECT-- BAR php-twig-2.12.5/tests/Fixtures/tags/inheritance/template_instance.test000066400000000000000000000004141362457344700261600ustar00rootroot00000000000000--TEST-- "extends" tag accepts Twig_Template instance --TEMPLATE-- {% extends foo %} {% block content %} {{ parent() }}FOO {% endblock %} --TEMPLATE(foo.twig)-- {% block content %}BAR{% endblock %} --DATA-- return ['foo' => $twig->load('foo.twig')] --EXPECT-- BARFOO php-twig-2.12.5/tests/Fixtures/tags/inheritance/use.test000066400000000000000000000017211362457344700232570ustar00rootroot00000000000000--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 [] --EXPECT-- content_parent content_use1 content_use2 content_use1_only content_use2_only php-twig-2.12.5/tests/Fixtures/tags/macro/000077500000000000000000000000001362457344700203715ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/macro/auto_import.test000066400000000000000000000003541362457344700236360ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {{ _self.hello('Fabien') }} {% macro hello(name) -%} Hello {{ _self.up(name) }} {% endmacro %} {% macro up(name) -%} {{ name|upper }} {% endmacro %} --DATA-- return [] --EXPECT-- Hello FABIEN php-twig-2.12.5/tests/Fixtures/tags/macro/auto_import_blocks.test000066400000000000000000000004231362457344700251700ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% block content %} {{ _self.hello('Fabien') }} {% endblock %} {% macro hello(name) -%} Hello {{ _self.up(name) }} {% endmacro %} {% macro up(name) -%} {{ name|upper }} {% endmacro %} --DATA-- return [] --EXPECT-- Hello FABIEN php-twig-2.12.5/tests/Fixtures/tags/macro/auto_import_without_blocks.test000066400000000000000000000003701362457344700267540ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% import 'macros' as macro %} {{ macro.foo() }} --TEMPLATE(macros)-- {% macro foo() %} foo {{- _self.bar() }} {% endmacro %} {% macro bar() -%} bar {% endmacro %} --DATA-- return [] --EXPECT-- foobar php-twig-2.12.5/tests/Fixtures/tags/macro/basic.test000066400000000000000000000007401362457344700223540ustar00rootroot00000000000000--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 [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/endmacro_name.test000066400000000000000000000003631362457344700240640ustar00rootroot00000000000000--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 [] --EXPECT-- foo bar php-twig-2.12.5/tests/Fixtures/tags/macro/external.test000066400000000000000000000007741362457344700231240ustar00rootroot00000000000000--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 [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/from.test000066400000000000000000000005341362457344700222370ustar00rootroot00000000000000--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 [] --EXPECT-- foofoo foofoo barfoo php-twig-2.12.5/tests/Fixtures/tags/macro/from_embed_with_global_macro.test000066400000000000000000000006321362457344700271260ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% from _self import input %} {% embed 'embed' %} {% block foo %} {{ input("username") }} {% endblock %} {% endembed %} {% macro input(name) -%} {% endmacro %} --TEMPLATE(embed)-- {% block foo %} {% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Unknown "input" function in "index.twig" at line 6. php-twig-2.12.5/tests/Fixtures/tags/macro/from_in_block_is_local.test000066400000000000000000000005411362457344700257420ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% block foo %} {%- from _self import input as linput %} {% endblock %} {% block bar %} {{- linput('username') }} {% endblock %} {% macro input(name) -%} {% endmacro %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Unknown "linput" function in "index.twig" at line 7. php-twig-2.12.5/tests/Fixtures/tags/macro/from_local_override.test000066400000000000000000000007561362457344700253160ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {%- from _self import input %} {% block foo %} {%- from "macros" import input %} {{- input('username') }} {% endblock %} {% block bar %} {{- input('username') }} {% endblock %} {% macro input(name) -%} {% endmacro %} --TEMPLATE(macros)-- {% macro input(name) %} {% endmacro %} --DATA-- return [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/from_macro_in_a_macro.test000066400000000000000000000003511362457344700255640ustar00rootroot00000000000000--TEST-- "from" tag with syntax error --TEMPLATE-- {% from _self import another, foo %} {{ foo() }} {% macro foo() %} {{ another() }} {% endmacro %} {% macro another() %} OK {% endmacro %} --DATA-- return [] --EXPECT-- OK php-twig-2.12.5/tests/Fixtures/tags/macro/from_macros_in_parent.test000066400000000000000000000003421362457344700256370ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% from "macros" import hello %} {{ hello() }} --TEMPLATE(macros)-- {% extends "parent" %} --TEMPLATE(parent)-- {% macro hello() %} Test {% endmacro %} --DATA-- return [] --EXPECT-- Test php-twig-2.12.5/tests/Fixtures/tags/macro/from_nested_blocks.test000066400000000000000000000005551362457344700251410ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% block foo %} {%- from _self import input as linput %} {% block bar %} {{- linput('username') }} {% endblock %} {% endblock %} {% macro input(name) -%} {% endmacro %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Unknown "linput" function in "index.twig" at line 6. php-twig-2.12.5/tests/Fixtures/tags/macro/from_nested_blocks_with_global_macro.test000066400000000000000000000004461362457344700306740ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {%- from _self import input %} {% block foo %} {% block bar %} {{- input('username') }} {% endblock %} {% endblock %} {% macro input(name) -%} {% endmacro %} --DATA-- return [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/from_recursive.test000066400000000000000000000004411362457344700243230ustar00rootroot00000000000000--TEST-- "import" tag --TEMPLATE-- {% from _self import recursive_macro %} {{ recursive_macro(10) }} {% macro recursive_macro(n) %} {% if n > 0 %} {{- recursive_macro(n - 1) -}} {% endif %} {{- n }} {% endmacro %} --DATA-- return [] --EXPECT-- 0 1 2 3 4 5 6 7 8 9 10 php-twig-2.12.5/tests/Fixtures/tags/macro/from_self_parent.test000066400000000000000000000004071362457344700246200ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% extends "parent" %} {% block test %} {{ _self.hello() }} {% endblock test %} --TEMPLATE(parent)-- {% block test %} Hello {% endblock test %} {% macro hello() %} Test {% endmacro %} --DATA-- return [] --EXPECT-- Test php-twig-2.12.5/tests/Fixtures/tags/macro/from_syntax_error.test000066400000000000000000000003571362457344700250610ustar00rootroot00000000000000--TEST-- "from" tag with syntax error --TEMPLATE-- {% from 'forms.twig' %} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Unexpected token "end of statement block" ("name" expected with value "import") in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tags/macro/global.test000066400000000000000000000003671362457344700225400ustar00rootroot00000000000000--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 [] --EXPECT-- fooglobal fooglobal php-twig-2.12.5/tests/Fixtures/tags/macro/import_and_blocks.test000066400000000000000000000012531362457344700247640ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% import _self as macros %} {% from _self import input %} {% block foo %} {{- macros.input('username') }} {{- input('username') }} {%- import _self as lmacros %} {%- from _self import input as linput %} {{- lmacros.input('username') }} {{- linput('username') }} {% endblock %} {% block bar %} {{- macros.input('username') }} {{- input('username') }} {% endblock %} {% macro input(name) -%} {% endmacro %} --DATA-- return [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/import_embed_with_global_macro.test000066400000000000000000000006511362457344700274760ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% import _self as macros %} {% embed 'embed' %} {% block foo %} {{ macros.input("username") }} {% endblock %} {% endembed %} {% macro input(name) -%} {% endmacro %} --TEMPLATE(embed)-- {% block foo %} {% endblock %} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "macros" does not exist in "index.twig" at line 6. php-twig-2.12.5/tests/Fixtures/tags/macro/import_from_string_template.test000066400000000000000000000003231362457344700271060ustar00rootroot00000000000000--TEST-- "import" tag with a template as string --TEMPLATE-- {% import template_from_string("{% macro test() %}ok{% endmacro %}") as m %} {{ m.test() }} --TEMPLATE(forms.twig)-- --DATA-- return [] --EXPECT-- ok php-twig-2.12.5/tests/Fixtures/tags/macro/import_in_block_is_local.test000066400000000000000000000005471362457344700263170ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% block foo %} {%- import _self as lmacros %} {% endblock %} {% block bar %} {{- lmacros.input('username') }} {% endblock %} {% macro input(name) -%} {% endmacro %} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "lmacros" does not exist in "index.twig" at line 7. php-twig-2.12.5/tests/Fixtures/tags/macro/import_local_override.test000066400000000000000000000007721362457344700256630ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {%- import _self as macros %} {% block foo %} {%- import "macros" as macros %} {{- macros.input('username') }} {% endblock %} {% block bar %} {{- macros.input('username') }} {% endblock %} {% macro input(name) -%} {% endmacro %} --TEMPLATE(macros)-- {% macro input(name) %} {% endmacro %} --DATA-- return [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/import_macro_in_a_macro.test000066400000000000000000000003501362457344700261320ustar00rootroot00000000000000--TEST-- "import" tag with syntax error --TEMPLATE-- {% import _self as foo %} {{ foo.foo() }} {% macro foo() %} {{ foo.another() }} {% endmacro %} {% macro another() %} OK {% endmacro %} --DATA-- return [] --EXPECT-- OK php-twig-2.12.5/tests/Fixtures/tags/macro/import_macros_in_parent.test000066400000000000000000000003361362457344700262110ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% import "macros" as m %} {{ m.hello() }} --TEMPLATE(macros)-- {% extends "parent" %} --TEMPLATE(parent)-- {% macro hello() %} Test {% endmacro %} --DATA-- return [] --EXPECT-- Test php-twig-2.12.5/tests/Fixtures/tags/macro/import_nested_blocks.test000066400000000000000000000005631362457344700255070ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% block foo %} {%- import _self as lmacros %} {% block bar %} {{- lmacros.input('username') }} {% endblock %} {% endblock %} {% macro input(name) -%} {% endmacro %} --DATA-- return [] --EXCEPTION-- Twig\Error\RuntimeError: Variable "lmacros" does not exist in "index.twig" at line 6. php-twig-2.12.5/tests/Fixtures/tags/macro/import_nested_blocks_with_global_macro.test000066400000000000000000000004541362457344700312420ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {%- import _self as macros %} {% block foo %} {% block bar %} {{- macros.input('username') }} {% endblock %} {% endblock %} {% macro input(name) -%} {% endmacro %} --DATA-- return [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/import_same_parent_and_child.test000066400000000000000000000006701362457344700271520ustar00rootroot00000000000000--TEST-- "import" tag --TEMPLATE-- {% extends "parent" %} {% macro anotherThing() -%} Do it too {% endmacro %} {% import _self as macros %} {% block content %} {{ parent() }} {{ macros.anotherThing() }} {% endblock %} --TEMPLATE(parent)-- {% macro thing() %} Do it {% endmacro %} {% import _self as macros %} {% block content %} {{ macros.thing() }} {% endblock %} --DATA-- return [] --EXPECT-- Do it Do it too php-twig-2.12.5/tests/Fixtures/tags/macro/import_self_parent.test000066400000000000000000000004671362457344700251750ustar00rootroot00000000000000--TEST-- "macro" tag --TEMPLATE-- {% extends "parent" %} {% import _self as me %} {% block test %} {{ me.hello() }} {% endblock test %} --TEMPLATE(parent)-- {% import _self as me %} {% block test %} Hello {% endblock test %} {% macro hello() %} Test {% endmacro %} --DATA-- return [] --EXPECT-- Test php-twig-2.12.5/tests/Fixtures/tags/macro/import_syntax_error.test000066400000000000000000000004071362457344700254240ustar00rootroot00000000000000--TEST-- "import" tag with reserved name --TEMPLATE-- {% import 'forms.twig' %} {{ macros.parent() }} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: Unexpected token "end of statement block" ("name" expected with value "as") in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tags/macro/self_import.test000066400000000000000000000007351362457344700236220ustar00rootroot00000000000000--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 [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/macro/special_chars.test000066400000000000000000000002721362457344700240730ustar00rootroot00000000000000--TEST-- "§" as a macro name --TEMPLATE-- {% import _self as macros %} {{ macros.§('foo') }} {% macro §(foo) %} §{{ foo }}§ {% endmacro %} --DATA-- return [] --EXPECT-- §foo§ php-twig-2.12.5/tests/Fixtures/tags/macro/super_globals.test000066400000000000000000000003021362457344700241260ustar00rootroot00000000000000--TEST-- Super globals as macro arguments --TEMPLATE-- {% import _self as macros %} {{ macros.foo('foo') }} {% macro foo(GET) %} {{ GET }} {% endmacro %} --DATA-- return [] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/tags/sandbox/000077500000000000000000000000001362457344700207265ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/sandbox/array.test000066400000000000000000000004131362457344700227430ustar00rootroot00000000000000--TEST-- sandbox tag --TEMPLATE-- {%- sandbox %} {%- include "foo.twig" %} {%- endsandbox %} --TEMPLATE(foo.twig)-- {{ [a][0] }} {{ dump([a][0]) }} --DATA-- return ['a' => 'b'] --CONFIG-- return ['autoescape' => false, 'debug' => true] --EXPECT-- b string(1) "b" php-twig-2.12.5/tests/Fixtures/tags/sandbox/not_valid1.test000066400000000000000000000003761362457344700236750ustar00rootroot00000000000000--TEST-- sandbox tag --TEMPLATE-- {%- sandbox %} {%- include "foo.twig" %} a {%- endsandbox %} --TEMPLATE(foo.twig)-- foo --EXCEPTION-- Twig\Error\SyntaxError: Only "include" tags are allowed within a "sandbox" section in "index.twig" at line 4. php-twig-2.12.5/tests/Fixtures/tags/sandbox/not_valid2.test000066400000000000000000000004721362457344700236730ustar00rootroot00000000000000--TEST-- sandbox tag --TEMPLATE-- {%- sandbox %} {%- include "foo.twig" %} {% if 1 %} {%- include "foo.twig" %} {% endif %} {%- endsandbox %} --TEMPLATE(foo.twig)-- foo --EXCEPTION-- Twig\Error\SyntaxError: Only "include" tags are allowed within a "sandbox" section in "index.twig" at line 5. php-twig-2.12.5/tests/Fixtures/tags/sandbox/simple.test000066400000000000000000000005001362457344700231130ustar00rootroot00000000000000--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 [] --EXPECT-- foo foo foo foo php-twig-2.12.5/tests/Fixtures/tags/set/000077500000000000000000000000001362457344700200635ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/set/basic.test000066400000000000000000000003311362457344700220420ustar00rootroot00000000000000--TEST-- "set" tag --TEMPLATE-- {% set foo = 'foo' %} {% set bar = 'foo
    ' %} {{ foo }} {{ bar }} {% set foo, bar = 'foo', 'bar' %} {{ foo }}{{ bar }} --DATA-- return [] --EXPECT-- foo foo<br /> foobar php-twig-2.12.5/tests/Fixtures/tags/set/capture-empty.test000066400000000000000000000002111362457344700235550ustar00rootroot00000000000000--TEST-- "set" tag block empty capture --TEMPLATE-- {% set foo %}{% endset %} {% if foo %}FAIL{% endif %} --DATA-- return [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/set/capture.test000066400000000000000000000002201362457344700224210ustar00rootroot00000000000000--TEST-- "set" tag block capture --TEMPLATE-- {% set foo %}f
    o
    o{% endset %} {{ foo }} --DATA-- return [] --EXPECT-- f
    o
    o php-twig-2.12.5/tests/Fixtures/tags/set/capture_scope.test000066400000000000000000000002141362457344700236150ustar00rootroot00000000000000--TEST-- "set" tag block capture --TEMPLATE-- {% set foo %}{{ foo }}{% endset %} {{ foo }} --DATA-- return ['foo' => 'foo'] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/tags/set/expression.test000066400000000000000000000002231362457344700231600ustar00rootroot00000000000000--TEST-- "set" tag --TEMPLATE-- {% set foo, bar = 'foo' ~ 'bar', 'bar' ~ 'foo' %} {{ foo }} {{ bar }} --DATA-- return [] --EXPECT-- foobar barfoo php-twig-2.12.5/tests/Fixtures/tags/set/inheritance.test000066400000000000000000000005521362457344700232570ustar00rootroot00000000000000--TEST-- "set" tag with inheritance --TEMPLATE-- {% extends "layout.twig" %} {% set bar %}bar{% endset %} {% block var_from_child %} {{- bar -}} {% endblock %} --TEMPLATE(layout.twig)-- {% set foo %}foo{% endset %} {% block var_from_layout %} {{- foo -}} {% endblock %} {% block var_from_child %} {% endblock %} --DATA-- return [] --EXPECT-- foo bar php-twig-2.12.5/tests/Fixtures/tags/set/inheritance_overriding.test000066400000000000000000000005521362457344700255070ustar00rootroot00000000000000--TEST-- "set" tag with inheritance --TEMPLATE-- {% extends "layout.twig" %} {% set foo %}bar{% endset %} {% block var_from_child %} {{- foo -}} {% endblock %} --TEMPLATE(layout.twig)-- {% set foo %}foo{% endset %} {% block var_from_layout %} {{- foo -}} {% endblock %} {% block var_from_child %} {% endblock %} --DATA-- return [] --EXPECT-- foo foo php-twig-2.12.5/tests/Fixtures/tags/set/mutating.test000066400000000000000000000002611362457344700226130ustar00rootroot00000000000000--TEST-- "set" tag --TEMPLATE-- {% set foo = "foo" %} {% set bar %} {%- set foo = "bar" -%} bar {% endset %} {{ foo }} {{ bar }} --DATA-- return [] --EXPECT-- bar bar php-twig-2.12.5/tests/Fixtures/tags/spaceless/000077500000000000000000000000001362457344700212525ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/spaceless/root_level_in_child.legacy.test000066400000000000000000000015071362457344700274240ustar00rootroot00000000000000--TEST-- "spaceless" tag in the root level of a child template --DEPRECATION-- The spaceless tag in "index.twig" at line 3 is deprecated since Twig 2.7, use the "spaceless" filter with the "apply" tag instead. Using the spaceless tag at the root level of a child template in "index.twig" at line 3 is deprecated since Twig 2.5.0 and will become a syntax error in 3.0. Nesting a block definition under a non-capturing node in "index.twig" at line 4 is deprecated since Twig 2.5.0 and will become a syntax error in 3.0. --TEMPLATE-- {% extends "layout.twig" %} {% spaceless %} {% block content %}

    Title

    {% endblock %} {% endspaceless %} --TEMPLATE(layout.twig)-- {% block content %}FOO{% endblock %} --DATA-- return array() --EXPECT--

    Title

    php-twig-2.12.5/tests/Fixtures/tags/spaceless/simple.test000066400000000000000000000005471362457344700234520ustar00rootroot00000000000000--TEST-- "spaceless" tag removes whites between HTML tags --DEPRECATION-- The spaceless tag in "index.twig" at line 2 is deprecated since Twig 2.7, use the "spaceless" filter with the "apply" tag instead. --TEMPLATE-- {% spaceless %}
    foo
    {% endspaceless %} --DATA-- return [] --EXPECT--
    foo
    php-twig-2.12.5/tests/Fixtures/tags/special_chars.test000066400000000000000000000001201362457344700227620ustar00rootroot00000000000000--TEST-- "§" custom tag --TEMPLATE-- {% § %} --DATA-- return [] --EXPECT-- § php-twig-2.12.5/tests/Fixtures/tags/use/000077500000000000000000000000001362457344700200645ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/use/aliases.test000066400000000000000000000002661362457344700224120ustar00rootroot00000000000000--TEST-- "use" tag --TEMPLATE-- {% use "blocks.twig" with content as foo %} {{ block('foo') }} --TEMPLATE(blocks.twig)-- {% block content 'foo' %} --DATA-- return [] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/tags/use/basic.test000066400000000000000000000002461362457344700220500ustar00rootroot00000000000000--TEST-- "use" tag --TEMPLATE-- {% use "blocks.twig" %} {{ block('content') }} --TEMPLATE(blocks.twig)-- {% block content 'foo' %} --DATA-- return [] --EXPECT-- foo php-twig-2.12.5/tests/Fixtures/tags/use/deep.test000066400000000000000000000005011362457344700216760ustar00rootroot00000000000000--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 [] --EXPECT-- foo foo bar php-twig-2.12.5/tests/Fixtures/tags/use/deep_empty.test000066400000000000000000000002261362457344700231200ustar00rootroot00000000000000--TEST-- "use" tag --TEMPLATE-- {% use "foo.twig" %} --TEMPLATE(foo.twig)-- {% use "bar.twig" %} --TEMPLATE(bar.twig)-- --DATA-- return [] --EXPECT-- php-twig-2.12.5/tests/Fixtures/tags/use/inheritance.test000066400000000000000000000011321362457344700232530ustar00rootroot00000000000000--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 [] --EXPECT--
    overridden sub_container
    php-twig-2.12.5/tests/Fixtures/tags/use/inheritance2.test000066400000000000000000000011311362457344700233340ustar00rootroot00000000000000--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 [] --EXPECT--
    overridden sub_container
    php-twig-2.12.5/tests/Fixtures/tags/use/multiple.test000066400000000000000000000005001362457344700226130ustar00rootroot00000000000000--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 [] --EXPECT-- bar foo bar php-twig-2.12.5/tests/Fixtures/tags/use/multiple_aliases.test000066400000000000000000000005731362457344700243260ustar00rootroot00000000000000--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 [] --EXPECT-- bar foo bar foo php-twig-2.12.5/tests/Fixtures/tags/use/parent_block.test000066400000000000000000000011501362457344700234250ustar00rootroot00000000000000--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 [] --EXPECT-- Content of block Content of block (first override) Content of block (second override) php-twig-2.12.5/tests/Fixtures/tags/use/parent_block2.test000066400000000000000000000010171362457344700235110ustar00rootroot00000000000000--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 [] --EXPECT-- Content of block Content of block (first override) Content of block (second override) php-twig-2.12.5/tests/Fixtures/tags/use/parent_block3.test000066400000000000000000000014671362457344700235230ustar00rootroot00000000000000--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 [] --EXPECT-- Content of foo Content of foo (first override) Content of foo (second override) Content of bar Content of bar (second override) php-twig-2.12.5/tests/Fixtures/tags/use/use_with_parent.test000066400000000000000000000005631362457344700241710ustar00rootroot00000000000000--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 [] --EXPECT-- PARENT CHILD BLOCK php-twig-2.12.5/tests/Fixtures/tags/verbatim/000077500000000000000000000000001362457344700211015ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/verbatim/basic.test000066400000000000000000000001701362457344700230610ustar00rootroot00000000000000--TEST-- "verbatim" tag --TEMPLATE-- {% verbatim %} {{ foo }} {% endverbatim %} --DATA-- return [] --EXPECT-- {{ foo }} php-twig-2.12.5/tests/Fixtures/tags/verbatim/whitespace_control.test000066400000000000000000000007631362457344700257040ustar00rootroot00000000000000--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 [] --EXPECT-- 1*** {{ 'bla' }} 1*** 2***{{ 'bla' }} 2*** 3***{{ 'bla' }} 3*** 4***{{ 'bla' }} 4*** 5***{{ 'bla' }}5*** php-twig-2.12.5/tests/Fixtures/tags/with/000077500000000000000000000000001362457344700202435ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tags/with/basic.test000066400000000000000000000003101362457344700222170ustar00rootroot00000000000000--TEST-- "with" tag --TEMPLATE-- {% with %} {% set bar = 'BAZ' %} {{ foo }}{{ bar }} {% endwith %} {{ foo }}{{ bar }} --DATA-- return ['foo' => 'foo', 'bar' => 'bar'] --EXPECT-- fooBAZ foobar php-twig-2.12.5/tests/Fixtures/tags/with/expression.test000066400000000000000000000002551362457344700233450ustar00rootroot00000000000000--TEST-- "with" tag with expression --TEMPLATE-- {% with {foo: 'foo', bar: 'BAZ'} %} {{ foo }}{{ bar }} {% endwith %} --DATA-- return ['foo' => 'baz'] --EXPECT-- fooBAZ php-twig-2.12.5/tests/Fixtures/tags/with/globals.test000066400000000000000000000001701362457344700225650ustar00rootroot00000000000000--TEST-- "with" tag --TEMPLATE-- {% with [] only %} {{ global }} {% endwith %} --DATA-- return [] --EXPECT-- global php-twig-2.12.5/tests/Fixtures/tags/with/iterable.test000066400000000000000000000003221362457344700227300ustar00rootroot00000000000000--TEST-- "with" tag with an iterable expression --TEMPLATE-- {% with vars %} {{ foo }}{{ bar }} {% endwith %} --DATA-- return ['vars' => new ArrayObject(['foo' => 'baz', 'bar' => 'qux'])] --EXPECT-- bazqux php-twig-2.12.5/tests/Fixtures/tags/with/nested.test000066400000000000000000000003751362457344700224330ustar00rootroot00000000000000--TEST-- nested "with" tags --TEMPLATE-- {% set foo, bar = 'foo', 'bar' %} {% with {bar: 'BAZ'} %} {% with {foo: 'FOO'} %} {{ foo }}{{ bar }} {% endwith %} {% endwith %} {{ foo }}{{ bar }} --DATA-- return [] --EXPECT-- FOOBAZ foobar php-twig-2.12.5/tests/Fixtures/tags/with/with_no_hash.test000066400000000000000000000004261362457344700236200ustar00rootroot00000000000000--TEST-- "with" tag with an expression that is not a hash --TEMPLATE-- {% with vars %} {{ foo }}{{ bar }} {% endwith %} --DATA-- return ['vars' => 'no-hash'] --EXCEPTION-- Twig\Error\RuntimeError: Variables passed to the "with" tag must be a hash in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tags/with/with_only.test000066400000000000000000000004421362457344700231600ustar00rootroot00000000000000--TEST-- "with" tag with expression and only --TEMPLATE-- {% with {foo: 'foo', bar: 'BAZ'} only %} {{ foo }}{{ bar }}{{ baz }} {% endwith %} --DATA-- return ['foo' => 'baz', 'baz' => 'baz'] --EXCEPTION-- Twig\Error\RuntimeError: Variable "baz" does not exist in "index.twig" at line 3. php-twig-2.12.5/tests/Fixtures/tests/000077500000000000000000000000001362457344700174745ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/tests/array.test000066400000000000000000000005201362457344700215100ustar00rootroot00000000000000--TEST-- array index test --TEMPLATE-- {% for key, value in days %} {{ key }} {% endfor %} --DATA-- return ['days' => [ 1 => ['money' => 9], 2 => ['money' => 21], 3 => ['money' => 38], 4 => ['money' => 6], 18 => ['money' => 6], 19 => ['money' => 3], 31 => ['money' => 11], ]] --EXPECT-- 1 2 3 4 18 19 31 php-twig-2.12.5/tests/Fixtures/tests/constant.test000066400000000000000000000006041362457344700222260ustar00rootroot00000000000000--TEST-- "const" test --TEMPLATE-- {{ 8 is constant('E_NOTICE') ? 'ok' : 'no' }} {{ 'bar' is constant('Twig\\Tests\\TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} {{ value is constant('Twig\\Tests\\TwigTestFoo::BAR_NAME') ? 'ok' : 'no' }} {{ 2 is constant('ARRAY_AS_PROPS', object) ? 'ok' : 'no' }} --DATA-- return ['value' => 'bar', 'object' => new \ArrayObject(['hi'])] --EXPECT-- ok ok ok okphp-twig-2.12.5/tests/Fixtures/tests/defined.test000066400000000000000000000057151362457344700220030ustar00rootroot00000000000000--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 [ 'definedVar' => 'defined', 'zeroVar' => 0, 'nullVar' => null, 'nested' => [ 'definedVar' => 'defined', 'zeroVar' => 0, 'nullVar' => null, 'definedArray' => [0], ], 'object' => new Twig\Tests\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 [ 'definedVar' => 'defined', 'zeroVar' => 0, 'nullVar' => null, 'nested' => [ 'definedVar' => 'defined', 'zeroVar' => 0, 'nullVar' => null, 'definedArray' => [0], ], 'object' => new Twig\Tests\TwigTestFoo(), ] --CONFIG-- return ['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 php-twig-2.12.5/tests/Fixtures/tests/defined_for_attribute.test000066400000000000000000000013601362457344700247240ustar00rootroot00000000000000--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 [ 'nested' => [ 'definedVar' => 'defined', ], 'definedVarName' => 'definedVar', 'undefinedVarName' => 'undefinedVar', ] --EXPECT-- ok ok ok ok --DATA-- return [ 'nested' => [ 'definedVar' => 'defined', ], 'definedVarName' => 'definedVar', 'undefinedVarName' => 'undefinedVar', ] --CONFIG-- return ['strict_variables' => false] --EXPECT-- ok ok ok ok php-twig-2.12.5/tests/Fixtures/tests/defined_for_blocks.test000066400000000000000000000015701362457344700242010ustar00rootroot00000000000000--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 [] --EXPECT-- ok ko ok ok ok ko ok ko php-twig-2.12.5/tests/Fixtures/tests/defined_for_blocks_with_template.test000066400000000000000000000007501362457344700271260ustar00rootroot00000000000000--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 [ 'included_loaded' => $twig->load('included.twig'), 'included_loaded_internal' => $twig->load('included.twig'), ] --EXPECT-- ok ok ok php-twig-2.12.5/tests/Fixtures/tests/defined_for_constants.test000066400000000000000000000006041362457344700247350ustar00rootroot00000000000000--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 ['expect' => DATE_W3C, 'object' => new \ArrayObject(['hi'])] --EXPECT-- ok ok ok ok php-twig-2.12.5/tests/Fixtures/tests/defined_for_macros.test000066400000000000000000000007401362457344700242060ustar00rootroot00000000000000--TEST-- "defined" support for macros --TEMPLATE-- {% import _self as macros %} {% from _self import hello, bar %} {% if macros.hello is defined -%} OK {% endif %} {% if macros.foo is not defined -%} OK {% endif %} {% if hello is defined -%} OK {% endif %} {% if bar is not defined -%} OK {% endif %} {% if foo is not defined -%} OK {% endif %} {% macro hello(name) %} Hello {{ name }} {% endmacro %} --DATA-- return [] --EXPECT-- OK OK OK OK OK php-twig-2.12.5/tests/Fixtures/tests/defined_on_complex_expr.test000066400000000000000000000003611362457344700252540ustar00rootroot00000000000000--TEST-- "defined" support for "complex" expressions --TEMPLATE-- {{ (1 + 2) is defined ? 'ok' : 'ko' }} --DATA-- return [] --EXCEPTION-- Twig\Error\SyntaxError: The "defined" test only works with simple variables in "index.twig" at line 2. php-twig-2.12.5/tests/Fixtures/tests/dynamic_test.test000066400000000000000000000003251362457344700230600ustar00rootroot00000000000000--TEST-- dynamic test --TEMPLATE-- {{ 'bar' is test_bar ? '1' :'0' }} {{ 'foo' is test_foo ? '1' :'0' }} {{ 'bar' is test_foo ? '1' :'0' }} {{ 'foo' is test_bar ? '1' :'0' }} --DATA-- return [] --EXPECT-- 1 1 0 0 php-twig-2.12.5/tests/Fixtures/tests/empty.test000066400000000000000000000034771362457344700215460ustar00rootroot00000000000000--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' }} {{ iterator is empty ? 'ko' : 'ok' }} {{ empty_iterator is empty ? 'ok' : 'ko' }} {{ callback_iterator is empty ? 'ko' : 'ok' }} {{ empty_callback_iterator is empty ? 'ok' : 'ko' }} --DATA-- return [ 'string_empty' => '', 'string_zero' => '0', 'value_null' => null, 'value_false' => false, 'value_int_zero' => 0, 'array_empty' => [], 'array_not_empty' => [1, 2], 'magically_callable' => new \Twig\Tests\MagicCallStub(), 'countable_empty' => new \Twig\Tests\CountableStub([]), 'countable_not_empty' => new \Twig\Tests\CountableStub([1, 2]), 'tostring_empty' => new \Twig\Tests\ToStringStub(''), 'tostring_not_empty' => new \Twig\Tests\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'), 'iterator' => $iter = new \ArrayIterator(['bar', 'foo']), 'empty_iterator' => new \ArrayIterator(), 'callback_iterator' => new \CallbackFilterIterator($iter, function ($el) { return true; }), 'empty_callback_iterator' => new \CallbackFilterIterator($iter, function ($el) { return false; }), ] --EXPECT-- ok ok ok ok ok ok ok ok ok ok ok ok ok ok ok ok ok ok php-twig-2.12.5/tests/Fixtures/tests/even.test000066400000000000000000000003141362457344700213300ustar00rootroot00000000000000--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 [] --EXPECT-- ok ok ok ok php-twig-2.12.5/tests/Fixtures/tests/in.test000066400000000000000000000041211362457344700210010ustar00rootroot00000000000000--TEST-- Twig supports the in operator --TEMPLATE-- {{ bar in foo ? 'OK' : 'KO' }} {{ not (bar in foo) ? 'KO' : 'OK' }} {{ bar not in foo ? 'KO' : 'OK' }} {{ 'a' in bar ? 'OK' : 'KO' }} {{ 'c' not in bar ? 'OK' : 'KO' }} {{ '' in bar ? 'OK' : 'KO' }} {{ '' in '' ? 'OK' : 'KO' }} {{ '0' not in '' ? 'OK' : 'KO' }} {{ 'a' not in '0' ? 'OK' : 'KO' }} {{ '0' in '0' ? 'OK' : 'KO' }} {{ false in [0, 1] ? 'OK' : 'KO' }} {{ true in [0, 1] ? 'OK' : 'KO' }} {{ '0' in [0, 1] ? 'OK' : 'KO' }} {{ '0' in [1, 0] ? 'OK' : 'KO' }} {{ '' in [0, 1] ? 'OK' : 'KO' }} {{ '' in [1, 0] ? 'OK' : 'KO' }} {{ 0 in ['', 1] ? 'OK' : 'KO' }} {{ 0 in [1, ''] ? 'OK' : 'KO' }} {{ '' in 'foo' ? 'OK' : 'KO' }} {{ 0 in 'foo' ? 'KO' : 'OK' }} {{ false in 'foo' ? 'KO' : 'OK' }} {{ false in '100' ? 'KO' : 'OK' }} {{ true in '100' ? 'KO' : 'OK' }} {{ [] in [true, false] ? 'OK' : 'KO' }} {{ [] in [true, ''] ? 'KO' : 'OK' }} {{ [] in [true, []] ? 'OK' : 'KO' }} {{ resource ? 'OK' : 'KO' }} {{ resource in 'foo'~resource ? 'KO' : 'OK' }} {{ object in 'stdClass' ? 'KO' : 'OK' }} {{ [] in 'Array' ? 'KO' : 'OK' }} {{ dir_object in 'foo'~dir_object ? 'KO' : 'OK' }} {{ ''~resource in resource ? 'KO' : 'OK' }} {{ 'stdClass' in object ? 'KO' : 'OK' }} {{ 'Array' in [] ? 'KO' : 'OK' }} {{ ''~dir_object in dir_object ? 'KO' : 'OK' }} {{ resource in [''~resource] ? 'KO' : 'OK' }} {{ resource in [resource + 1 - 1] ? 'KO' : 'OK' }} {{ dir_object in [''~dir_object] ? 'KO' : 'OK' }} {{ 5 in 125 ? 'KO' : 'OK' }} {{ 5 in '125' ? 'OK' : 'KO' }} {{ '5' in 125 ? 'KO' : 'OK' }} {{ '5' in '125' ? 'OK' : 'KO' }} {{ 5.5 in 125.5 ? 'KO' : 'OK' }} {{ 5.5 in '125.5' ? 'OK' : 'KO' }} {{ '5.5' in 125.5 ? 'KO' : 'OK' }} {{ safe in ['foo', 'bar'] ? 'OK' : 'KO' }} {{ 'fo' in safe ? 'OK' : 'KO' }} --DATA-- return ['bar' => 'bar', 'foo' => ['bar' => 'bar'], 'dir_object' => new \SplFileInfo(__DIR__), 'object' => new \stdClass(), 'resource' => opendir(__DIR__), 'safe' => new \Twig\Markup('foo', 'UTF-8')] --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 OK OK OK OK OK OK OK OK OK OK OK OK OK OK OK php-twig-2.12.5/tests/Fixtures/tests/in_with_objects.test000066400000000000000000000005271362457344700235530ustar00rootroot00000000000000--TEST-- Twig supports the in operator when using objects --TEMPLATE-- {% if object in object_list %} TRUE {% endif %} --DATA-- $foo = new Twig\Tests\TwigTestFoo(); $foo1 = new Twig\Tests\TwigTestFoo(); $foo->position = $foo1; $foo1->position = $foo; return [ 'object' => $foo, 'object_list' => [$foo1, $foo], ] --EXPECT-- TRUE php-twig-2.12.5/tests/Fixtures/tests/iterable.test000066400000000000000000000005311362457344700221630ustar00rootroot00000000000000--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 [ 'foo' => [], 'traversable' => new \ArrayIterator([]), 'obj' => new \stdClass(), 'val' => 'test', ] --EXPECT-- ok ok ko kophp-twig-2.12.5/tests/Fixtures/tests/null_coalesce.test000066400000000000000000000007041362457344700232060ustar00rootroot00000000000000--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 ['bar' => 'OK', 'foo' => ['bar' => 'OK']] --EXPECT-- OK OK OK OK OK OK OK OK OK OK 3 6 php-twig-2.12.5/tests/Fixtures/tests/null_coalesce_block.test000066400000000000000000000002361362457344700243600ustar00rootroot00000000000000--TEST-- Twig supports the ?? operator with blocks --TEMPLATE-- {% block foo %}OK{% endblock %} {{ block('foo') ?? 'KO' }} --DATA-- return [] --EXPECT-- OKOK php-twig-2.12.5/tests/Fixtures/tests/odd.test000066400000000000000000000001761362457344700211470ustar00rootroot00000000000000--TEST-- "odd" test --TEMPLATE-- {{ 1 is odd ? 'ok' : 'ko' }} {{ 2 is odd ? 'ko' : 'ok' }} --DATA-- return [] --EXPECT-- ok okphp-twig-2.12.5/tests/Fixtures/whitespace/000077500000000000000000000000001362457344700204665ustar00rootroot00000000000000php-twig-2.12.5/tests/Fixtures/whitespace/trim_block.test000066400000000000000000000015611362457344700235170ustar00rootroot00000000000000--TEST-- Whitespace trimming on tags. --TEMPLATE-- 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 ['leading' => 'leading space', 'trailing' => 'trailing space', 'both' => 'both'] --EXPECT-- 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 php-twig-2.12.5/tests/Fixtures/whitespace/trim_delimiter_as_strings.test000066400000000000000000000002271362457344700266350ustar00rootroot00000000000000--TEST-- Whitespace trimming as strings. --TEMPLATE-- {{ 5 * '{#-'|length }} {{ '{{-'|length * 5 + '{%-'|length }} --DATA-- return [] --EXPECT-- 15 18 php-twig-2.12.5/tests/Fixtures/whitespace/trim_left.test000066400000000000000000000004351362457344700233560ustar00rootroot00000000000000--TEST-- Whitespace trimming on tags (left side). --TEMPLATE-- **{% if true %} foo {%- endif %}** ** {{- 'foo' }}** ** {#- comment #}** **{% verbatim %} foo {%- endverbatim %}** --DATA-- return [] --EXPECT-- **foo** **foo** **** ** foo** php-twig-2.12.5/tests/Fixtures/whitespace/trim_line_left.test000066400000000000000000000004371362457344700243670ustar00rootroot00000000000000--TEST-- Line whitespace trimming on tags (left side). --TEMPLATE-- **{% if true %} foo {%~ endif %}** ** {{~ 'foo' }}** ** {#~ comment #}** **{% verbatim %} foo {%~ endverbatim %}** --DATA-- return [] --EXPECT-- **foo ** ** foo** ** ** ** foo ** php-twig-2.12.5/tests/Fixtures/whitespace/trim_line_right.test000066400000000000000000000004611362457344700245470ustar00rootroot00000000000000--TEST-- Line whitespace trimming on tags (right side). --TEMPLATE-- **{% if true ~%} foo{% endif %}** **{{ 'foo' ~}} foo ** **{# comment ~#} foo ** **{% verbatim ~%} foo{% endverbatim %}** --DATA-- return [] --EXPECT-- ** foo** **foo foo ** ** foo ** ** foo** php-twig-2.12.5/tests/Fixtures/whitespace/trim_right.test000066400000000000000000000004321362457344700235360ustar00rootroot00000000000000--TEST-- Whitespace trimming on tags (right side). --TEMPLATE-- **{% if true -%} foo{% endif %}** **{{ 'foo' -}} ** **{# comment -#} ** **{% verbatim -%} foo{% endverbatim %}** --DATA-- return [] --EXPECT-- **foo** **foo** **** **foo** php-twig-2.12.5/tests/IntegrationTest.php000066400000000000000000000213601362457344700203570ustar00rootroot00000000000000position = 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 AbstractTokenParser { public function parse(Token $token) { $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new PrintNode(new ConstantExpression('§', -1), -1); } public function getTag() { return '§'; } } class TwigTestExtension extends AbstractExtension { public function getTokenParsers() { return [ new TwigTestTokenParser_§(), ]; } public function getFilters() { return [ new TwigFilter('§', [$this, '§Filter']), new TwigFilter('escape_and_nl2br', [$this, 'escape_and_nl2br'], ['needs_environment' => true, 'is_safe' => ['html']]), new TwigFilter('nl2br', [$this, 'nl2br'], ['pre_escape' => 'html', 'is_safe' => ['html']]), new TwigFilter('escape_something', [$this, 'escape_something'], ['is_safe' => ['something']]), new TwigFilter('preserves_safety', [$this, 'preserves_safety'], ['preserves_safety' => ['html']]), new TwigFilter('static_call_string', 'Twig\Tests\TwigTestExtension::staticCall'), new TwigFilter('static_call_array', ['Twig\Tests\TwigTestExtension', 'staticCall']), new TwigFilter('magic_call', [$this, 'magicCall']), new TwigFilter('magic_call_string', 'Twig\Tests\TwigTestExtension::magicStaticCall'), new TwigFilter('magic_call_array', ['Twig\Tests\TwigTestExtension', 'magicStaticCall']), new TwigFilter('*_path', [$this, 'dynamic_path']), new TwigFilter('*_foo_*_bar', [$this, 'dynamic_foo']), new TwigFilter('anon_foo', function ($name) { return '*'.$name.'*'; }), ]; } public function getFunctions() { return [ new TwigFunction('§', [$this, '§Function']), new TwigFunction('safe_br', [$this, 'br'], ['is_safe' => ['html']]), new TwigFunction('unsafe_br', [$this, 'br']), new TwigFunction('static_call_string', 'Twig\Tests\TwigTestExtension::staticCall'), new TwigFunction('static_call_array', ['Twig\Tests\TwigTestExtension', 'staticCall']), new TwigFunction('*_path', [$this, 'dynamic_path']), new TwigFunction('*_foo_*_bar', [$this, 'dynamic_foo']), new TwigFunction('anon_foo', function ($name) { return '*'.$name.'*'; }), ]; } public function getTests() { return [ new TwigTest('multi word', [$this, 'is_multi_word']), new TwigTest('test_*', [$this, 'dynamic_test']), ]; } public function §Filter($value) { return "§{$value}§"; } public function §Function($value) { return "§{$value}§"; } /** * nl2br which also escapes, for testing escaper filters. */ public function escape_and_nl2br($env, $value, $sep = '
    ') { return $this->nl2br(twig_escape_filter($env, $value, 'html'), $sep); } /** * nl2br only, for testing filters with pre_escape. */ public function nl2br($value, $sep = '
    ') { // not secure if $value contains html tags (not only entities) // don't use return str_replace("\n", "$sep\n", $value); } public function dynamic_path($element, $item) { return $element.'/'.$item; } public function dynamic_foo($foo, $bar, $item) { return $foo.'/'.$bar.'/'.$item; } public function dynamic_test($element, $item) { return $element === $item; } public function escape_something($value) { return strtoupper($value); } public function preserves_safety($value) { return strtoupper($value); } public static function staticCall($value) { return "*$value*"; } public function br() { return '
    '; } public function is_multi_word($value) { return false !== strpos($value, ' '); } public function __call($method, $arguments) { if ('magicCall' !== $method) { throw new \BadMethodCallException('Unexpected call to __call'); } return 'magic_'.$arguments[0]; } public static function __callStatic($method, $arguments) { if ('magicStaticCall' !== $method) { throw new \BadMethodCallException('Unexpected call to __callStatic'); } return 'static_magic_'.$arguments[0]; } } /** * This class is used in tests for the "length" filter and "empty" test. It asserts that __call is not * used to convert such objects to strings. */ class MagicCallStub { public function __call($name, $args) { throw new \Exception('__call shall not be called'); } } class ToStringStub { /** * @var string */ private $string; public function __construct($string) { $this->string = $string; } public function __toString() { return $this->string; } } /** * This class is used in tests for the length filter and empty test to show * that when \Countable is implemented, it is preferred over the __toString() * method. */ class CountableStub implements \Countable { private $count; public function __construct($count) { $this->count = $count; } public function count() { return $this->count; } public function __toString() { throw new \Exception('__toString shall not be called on \Countables'); } } /** * This class is used in tests for the length filter. */ class IteratorAggregateStub implements \IteratorAggregate { private $data; public function __construct(array $data) { $this->data = $data; } public function getIterator() { return new \ArrayIterator($this->data); } } class SimpleIteratorForTesting implements \Iterator { private $data = [1, 2, 3, 4, 5, 6, 7]; private $key = 0; public function current() { return $this->key; } public function next() { ++$this->key; } public function key() { return $this->key; } public function valid() { return isset($this->data[$this->key]); } public function rewind() { $this->key = 0; } public function __toString() { // for testing, make sure string length returned is not the same as the `iterator_count` return str_repeat('X', iterator_count($this) + 10); } } php-twig-2.12.5/tests/LexerTest.php000066400000000000000000000323461362457344700171610ustar00rootroot00000000000000createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::BLOCK_START_TYPE); $this->assertSame('§', $stream->expect(Token::NAME_TYPE)->getValue()); } public function testNameLabelForFunction() { $template = '{{ §() }}'; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::VAR_START_TYPE); $this->assertSame('§', $stream->expect(Token::NAME_TYPE)->getValue()); } public function testBracketsNesting() { $template = '{{ {"a":{"b":"c"}} }}'; $this->assertEquals(2, $this->countToken($template, Token::PUNCTUATION_TYPE, '{')); $this->assertEquals(2, $this->countToken($template, Token::PUNCTUATION_TYPE, '}')); } protected function countToken($template, $type, $value = null) { $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new 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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); // foo\nbar\n $this->assertSame(1, $stream->expect(Token::TEXT_TYPE)->getLine()); // \n (after {% line %}) $this->assertSame(10, $stream->expect(Token::TEXT_TYPE)->getLine()); // {{ $this->assertSame(11, $stream->expect(Token::VAR_START_TYPE)->getLine()); // baz $this->assertSame(12, $stream->expect(Token::NAME_TYPE)->getLine()); } public function testLineDirectiveInline() { $template = "foo\n" ."bar{% line 10 %}{{\n" ."baz\n" ."}}\n"; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); // foo\nbar $this->assertSame(1, $stream->expect(Token::TEXT_TYPE)->getLine()); // {{ $this->assertSame(10, $stream->expect(Token::VAR_START_TYPE)->getLine()); // baz $this->assertSame(11, $stream->expect(Token::NAME_TYPE)->getLine()); } public function testLongComments() { $template = '{# '.str_repeat('*', 100000).' #}'; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $lexer->tokenize(new 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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $lexer->tokenize(new 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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $lexer->tokenize(new 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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $lexer->tokenize(new 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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->next(); $node = $stream->next(); $this->assertEquals('922337203685477580700', $node->getValue()); } public function testStringWithEscapedDelimiter() { $tests = [ "{{ 'foo \' bar' }}" => 'foo \' bar', '{{ "foo \" bar" }}' => 'foo " bar', ]; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); foreach ($tests as $template => $expected) { $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::VAR_START_TYPE); $stream->expect(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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::TEXT_TYPE, 'foo '); $stream->expect(Token::VAR_START_TYPE); $stream->expect(Token::STRING_TYPE, 'bar '); $stream->expect(Token::INTERPOLATION_START_TYPE); $stream->expect(Token::NAME_TYPE, 'baz'); $stream->expect(Token::OPERATOR_TYPE, '+'); $stream->expect(Token::NUMBER_TYPE, '1'); $stream->expect(Token::INTERPOLATION_END_TYPE); $stream->expect(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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::VAR_START_TYPE); $stream->expect(Token::STRING_TYPE, 'bar #{baz+1}'); $stream->expect(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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::VAR_START_TYPE); $stream->expect(Token::STRING_TYPE, 'bar # baz'); $stream->expect(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 testStringWithUnterminatedInterpolation() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unclosed """'); $template = '{{ "bar #{x" }}'; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $lexer->tokenize(new Source($template, 'index')); } public function testStringWithNestedInterpolations() { $template = '{{ "bar #{ "foo#{bar}" }" }}'; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::VAR_START_TYPE); $stream->expect(Token::STRING_TYPE, 'bar '); $stream->expect(Token::INTERPOLATION_START_TYPE); $stream->expect(Token::STRING_TYPE, 'foo'); $stream->expect(Token::INTERPOLATION_START_TYPE); $stream->expect(Token::NAME_TYPE, 'bar'); $stream->expect(Token::INTERPOLATION_END_TYPE); $stream->expect(Token::INTERPOLATION_END_TYPE); $stream->expect(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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::BLOCK_START_TYPE); $stream->expect(Token::NAME_TYPE, 'foo'); $stream->expect(Token::STRING_TYPE, 'bar '); $stream->expect(Token::INTERPOLATION_START_TYPE); $stream->expect(Token::STRING_TYPE, 'foo'); $stream->expect(Token::INTERPOLATION_START_TYPE); $stream->expect(Token::NAME_TYPE, 'bar'); $stream->expect(Token::INTERPOLATION_END_TYPE); $stream->expect(Token::INTERPOLATION_END_TYPE); $stream->expect(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 Lexer(new Environment($this->createMock(LoaderInterface::class))); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::VAR_START_TYPE); $stream->expect(Token::NUMBER_TYPE, 1); $stream->expect(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); } public function testUnterminatedVariable() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unclosed "variable" in "index" at line 3'); $template = ' {{ bar '; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $lexer->tokenize(new Source($template, 'index')); } public function testUnterminatedBlock() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unclosed "block" in "index" at line 3'); $template = ' {% bar '; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class))); $lexer->tokenize(new Source($template, 'index')); } public function testOverridingSyntax() { $template = '[# comment #]{# variable #}/# if true #/true/# endif #/'; $lexer = new Lexer(new Environment($this->createMock(LoaderInterface::class)), [ 'tag_comment' => ['[#', '#]'], 'tag_block' => ['/#', '#/'], 'tag_variable' => ['{#', '#}'], ]); $stream = $lexer->tokenize(new Source($template, 'index')); $stream->expect(Token::VAR_START_TYPE); $stream->expect(Token::NAME_TYPE, 'variable'); $stream->expect(Token::VAR_END_TYPE); $stream->expect(Token::BLOCK_START_TYPE); $stream->expect(Token::NAME_TYPE, 'if'); $stream->expect(Token::NAME_TYPE, 'true'); $stream->expect(Token::BLOCK_END_TYPE); $stream->expect(Token::TEXT_TYPE, 'true'); $stream->expect(Token::BLOCK_START_TYPE); $stream->expect(Token::NAME_TYPE, 'endif'); $stream->expect(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); } } php-twig-2.12.5/tests/Loader/000077500000000000000000000000001362457344700157275ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/ArrayTest.php000066400000000000000000000042171362457344700203620ustar00rootroot00000000000000expectException(LoaderError::class); $loader = new ArrayLoader([]); $loader->getSourceContext('foo'); } public function testGetCacheKey() { $loader = new ArrayLoader(['foo' => 'bar']); $this->assertEquals('foo:bar', $loader->getCacheKey('foo')); } public function testGetCacheKeyWhenTemplateHasDuplicateContent() { $loader = new ArrayLoader([ 'foo' => 'bar', 'baz' => 'bar', ]); $this->assertEquals('foo:bar', $loader->getCacheKey('foo')); $this->assertEquals('baz:bar', $loader->getCacheKey('baz')); } public function testGetCacheKeyIsProtectedFromEdgeCollisions() { $loader = new ArrayLoader([ 'foo__' => 'bar', 'foo' => '__bar', ]); $this->assertEquals('foo__:bar', $loader->getCacheKey('foo__')); $this->assertEquals('foo:__bar', $loader->getCacheKey('foo')); } public function testGetCacheKeyWhenTemplateDoesNotExist() { $this->expectException(LoaderError::class); $loader = new ArrayLoader([]); $loader->getCacheKey('foo'); } public function testSetTemplate() { $loader = new ArrayLoader([]); $loader->setTemplate('foo', 'bar'); $this->assertEquals('bar', $loader->getSourceContext('foo')->getCode()); } public function testIsFresh() { $loader = new ArrayLoader(['foo' => 'bar']); $this->assertTrue($loader->isFresh('foo', time())); } public function testIsFreshWhenTemplateDoesNotExist() { $this->expectException(LoaderError::class); $loader = new ArrayLoader([]); $loader->isFresh('foo', time()); } } php-twig-2.12.5/tests/Loader/ChainTest.php000066400000000000000000000061531362457344700203270ustar00rootroot00000000000000 'bar']), new ArrayLoader(['errors/index.html' => 'baz']), new FilesystemLoader([$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()); } public function testGetSourceContextWhenTemplateDoesNotExist() { $this->expectException(LoaderError::class); $loader = new ChainLoader([]); $loader->getSourceContext('foo'); } public function testGetCacheKey() { $loader = new ChainLoader([ new ArrayLoader(['foo' => 'bar']), new ArrayLoader(['foo' => 'foobar', 'bar' => 'foo']), ]); $this->assertEquals('foo:bar', $loader->getCacheKey('foo')); $this->assertEquals('bar:foo', $loader->getCacheKey('bar')); } public function testGetCacheKeyWhenTemplateDoesNotExist() { $this->expectException(LoaderError::class); $loader = new ChainLoader([]); $loader->getCacheKey('foo'); } public function testAddLoader() { $loader = new ChainLoader(); $loader->addLoader(new ArrayLoader(['foo' => 'bar'])); $this->assertEquals('bar', $loader->getSourceContext('foo')->getCode()); } public function testExists() { $loader1 = $this->createMock(LoaderInterface::class); $loader1->expects($this->once())->method('exists')->willReturn(false); $loader1->expects($this->never())->method('getSourceContext'); $loader2 = $this->createMock(LoaderInterface::class); $loader2->expects($this->once())->method('exists')->willReturn(true); $loader2->expects($this->never())->method('getSourceContext'); $loader = new ChainLoader(); $loader->addLoader($loader1); $loader->addLoader($loader2); $this->assertTrue($loader->exists('foo')); } } php-twig-2.12.5/tests/Loader/FilesystemTest.php000066400000000000000000000214511362457344700214270ustar00rootroot00000000000000assertEquals('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 FilesystemLoader([__DIR__.'/../Fixtures']); try { $loader->getCacheKey($template); $this->fail(); } catch (LoaderError $e) { $this->assertStringNotContainsString('Unable to find template', $e->getMessage()); } } public function getSecurityTests() { return [ ["AutoloaderTest\0.php"], ['..\\AutoloaderTest.php'], ['..\\\\\\AutoloaderTest.php'], ['../AutoloaderTest.php'], ['..////AutoloaderTest.php'], ['./../AutoloaderTest.php'], ['.\\..\\AutoloaderTest.php'], ['././././././../AutoloaderTest.php'], ['.\\./.\\./.\\./../AutoloaderTest.php'], ['foo/../../AutoloaderTest.php'], ['foo\\..\\..\\AutoloaderTest.php'], ['foo/../bar/../../AutoloaderTest.php'], ['foo/bar/../../../AutoloaderTest.php'], ['filters/../../AutoloaderTest.php'], ['filters//..//..//AutoloaderTest.php'], ['filters\\..\\..\\AutoloaderTest.php'], ['filters\\\\..\\\\..\\\\AutoloaderTest.php'], ['filters\\//../\\/\\..\\AutoloaderTest.php'], ['/../AutoloaderTest.php'], ]; } /** * @dataProvider getBasePaths */ public function testPaths($basePath, $cacheKey, $rootPath) { $loader = new FilesystemLoader([$basePath.'/normal', $basePath.'/normal_bis'], $rootPath); $loader->setPaths([$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([ $basePath.'/normal_final', $basePath.'/normal', $basePath.'/normal_bis', $basePath.'/normal_ter', ], $loader->getPaths()); $this->assertEquals([ $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 [ [ __DIR__.'/Fixtures', 'tests/Loader/Fixtures/named_quater/named_absolute.html', null, ], [ __DIR__.'/Fixtures/../Fixtures', 'tests/Loader/Fixtures/named_quater/named_absolute.html', null, ], [ 'tests/Loader/Fixtures', 'tests/Loader/Fixtures/named_quater/named_absolute.html', getcwd(), ], [ 'Fixtures', 'Fixtures/named_quater/named_absolute.html', getcwd().'/tests/Loader', ], [ 'Fixtures', 'Fixtures/named_quater/named_absolute.html', getcwd().'/tests/../tests/Loader', ], ]; } public function testEmptyConstructor() { $loader = new FilesystemLoader(); $this->assertEquals([], $loader->getPaths()); } public function testGetNamespaces() { $loader = new FilesystemLoader(sys_get_temp_dir()); $this->assertEquals([FilesystemLoader::MAIN_NAMESPACE], $loader->getNamespaces()); $loader->addPath(sys_get_temp_dir(), 'named'); $this->assertEquals([FilesystemLoader::MAIN_NAMESPACE, 'named'], $loader->getNamespaces()); } public function testFindTemplateExceptionNamespace() { $basePath = __DIR__.'/Fixtures'; $loader = new FilesystemLoader([$basePath.'/normal']); $loader->addPath($basePath.'/named', 'named'); try { $loader->getSourceContext('@named/nowhere.html'); } catch (\Exception $e) { $this->assertInstanceOf(LoaderError::class, $e); $this->assertStringContainsString('Unable to find template "@named/nowhere.html"', $e->getMessage()); } } public function testFindTemplateWithCache() { $basePath = __DIR__.'/Fixtures'; $loader = new FilesystemLoader([$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 FilesystemLoader([]); $loader->addPath(__DIR__.'/Fixtures/themes/theme2'); $loader->addPath(__DIR__.'/Fixtures/themes/theme1'); $loader->addPath(__DIR__.'/Fixtures/themes/theme1', 'default_theme'); $twig = new Environment($loader); $template = $twig->load('blocks.html.twig'); $this->assertSame('block from theme 1', $template->renderBlock('b1', [])); $template = $twig->load('blocks.html.twig'); $this->assertSame('block from theme 2', $template->renderBlock('b2', [])); } public function getArrayInheritanceTests() { return [ 'valid array inheritance' => ['array_inheritance_valid_parent.html.twig'], 'array inheritance with null first template' => ['array_inheritance_null_parent.html.twig'], 'array inheritance with empty first template' => ['array_inheritance_empty_parent.html.twig'], 'array inheritance with non-existent first template' => ['array_inheritance_nonexistent_parent.html.twig'], ]; } /** * @dataProvider getArrayInheritanceTests * * @param $templateName string Template name with array inheritance */ public function testArrayInheritance($templateName) { $loader = new FilesystemLoader([]); $loader->addPath(__DIR__.'/Fixtures/inheritance'); $twig = new Environment($loader); $template = $twig->load($templateName); $this->assertSame('VALID Child', $template->renderBlock('body', [])); } public function testLoadTemplateFromPhar() { $loader = new FilesystemLoader([]); // 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()); } public function testTemplateExistsAlwaysReturnsBool() { $loader = new FilesystemLoader([]); $this->assertFalse($loader->exists("foo\0.twig")); $this->assertFalse($loader->exists('../foo.twig')); $this->assertFalse($loader->exists('@foo')); $this->assertFalse($loader->exists('foo')); $this->assertFalse($loader->exists('@foo/bar.twig')); $loader->addPath(__DIR__.'/Fixtures/normal'); $this->assertTrue($loader->exists('index.html')); $loader->addPath(__DIR__.'/Fixtures/normal', 'foo'); $this->assertTrue($loader->exists('@foo/index.html')); } } php-twig-2.12.5/tests/Loader/Fixtures/000077500000000000000000000000001362457344700175405ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/inheritance/000077500000000000000000000000001362457344700220315ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/inheritance/array_inheritance_empty_parent.html.twig000066400000000000000000000001321362457344700321420ustar00rootroot00000000000000{% extends ['','parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} php-twig-2.12.5/tests/Loader/Fixtures/inheritance/array_inheritance_nonexistent_parent.html.twig000066400000000000000000000001571362457344700333710ustar00rootroot00000000000000{% extends ['nonexistent.html.twig','parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} php-twig-2.12.5/tests/Loader/Fixtures/inheritance/array_inheritance_null_parent.html.twig000066400000000000000000000001341362457344700317600ustar00rootroot00000000000000{% extends [null,'parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} php-twig-2.12.5/tests/Loader/Fixtures/inheritance/array_inheritance_valid_parent.html.twig000066400000000000000000000001601362457344700321040ustar00rootroot00000000000000{% extends ['parent.html.twig','spare_parent.html.twig'] %} {% block body %}{{ parent() }} Child{% endblock %} php-twig-2.12.5/tests/Loader/Fixtures/inheritance/parent.html.twig000066400000000000000000000000441362457344700251570ustar00rootroot00000000000000{% block body %}VALID{% endblock %} php-twig-2.12.5/tests/Loader/Fixtures/inheritance/spare_parent.html.twig000066400000000000000000000000531362457344700263510ustar00rootroot00000000000000{% block body %}SPARE PARENT{% endblock %} php-twig-2.12.5/tests/Loader/Fixtures/named/000077500000000000000000000000001362457344700206245ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/named/index.html000066400000000000000000000000131362457344700226130ustar00rootroot00000000000000named path php-twig-2.12.5/tests/Loader/Fixtures/named_bis/000077500000000000000000000000001362457344700214615ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/named_bis/index.html000066400000000000000000000000211362457344700234470ustar00rootroot00000000000000named path (bis) php-twig-2.12.5/tests/Loader/Fixtures/named_final/000077500000000000000000000000001362457344700217755ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/named_final/index.html000066400000000000000000000000231362457344700237650ustar00rootroot00000000000000named path (final) php-twig-2.12.5/tests/Loader/Fixtures/named_quater/000077500000000000000000000000001362457344700222055ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/named_quater/named_absolute.html000066400000000000000000000000241362457344700260510ustar00rootroot00000000000000named path (quater) php-twig-2.12.5/tests/Loader/Fixtures/named_ter/000077500000000000000000000000001362457344700214765ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/named_ter/index.html000066400000000000000000000000211362457344700234640ustar00rootroot00000000000000named path (ter) php-twig-2.12.5/tests/Loader/Fixtures/normal/000077500000000000000000000000001362457344700210305ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/normal/index.html000066400000000000000000000000051362457344700230200ustar00rootroot00000000000000path php-twig-2.12.5/tests/Loader/Fixtures/normal_bis/000077500000000000000000000000001362457344700216655ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/normal_bis/index.html000066400000000000000000000000131362457344700236540ustar00rootroot00000000000000path (bis) php-twig-2.12.5/tests/Loader/Fixtures/normal_final/000077500000000000000000000000001362457344700222015ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/normal_final/index.html000066400000000000000000000000151362457344700241720ustar00rootroot00000000000000path (final) php-twig-2.12.5/tests/Loader/Fixtures/normal_ter/000077500000000000000000000000001362457344700217025ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/normal_ter/index.html000066400000000000000000000000131362457344700236710ustar00rootroot00000000000000path (ter) php-twig-2.12.5/tests/Loader/Fixtures/phar/000077500000000000000000000000001362457344700204725ustar00rootroot00000000000000php-twig-2.12.5/tests/Loader/Fixtures/phar/phar-sample.phar000066400000000000000000000152021362457344700235570ustar00rootroot00000000000000 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����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Loader/Fixtures/themes/�������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0021025�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Loader/Fixtures/themes/theme1/������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0022210�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Loader/Fixtures/themes/theme1/blocks.html.twig��������������������������������0000664�0000000�0000000�00000000137�13624573447�0025325�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% block b1 %}block from theme 1{% endblock %} {% block b2 %}block from theme 1{% endblock %} ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Loader/Fixtures/themes/theme2/������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0022211�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Loader/Fixtures/themes/theme2/blocks.html.twig��������������������������������0000664�0000000�0000000�00000000134�13624573447�0025323�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������{% use '@default_theme/blocks.html.twig' %} {% block b2 %}block from theme 2{% endblock %} ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/�������������������������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0015406�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/AutoEscapeTest.php�������������������������������������������������������0000664�0000000�0000000�00000001555�13624573447�0021016�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\AutoEscapeNode; use Twig\Node\Node; use Twig\Node\TextNode; use Twig\Test\NodeTestCase; class AutoEscapeTest extends NodeTestCase { public function testConstructor() { $body = new Node([new TextNode('foo', 1)]); $node = new AutoEscapeNode(true, $body, 1); $this->assertEquals($body, $node->getNode('body')); $this->assertTrue($node->getAttribute('value')); } public function getTests() { $body = new Node([new TextNode('foo', 1)]); $node = new AutoEscapeNode(true, $body, 1); return [ [$node, "// line 1\necho \"foo\";"], ]; } } ���������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/BlockReferenceTest.php���������������������������������������������������0000664�0000000�0000000�00000001312�13624573447�0021625�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\BlockReferenceNode; use Twig\Test\NodeTestCase; class BlockReferenceTest extends NodeTestCase { public function testConstructor() { $node = new BlockReferenceNode('foo', 1); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { return [ [new BlockReferenceNode('foo', 1), <<<EOF // line 1 \$this->displayBlock('foo', \$context, \$blocks); EOF ], ]; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/BlockTest.php������������������������������������������������������������0000664�0000000�0000000�00000001653�13624573447�0020016�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\BlockNode; use Twig\Node\TextNode; use Twig\Test\NodeTestCase; class BlockTest extends NodeTestCase { public function testConstructor() { $body = new TextNode('foo', 1); $node = new BlockNode('foo', $body, 1); $this->assertEquals($body, $node->getNode('body')); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { $body = new TextNode('foo', 1); $node = new BlockNode('foo', $body, 1); return [ [$node, <<<EOF // line 1 public function block_foo(\$context, array \$blocks = []) { \$macros = \$this->macros; echo "foo"; } EOF ], ]; } } �������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/DeprecatedTest.php�������������������������������������������������������0000664�0000000�0000000�00000004310�13624573447�0021015�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Environment; use Twig\Loader\LoaderInterface; use Twig\Node\DeprecatedNode; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\FunctionExpression; use Twig\Node\IfNode; use Twig\Node\Node; use Twig\Source; use Twig\Test\NodeTestCase; use Twig\TwigFunction; class DeprecatedTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression('foo', 1); $node = new DeprecatedNode($expr, 1); $this->assertEquals($expr, $node->getNode('expr')); } public function getTests() { $tests = []; $expr = new ConstantExpression('This section is deprecated', 1); $node = new DeprecatedNode($expr, 1, 'deprecated'); $node->setSourceContext(new Source('', 'foo.twig')); $tests[] = [$node, <<<EOF // line 1 @trigger_error("This section is deprecated"." (\"foo.twig\" at line 1).", E_USER_DEPRECATED); EOF ]; $t = new Node([ new ConstantExpression(true, 1), new DeprecatedNode($expr, 2, 'deprecated'), ], [], 1); $node = new IfNode($t, null, 1); $node->setSourceContext(new Source('', 'foo.twig')); $tests[] = [$node, <<<EOF // line 1 if (true) { // line 2 @trigger_error("This section is deprecated"." (\"foo.twig\" at line 2).", E_USER_DEPRECATED); } EOF ]; $environment = new Environment($this->createMock(LoaderInterface::class)); $environment->addFunction(new TwigFunction('foo', 'foo', [])); $expr = new FunctionExpression('foo', new Node(), 1); $node = new DeprecatedNode($expr, 1, 'deprecated'); $node->setSourceContext(new Source('', 'foo.twig')); $compiler = $this->getCompiler($environment); $varName = $compiler->getVarName(); $tests[] = [$node, <<<EOF // line 1 \$$varName = foo(); @trigger_error(\$$varName." (\"foo.twig\" at line 1).", E_USER_DEPRECATED); EOF , $environment]; return $tests; } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/DoTest.php���������������������������������������������������������������0000664�0000000�0000000�00000001430�13624573447�0017317�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\DoNode; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class DoTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression('foo', 1); $node = new DoNode($expr, 1); $this->assertEquals($expr, $node->getNode('expr')); } public function getTests() { $tests = []; $expr = new ConstantExpression('foo', 1); $node = new DoNode($expr, 1); $tests[] = [$node, "// line 1\n\"foo\";"]; return $tests; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/��������������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0017545�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/ArrayTest.php�������������������������������������������������0000664�0000000�0000000�00000002032�13624573447�0022171�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Node\Expression\ArrayExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class ArrayTest extends NodeTestCase { public function testConstructor() { $elements = [new ConstantExpression('foo', 1), $foo = new ConstantExpression('bar', 1)]; $node = new ArrayExpression($elements, 1); $this->assertEquals($foo, $node->getNode(1)); } public function getTests() { $elements = [ new ConstantExpression('foo', 1), new ConstantExpression('bar', 1), new ConstantExpression('bar', 1), new ConstantExpression('foo', 1), ]; $node = new ArrayExpression($elements, 1); return [ [$node, '["foo" => "bar", "bar" => "foo"]'], ]; } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/AssignNameTest.php��������������������������������������������0000664�0000000�0000000�00000001270�13624573447�0023143�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Node\Expression\AssignNameExpression; use Twig\Test\NodeTestCase; class AssignNameTest extends NodeTestCase { public function testConstructor() { $node = new AssignNameExpression('foo', 1); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { $node = new AssignNameExpression('foo', 1); return [ [$node, '$context["foo"]'], ]; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/�������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0020771�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/AddTest.php��������������������������������������������0000664�0000000�0000000�00000001706�13624573447�0023036�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\AddBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class AddTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new AddBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new AddBinary($left, $right, 1); return [ [$node, '(1 + 2)'], ]; } } ����������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/AndTest.php��������������������������������������������0000664�0000000�0000000�00000001707�13624573447�0023051�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\AndBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class AndTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new AndBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new AndBinary($left, $right, 1); return [ [$node, '(1 && 2)'], ]; } } ���������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/ConcatTest.php�����������������������������������������0000664�0000000�0000000�00000001722�13624573447�0023553�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\ConcatBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class ConcatTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new ConcatBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new ConcatBinary($left, $right, 1); return [ [$node, '(1 . 2)'], ]; } } ����������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/DivTest.php��������������������������������������������0000664�0000000�0000000�00000001706�13624573447�0023070�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\DivBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class DivTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new DivBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new DivBinary($left, $right, 1); return [ [$node, '(1 / 2)'], ]; } } ����������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/FloorDivTest.php���������������������������������������0000664�0000000�0000000�00000001747�13624573447�0024077�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\FloorDivBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class FloorDivTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new FloorDivBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new FloorDivBinary($left, $right, 1); return [ [$node, '(int) floor((1 / 2))'], ]; } } �������������������������php-twig-2.12.5/tests/Node/Expression/Binary/ModTest.php��������������������������������������������0000664�0000000�0000000�00000001706�13624573447�0023065�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\ModBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class ModTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new ModBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new ModBinary($left, $right, 1); return [ [$node, '(1 % 2)'], ]; } } ����������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/MulTest.php��������������������������������������������0000664�0000000�0000000�00000001706�13624573447�0023103�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\MulBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class MulTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new MulBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new MulBinary($left, $right, 1); return [ [$node, '(1 * 2)'], ]; } } ����������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/OrTest.php���������������������������������������������0000664�0000000�0000000�00000001703�13624573447�0022723�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\OrBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class OrTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new OrBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new OrBinary($left, $right, 1); return [ [$node, '(1 || 2)'], ]; } } �������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Binary/SubTest.php��������������������������������������������0000664�0000000�0000000�00000001706�13624573447�0023077�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Binary; /* * 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. */ use Twig\Node\Expression\Binary\SubBinary; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class SubTest extends NodeTestCase { public function testConstructor() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new SubBinary($left, $right, 1); $this->assertEquals($left, $node->getNode('left')); $this->assertEquals($right, $node->getNode('right')); } public function getTests() { $left = new ConstantExpression(1, 1); $right = new ConstantExpression(2, 1); $node = new SubBinary($left, $right, 1); return [ [$node, '(1 - 2)'], ]; } } ����������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/CallTest.php��������������������������������������������������0000664�0000000�0000000�00000014065�13624573447�0021777�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Error\SyntaxError; use Twig\Node\Expression\CallExpression; class CallTest extends TestCase { public function testGetArguments() { $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'date']); $this->assertEquals(['U', null], $this->getArguments($node, ['date', ['format' => 'U', 'timestamp' => null]])); } public function testGetArgumentsWhenPositionalArgumentsAfterNamedArguments() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Positional arguments cannot be used after named arguments for function "date".'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'date']); $this->getArguments($node, ['date', ['timestamp' => 123456, 'Y-m-d']]); } public function testGetArgumentsWhenArgumentIsDefinedTwice() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Argument "format" is defined twice for function "date".'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'date']); $this->getArguments($node, ['date', ['Y-m-d', 'format' => 'U']]); } public function testGetArgumentsWithWrongNamedArgumentName() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown argument "unknown" for function "date(format, timestamp)".'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'date']); $this->getArguments($node, ['date', ['Y-m-d', 'timestamp' => null, 'unknown' => '']]); } public function testGetArgumentsWithWrongNamedArgumentNames() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown arguments "unknown1", "unknown2" for function "date(format, timestamp)".'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'date']); $this->getArguments($node, ['date', ['Y-m-d', 'timestamp' => null, 'unknown1' => '', 'unknown2' => '']]); } public function testResolveArgumentsWithMissingValueForOptionalArgument() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('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".'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'substr_compare']); $this->getArguments($node, ['substr_compare', ['abcd', 'bc', 'offset' => 1, 'case_sensitivity' => true]]); } public function testResolveArgumentsOnlyNecessaryArgumentsForCustomFunction() { $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'custom_function']); $this->assertEquals(['arg1'], $this->getArguments($node, [[$this, 'customFunction'], ['arg1' => 'arg1']])); } public function testGetArgumentsForStaticMethod() { $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'custom_static_function']); $this->assertEquals(['arg1'], $this->getArguments($node, [__CLASS__.'::customStaticFunction', ['arg1' => 'arg1']])); } public function testResolveArgumentsWithMissingParameterForArbitraryArguments() { $this->expectException(\LogicException::class); $this->expectExceptionMessage('The last parameter of "Twig\\Tests\\Node\\Expression\\CallTest::customFunctionWithArbitraryArguments" for function "foo" must be an array with default value, eg. "array $arg = []".'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'foo', 'is_variadic' => true]); $this->getArguments($node, [[$this, 'customFunctionWithArbitraryArguments'], []]); } public static function customStaticFunction($arg1, $arg2 = 'default', $arg3 = []) { } public function customFunction($arg1, $arg2 = 'default', $arg3 = []) { } private function getArguments($call, $args) { $m = new \ReflectionMethod($call, 'getArguments'); $m->setAccessible(true); return $m->invokeArgs($call, $args); } public function customFunctionWithArbitraryArguments() { } public function testResolveArgumentsWithMissingParameterForArbitraryArgumentsOnFunction() { $this->expectException(\LogicException::class); $this->expectExceptionMessageRegExp('#^The last parameter of "Twig\\\\Tests\\\\Node\\\\Expression\\\\custom_Twig_Tests_Node_Expression_CallTest_function" for function "foo" must be an array with default value, eg\\. "array \\$arg \\= \\[\\]"\\.$#'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'foo', 'is_variadic' => true]); $node->getArguments('Twig\Tests\Node\Expression\custom_Twig_Tests_Node_Expression_CallTest_function', []); } public function testResolveArgumentsWithMissingParameterForArbitraryArgumentsOnObject() { $this->expectException(\LogicException::class); $this->expectExceptionMessageRegExp('#^The last parameter of "Twig\\\\Tests\\\\Node\\\\Expression\\\\CallableTestClass\\:\\:__invoke" for function "foo" must be an array with default value, eg\\. "array \\$arg \\= \\[\\]"\\.$#'); $node = new Node_Expression_Call([], ['type' => 'function', 'name' => 'foo', 'is_variadic' => true]); $node->getArguments(new CallableTestClass(), []); } } class Node_Expression_Call extends CallExpression { 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) { } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/ConditionalTest.php�������������������������������������������0000664�0000000�0000000�00000002270�13624573447�0023362�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Node\Expression\ConditionalExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class ConditionalTest extends NodeTestCase { public function testConstructor() { $expr1 = new ConstantExpression(1, 1); $expr2 = new ConstantExpression(2, 1); $expr3 = new ConstantExpression(3, 1); $node = new ConditionalExpression($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 = []; $expr1 = new ConstantExpression(1, 1); $expr2 = new ConstantExpression(2, 1); $expr3 = new ConstantExpression(3, 1); $node = new ConditionalExpression($expr1, $expr2, $expr3, 1); $tests[] = [$node, '((1) ? (2) : (3))']; return $tests; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/ConstantTest.php����������������������������������������������0000664�0000000�0000000�00000001277�13624573447�0022716�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Test\NodeTestCase; class ConstantTest extends NodeTestCase { public function testConstructor() { $node = new ConstantExpression('foo', 1); $this->assertEquals('foo', $node->getAttribute('value')); } public function getTests() { $tests = []; $node = new ConstantExpression('foo', 1); $tests[] = [$node, '"foo"']; return $tests; } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/FilterTest.php������������������������������������������������0000664�0000000�0000000�00000014244�13624573447�0022350�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Environment; use Twig\Error\SyntaxError; use Twig\Loader\ArrayLoader; use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\FilterExpression; use Twig\Node\Node; use Twig\Test\NodeTestCase; use Twig\TwigFilter; class FilterTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression('foo', 1); $name = new ConstantExpression('upper', 1); $args = new Node(); $node = new FilterExpression($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 Environment($this->createMock(LoaderInterface::class)); $environment->addFilter(new TwigFilter('bar', 'twig_tests_filter_dummy', ['needs_environment' => true])); $environment->addFilter(new TwigFilter('barbar', 'Twig\Tests\Node\Expression\twig_tests_filter_barbar', ['needs_context' => true, 'is_variadic' => true])); $tests = []; $expr = new ConstantExpression('foo', 1); $node = $this->createFilter($expr, 'upper'); $node = $this->createFilter($node, 'number_format', [new ConstantExpression(2, 1), new ConstantExpression('.', 1), new ConstantExpression(',', 1)]); $tests[] = [$node, 'twig_number_format_filter($this->env, twig_upper_filter($this->env, "foo"), 2, ".", ",")']; // named arguments $date = new ConstantExpression(0, 1); $node = $this->createFilter($date, 'date', [ 'timezone' => new ConstantExpression('America/Chicago', 1), 'format' => new ConstantExpression('d/m/Y H:i:s P', 1), ]); $tests[] = [$node, 'twig_date_format_filter($this->env, 0, "d/m/Y H:i:s P", "America/Chicago")']; // skip an optional argument $date = new ConstantExpression(0, 1); $node = $this->createFilter($date, 'date', [ 'timezone' => new ConstantExpression('America/Chicago', 1), ]); $tests[] = [$node, 'twig_date_format_filter($this->env, 0, null, "America/Chicago")']; // underscores vs camelCase for named arguments $string = new ConstantExpression('abc', 1); $node = $this->createFilter($string, 'reverse', [ 'preserve_keys' => new ConstantExpression(true, 1), ]); $tests[] = [$node, 'twig_reverse_filter($this->env, "abc", true)']; $node = $this->createFilter($string, 'reverse', [ 'preserveKeys' => new ConstantExpression(true, 1), ]); $tests[] = [$node, 'twig_reverse_filter($this->env, "abc", true)']; // filter as an anonymous function $node = $this->createFilter(new ConstantExpression('foo', 1), 'anonymous'); $tests[] = [$node, 'call_user_func_array($this->env->getFilter(\'anonymous\')->getCallable(), ["foo"])']; // needs environment $node = $this->createFilter($string, 'bar'); $tests[] = [$node, 'twig_tests_filter_dummy($this->env, "abc")', $environment]; $node = $this->createFilter($string, 'bar', [new ConstantExpression('bar', 1)]); $tests[] = [$node, 'twig_tests_filter_dummy($this->env, "abc", "bar")', $environment]; // arbitrary named arguments $node = $this->createFilter($string, 'barbar'); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_filter_barbar($context, "abc")', $environment]; $node = $this->createFilter($string, 'barbar', ['foo' => new ConstantExpression('bar', 1)]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_filter_barbar($context, "abc", null, null, ["foo" => "bar"])', $environment]; $node = $this->createFilter($string, 'barbar', ['arg2' => new ConstantExpression('bar', 1)]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_filter_barbar($context, "abc", null, "bar")', $environment]; $node = $this->createFilter($string, 'barbar', [ new ConstantExpression('1', 1), new ConstantExpression('2', 1), new ConstantExpression('3', 1), 'foo' => new ConstantExpression('bar', 1), ]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_filter_barbar($context, "abc", "1", "2", [0 => "3", "foo" => "bar"])', $environment]; return $tests; } public function testCompileWithWrongNamedArgumentName() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown argument "foobar" for filter "date(format, timezone)" at line 1.'); $date = new ConstantExpression(0, 1); $node = $this->createFilter($date, 'date', [ 'foobar' => new ConstantExpression('America/Chicago', 1), ]); $compiler = $this->getCompiler(); $compiler->compile($node); } public function testCompileWithMissingNamedArgument() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Value for argument "from" is required for filter "replace" at line 1.'); $value = new ConstantExpression(0, 1); $node = $this->createFilter($value, 'replace', [ 'to' => new ConstantExpression('foo', 1), ]); $compiler = $this->getCompiler(); $compiler->compile($node); } protected function createFilter($node, $name, array $arguments = []) { $name = new ConstantExpression($name, 1); $arguments = new Node($arguments); return new FilterExpression($node, $name, $arguments, 1); } protected function getEnvironment() { $env = new Environment(new ArrayLoader([])); $env->addFilter(new TwigFilter('anonymous', function () {})); return $env; } } function twig_tests_filter_dummy() { } function twig_tests_filter_barbar($context, $string, $arg1 = null, $arg2 = null, array $args = []) { } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/FunctionTest.php����������������������������������������������0000664�0000000�0000000�00000011475�13624573447�0022713�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Environment; use Twig\Loader\ArrayLoader; use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\FunctionExpression; use Twig\Node\Node; use Twig\Test\NodeTestCase; use Twig\TwigFunction; class FunctionTest extends NodeTestCase { public function testConstructor() { $name = 'function'; $args = new Node(); $node = new FunctionExpression($name, $args, 1); $this->assertEquals($name, $node->getAttribute('name')); $this->assertEquals($args, $node->getNode('arguments')); } public function getTests() { $environment = new Environment($this->createMock(LoaderInterface::class)); $environment->addFunction(new TwigFunction('foo', 'twig_tests_function_dummy', [])); $environment->addFunction(new TwigFunction('bar', 'twig_tests_function_dummy', ['needs_environment' => true])); $environment->addFunction(new TwigFunction('foofoo', 'twig_tests_function_dummy', ['needs_context' => true])); $environment->addFunction(new TwigFunction('foobar', 'twig_tests_function_dummy', ['needs_environment' => true, 'needs_context' => true])); $environment->addFunction(new TwigFunction('barbar', 'Twig\Tests\Node\Expression\twig_tests_function_barbar', ['is_variadic' => true])); $tests = []; $node = $this->createFunction('foo'); $tests[] = [$node, 'twig_tests_function_dummy()', $environment]; $node = $this->createFunction('foo', [new ConstantExpression('bar', 1), new ConstantExpression('foobar', 1)]); $tests[] = [$node, 'twig_tests_function_dummy("bar", "foobar")', $environment]; $node = $this->createFunction('bar'); $tests[] = [$node, 'twig_tests_function_dummy($this->env)', $environment]; $node = $this->createFunction('bar', [new ConstantExpression('bar', 1)]); $tests[] = [$node, 'twig_tests_function_dummy($this->env, "bar")', $environment]; $node = $this->createFunction('foofoo'); $tests[] = [$node, 'twig_tests_function_dummy($context)', $environment]; $node = $this->createFunction('foofoo', [new ConstantExpression('bar', 1)]); $tests[] = [$node, 'twig_tests_function_dummy($context, "bar")', $environment]; $node = $this->createFunction('foobar'); $tests[] = [$node, 'twig_tests_function_dummy($this->env, $context)', $environment]; $node = $this->createFunction('foobar', [new ConstantExpression('bar', 1)]); $tests[] = [$node, 'twig_tests_function_dummy($this->env, $context, "bar")', $environment]; // named arguments $node = $this->createFunction('date', [ 'timezone' => new ConstantExpression('America/Chicago', 1), 'date' => new ConstantExpression(0, 1), ]); $tests[] = [$node, 'twig_date_converter($this->env, 0, "America/Chicago")']; // arbitrary named arguments $node = $this->createFunction('barbar'); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_function_barbar()', $environment]; $node = $this->createFunction('barbar', ['foo' => new ConstantExpression('bar', 1)]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_function_barbar(null, null, ["foo" => "bar"])', $environment]; $node = $this->createFunction('barbar', ['arg2' => new ConstantExpression('bar', 1)]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_function_barbar(null, "bar")', $environment]; $node = $this->createFunction('barbar', [ new ConstantExpression('1', 1), new ConstantExpression('2', 1), new ConstantExpression('3', 1), 'foo' => new ConstantExpression('bar', 1), ]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_function_barbar("1", "2", [0 => "3", "foo" => "bar"])', $environment]; // function as an anonymous function $node = $this->createFunction('anonymous', [new ConstantExpression('foo', 1)]); $tests[] = [$node, 'call_user_func_array($this->env->getFunction(\'anonymous\')->getCallable(), ["foo"])']; return $tests; } protected function createFunction($name, array $arguments = []) { return new FunctionExpression($name, new Node($arguments), 1); } protected function getEnvironment() { $env = new Environment(new ArrayLoader([])); $env->addFunction(new TwigFunction('anonymous', function () {})); return $env; } } function twig_tests_function_dummy() { } function twig_tests_function_barbar($arg1 = null, $arg2 = null, array $args = []) { } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/GetAttrTest.php�����������������������������������������������0000664�0000000�0000000�00000004551�13624573447�0022475�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Node\Expression\ArrayExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\GetAttrExpression; use Twig\Node\Expression\NameExpression; use Twig\Template; use Twig\Test\NodeTestCase; class GetAttrTest extends NodeTestCase { public function testConstructor() { $expr = new NameExpression('foo', 1); $attr = new ConstantExpression('bar', 1); $args = new ArrayExpression([], 1); $args->addElement(new NameExpression('foo', 1)); $args->addElement(new ConstantExpression('bar', 1)); $node = new GetAttrExpression($expr, $attr, $args, Template::ARRAY_CALL, 1); $this->assertEquals($expr, $node->getNode('node')); $this->assertEquals($attr, $node->getNode('attribute')); $this->assertEquals($args, $node->getNode('arguments')); $this->assertEquals(Template::ARRAY_CALL, $node->getAttribute('type')); } public function getTests() { $tests = []; $expr = new NameExpression('foo', 1); $attr = new ConstantExpression('bar', 1); $args = new ArrayExpression([], 1); $node = new GetAttrExpression($expr, $attr, $args, Template::ANY_CALL, 1); $tests[] = [$node, sprintf('%s%s, "bar", [], "any", false, false, false, 1)', $this->getAttributeGetter(), $this->getVariableGetter('foo', 1))]; $node = new GetAttrExpression($expr, $attr, $args, Template::ARRAY_CALL, 1); $tests[] = [$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 ArrayExpression([], 1); $args->addElement(new NameExpression('foo', 1)); $args->addElement(new ConstantExpression('bar', 1)); $node = new GetAttrExpression($expr, $attr, $args, Template::METHOD_CALL, 1); $tests[] = [$node, sprintf('%s%s, "bar", [0 => %s, 1 => "bar"], "method", false, false, false, 1)', $this->getAttributeGetter(), $this->getVariableGetter('foo', 1), $this->getVariableGetter('foo'))]; return $tests; } } �������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/NameTest.php��������������������������������������������������0000664�0000000�0000000�00000002623�13624573447�0022001�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Environment; use Twig\Loader\LoaderInterface; use Twig\Node\Expression\NameExpression; use Twig\Test\NodeTestCase; class NameTest extends NodeTestCase { public function testConstructor() { $node = new NameExpression('foo', 1); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { $node = new NameExpression('foo', 1); $self = new NameExpression('_self', 1); $context = new NameExpression('_context', 1); $env = new Environment($this->createMock(LoaderInterface::class), ['strict_variables' => true]); $env1 = new Environment($this->createMock(LoaderInterface::class), ['strict_variables' => false]); $output = '(isset($context["foo"]) || array_key_exists("foo", $context) ? $context["foo"] : (function () { throw new RuntimeError(\'Variable "foo" does not exist.\', 1, $this->source); })())'; return [ [$node, "// line 1\n".$output, $env], [$node, $this->getVariableGetter('foo', 1), $env1], [$self, "// line 1\n\$this->getTemplateName()"], [$context, "// line 1\n\$context"], ]; } } �������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/NullCoalesceTest.php������������������������������������������0000664�0000000�0000000�00000001322�13624573447�0023465�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\NameExpression; use Twig\Node\Expression\NullCoalesceExpression; use Twig\Test\NodeTestCase; class NullCoalesceTest extends NodeTestCase { public function getTests() { $left = new NameExpression('foo', 1); $right = new ConstantExpression(2, 1); $node = new NullCoalesceExpression($left, $right, 1); return [[$node, "((// line 1\n\$context[\"foo\"]) ?? (2))"]]; } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/ParentTest.php������������������������������������������������0000664�0000000�0000000�00000001313�13624573447�0022345�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Node\Expression\ParentExpression; use Twig\Test\NodeTestCase; class ParentTest extends NodeTestCase { public function testConstructor() { $node = new ParentExpression('foo', 1); $this->assertEquals('foo', $node->getAttribute('name')); } public function getTests() { $tests = []; $tests[] = [new ParentExpression('foo', 1), '$this->renderParentBlock("foo", $context, $blocks)']; return $tests; } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/TestTest.php��������������������������������������������������0000664�0000000�0000000�00000006334�13624573447�0022043�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression; /* * 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. */ use Twig\Environment; use Twig\Loader\ArrayLoader; use Twig\Loader\LoaderInterface; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\Test\NullTest; use Twig\Node\Expression\TestExpression; use Twig\Node\Node; use Twig\Test\NodeTestCase; use Twig\TwigTest; class TestTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression('foo', 1); $name = new ConstantExpression('null', 1); $args = new Node(); $node = new TestExpression($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 Environment($this->createMock(LoaderInterface::class)); $environment->addTest(new TwigTest('barbar', 'Twig\Tests\Node\Expression\twig_tests_test_barbar', ['is_variadic' => true, 'need_context' => true])); $tests = []; $expr = new ConstantExpression('foo', 1); $node = new NullTest($expr, 'null', new Node([]), 1); $tests[] = [$node, '(null === "foo")']; // test as an anonymous function $node = $this->createTest(new ConstantExpression('foo', 1), 'anonymous', [new ConstantExpression('foo', 1)]); $tests[] = [$node, 'call_user_func_array($this->env->getTest(\'anonymous\')->getCallable(), ["foo", "foo"])']; // arbitrary named arguments $string = new ConstantExpression('abc', 1); $node = $this->createTest($string, 'barbar'); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_test_barbar("abc")', $environment]; $node = $this->createTest($string, 'barbar', ['foo' => new ConstantExpression('bar', 1)]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_test_barbar("abc", null, null, ["foo" => "bar"])', $environment]; $node = $this->createTest($string, 'barbar', ['arg2' => new ConstantExpression('bar', 1)]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_test_barbar("abc", null, "bar")', $environment]; $node = $this->createTest($string, 'barbar', [ new ConstantExpression('1', 1), new ConstantExpression('2', 1), new ConstantExpression('3', 1), 'foo' => new ConstantExpression('bar', 1), ]); $tests[] = [$node, 'Twig\Tests\Node\Expression\twig_tests_test_barbar("abc", "1", "2", [0 => "3", "foo" => "bar"])', $environment]; return $tests; } protected function createTest($node, $name, array $arguments = []) { return new TestExpression($node, $name, new Node($arguments), 1); } protected function getEnvironment() { $env = new Environment(new ArrayLoader([])); $env->addTest(new TwigTest('anonymous', function () {})); return $env; } } function twig_tests_test_barbar($string, $arg1 = null, $arg2 = null, array $args = []) { } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Unary/��������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0020643�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Unary/NegTest.php���������������������������������������������0000664�0000000�0000000�00000001476�13624573447�0022735�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Unary; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\Unary\NegUnary; use Twig\Test\NodeTestCase; class NegTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression(1, 1); $node = new NegUnary($expr, 1); $this->assertEquals($expr, $node->getNode('node')); } public function getTests() { $node = new ConstantExpression(1, 1); $node = new NegUnary($node, 1); return [ [$node, '-1'], [new NegUnary($node, 1), '- -1'], ]; } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Unary/NotTest.php���������������������������������������������0000664�0000000�0000000�00000001420�13624573447�0022751�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Unary; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\Unary\NotUnary; use Twig\Test\NodeTestCase; class NotTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression(1, 1); $node = new NotUnary($expr, 1); $this->assertEquals($expr, $node->getNode('node')); } public function getTests() { $node = new ConstantExpression(1, 1); $node = new NotUnary($node, 1); return [ [$node, '!1'], ]; } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/Expression/Unary/PosTest.php���������������������������������������������0000664�0000000�0000000�00000001420�13624573447�0022752�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node\Expression\Unary; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\Unary\PosUnary; use Twig\Test\NodeTestCase; class PosTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression(1, 1); $node = new PosUnary($expr, 1); $this->assertEquals($expr, $node->getNode('node')); } public function getTests() { $node = new ConstantExpression(1, 1); $node = new PosUnary($node, 1); return [ [$node, '+1'], ]; } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/ForTest.php��������������������������������������������������������������0000664�0000000�0000000�00000016755�13624573447�0017523�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Expression\AssignNameExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\NameExpression; use Twig\Node\ForNode; use Twig\Node\IfNode; use Twig\Node\Node; use Twig\Node\PrintNode; use Twig\Test\NodeTestCase; class ForTest extends NodeTestCase { public function testConstructor() { $keyTarget = new AssignNameExpression('key', 1); $valueTarget = new AssignNameExpression('item', 1); $seq = new NameExpression('items', 1); $ifexpr = new ConstantExpression(true, 1); $body = new Node([new PrintNode(new NameExpression('foo', 1), 1)], [], 1); $else = null; $node = new ForNode($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->assertInstanceOf(IfNode::class, $node->getNode('body')); $this->assertEquals($body, $node->getNode('body')->getNode('tests')->getNode(1)->getNode(0)); $this->assertFalse($node->hasNode('else')); $else = new PrintNode(new NameExpression('foo', 1), 1); $node = new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); $node->setAttribute('with_loop', false); $this->assertEquals($else, $node->getNode('else')); } public function getTests() { $tests = []; $keyTarget = new AssignNameExpression('key', 1); $valueTarget = new AssignNameExpression('item', 1); $seq = new NameExpression('items', 1); $ifexpr = null; $body = new Node([new PrintNode(new NameExpression('foo', 1), 1)], [], 1); $else = null; $node = new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); $node->setAttribute('with_loop', false); $tests[] = [$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 AssignNameExpression('k', 1); $valueTarget = new AssignNameExpression('v', 1); $seq = new NameExpression('values', 1); $ifexpr = null; $body = new Node([new PrintNode(new NameExpression('foo', 1), 1)], [], 1); $else = null; $node = new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); $node->setAttribute('with_loop', true); $tests[] = [$node, <<<EOF // line 1 \$context['_parent'] = \$context; \$context['_seq'] = twig_ensure_traversable({$this->getVariableGetter('values')}); \$context['loop'] = [ '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 AssignNameExpression('k', 1); $valueTarget = new AssignNameExpression('v', 1); $seq = new NameExpression('values', 1); $ifexpr = new ConstantExpression(true, 1); $body = new Node([new PrintNode(new NameExpression('foo', 1), 1)], [], 1); $else = null; $node = new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); $node->setAttribute('with_loop', true); $tests[] = [$node, <<<EOF // line 1 \$context['_parent'] = \$context; \$context['_seq'] = twig_ensure_traversable({$this->getVariableGetter('values')}); \$context['loop'] = [ '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 AssignNameExpression('k', 1); $valueTarget = new AssignNameExpression('v', 1); $seq = new NameExpression('values', 1); $ifexpr = null; $body = new Node([new PrintNode(new NameExpression('foo', 1), 1)], [], 1); $else = new PrintNode(new NameExpression('foo', 1), 1); $node = new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body, $else, 1); $node->setAttribute('with_loop', true); $tests[] = [$node, <<<EOF // line 1 \$context['_parent'] = \$context; \$context['_seq'] = twig_ensure_traversable({$this->getVariableGetter('values')}); \$context['_iterated'] = false; \$context['loop'] = [ '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; } } �������������������php-twig-2.12.5/tests/Node/IfTest.php���������������������������������������������������������������0000664�0000000�0000000�00000004440�13624573447�0017317�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\NameExpression; use Twig\Node\IfNode; use Twig\Node\Node; use Twig\Node\PrintNode; use Twig\Test\NodeTestCase; class IfTest extends NodeTestCase { public function testConstructor() { $t = new Node([ new ConstantExpression(true, 1), new PrintNode(new NameExpression('foo', 1), 1), ], [], 1); $else = null; $node = new IfNode($t, $else, 1); $this->assertEquals($t, $node->getNode('tests')); $this->assertFalse($node->hasNode('else')); $else = new PrintNode(new NameExpression('bar', 1), 1); $node = new IfNode($t, $else, 1); $this->assertEquals($else, $node->getNode('else')); } public function getTests() { $tests = []; $t = new Node([ new ConstantExpression(true, 1), new PrintNode(new NameExpression('foo', 1), 1), ], [], 1); $else = null; $node = new IfNode($t, $else, 1); $tests[] = [$node, <<<EOF // line 1 if (true) { echo {$this->getVariableGetter('foo')}; } EOF ]; $t = new Node([ new ConstantExpression(true, 1), new PrintNode(new NameExpression('foo', 1), 1), new ConstantExpression(false, 1), new PrintNode(new NameExpression('bar', 1), 1), ], [], 1); $else = null; $node = new IfNode($t, $else, 1); $tests[] = [$node, <<<EOF // line 1 if (true) { echo {$this->getVariableGetter('foo')}; } elseif (false) { echo {$this->getVariableGetter('bar')}; } EOF ]; $t = new Node([ new ConstantExpression(true, 1), new PrintNode(new NameExpression('foo', 1), 1), ], [], 1); $else = new PrintNode(new NameExpression('bar', 1), 1); $node = new IfNode($t, $else, 1); $tests[] = [$node, <<<EOF // line 1 if (true) { echo {$this->getVariableGetter('foo')}; } else { echo {$this->getVariableGetter('bar')}; } EOF ]; return $tests; } } ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/ImportTest.php�����������������������������������������������������������0000664�0000000�0000000�00000002202�13624573447�0020225�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Expression\AssignNameExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\ImportNode; use Twig\Test\NodeTestCase; class ImportTest extends NodeTestCase { public function testConstructor() { $macro = new ConstantExpression('foo.twig', 1); $var = new AssignNameExpression('macro', 1); $node = new ImportNode($macro, $var, 1); $this->assertEquals($macro, $node->getNode('expr')); $this->assertEquals($var, $node->getNode('var')); } public function getTests() { $tests = []; $macro = new ConstantExpression('foo.twig', 1); $var = new AssignNameExpression('macro', 1); $node = new ImportNode($macro, $var, 1); $tests[] = [$node, <<<EOF // line 1 \$macros["macro"] = \$this->macros["macro"] = \$this->loadTemplate("foo.twig", null, 1)->unwrap(); EOF ]; return $tests; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/IncludeTest.php����������������������������������������������������������0000664�0000000�0000000�00000005472�13624573447�0020352�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Expression\ArrayExpression; use Twig\Node\Expression\ConditionalExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\IncludeNode; use Twig\Test\NodeTestCase; class IncludeTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression('foo.twig', 1); $node = new IncludeNode($expr, null, false, false, 1); $this->assertFalse($node->hasNode('variables')); $this->assertEquals($expr, $node->getNode('expr')); $this->assertFalse($node->getAttribute('only')); $vars = new ArrayExpression([new ConstantExpression('foo', 1), new ConstantExpression(true, 1)], 1); $node = new IncludeNode($expr, $vars, true, false, 1); $this->assertEquals($vars, $node->getNode('variables')); $this->assertTrue($node->getAttribute('only')); } public function getTests() { $tests = []; $expr = new ConstantExpression('foo.twig', 1); $node = new IncludeNode($expr, null, false, false, 1); $tests[] = [$node, <<<EOF // line 1 \$this->loadTemplate("foo.twig", null, 1)->display(\$context); EOF ]; $expr = new ConditionalExpression( new ConstantExpression(true, 1), new ConstantExpression('foo', 1), new ConstantExpression('foo', 1), 0 ); $node = new IncludeNode($expr, null, false, false, 1); $tests[] = [$node, <<<EOF // line 1 \$this->loadTemplate(((true) ? ("foo") : ("foo")), null, 1)->display(\$context); EOF ]; $expr = new ConstantExpression('foo.twig', 1); $vars = new ArrayExpression([new ConstantExpression('foo', 1), new ConstantExpression(true, 1)], 1); $node = new IncludeNode($expr, $vars, false, false, 1); $tests[] = [$node, <<<EOF // line 1 \$this->loadTemplate("foo.twig", null, 1)->display(twig_array_merge(\$context, ["foo" => true])); EOF ]; $node = new IncludeNode($expr, $vars, true, false, 1); $tests[] = [$node, <<<EOF // line 1 \$this->loadTemplate("foo.twig", null, 1)->display(twig_to_array(["foo" => true])); EOF ]; $node = new IncludeNode($expr, $vars, true, true, 1); $tests[] = [$node, <<<EOF // line 1 \$__internal_%s = null; try { \$__internal_%s = \$this->loadTemplate("foo.twig", null, 1); } catch (LoaderError \$e) { // ignore missing template } if (\$__internal_%s) { \$__internal_%s->display(twig_to_array(["foo" => true])); } EOF , null, true]; return $tests; } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/MacroTest.php������������������������������������������������������������0000664�0000000�0000000�00000003343�13624573447�0020023�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\NameExpression; use Twig\Node\MacroNode; use Twig\Node\Node; use Twig\Node\TextNode; use Twig\Test\NodeTestCase; class MacroTest extends NodeTestCase { public function testConstructor() { $body = new TextNode('foo', 1); $arguments = new Node([new NameExpression('foo', 1)], [], 1); $node = new MacroNode('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 TextNode('foo', 1); $arguments = new Node([ 'foo' => new ConstantExpression(null, 1), 'bar' => new ConstantExpression('Foo', 1), ], [], 1); $node = new MacroNode('foo', $body, $arguments, 1); return [ [$node, <<<EOF // line 1 public function macro_foo(\$__foo__ = null, \$__bar__ = "Foo", ...\$__varargs__) { \$macros = \$this->macros; \$context = \$this->env->mergeGlobals([ "foo" => \$__foo__, "bar" => \$__bar__, "varargs" => \$__varargs__, ]); \$blocks = []; ob_start(function () { return ''; }); try { echo "foo"; return ('' === \$tmp = ob_get_contents()) ? '' : new Markup(\$tmp, \$this->env->getCharset()); } finally { ob_end_clean(); } } EOF ], ]; } } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/ModuleTest.php�����������������������������������������������������������0000664�0000000�0000000�00000015661�13624573447�0020215�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Environment; use Twig\Loader\LoaderInterface; use Twig\Node\Expression\AssignNameExpression; use Twig\Node\Expression\ConditionalExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\ImportNode; use Twig\Node\ModuleNode; use Twig\Node\Node; use Twig\Node\SetNode; use Twig\Node\TextNode; use Twig\Source; use Twig\Test\NodeTestCase; class ModuleTest extends NodeTestCase { public function testConstructor() { $body = new TextNode('foo', 1); $parent = new ConstantExpression('layout.twig', 1); $blocks = new Node(); $macros = new Node(); $traits = new Node(); $source = new Source('{{ foo }}', 'foo.twig'); $node = new ModuleNode($body, $parent, $blocks, $macros, $traits, new Node([]), $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 Environment($this->createMock(LoaderInterface::class)); $tests = []; $body = new TextNode('foo', 1); $extends = null; $blocks = new Node(); $macros = new Node(); $traits = new Node(); $source = new Source('{{ foo }}', 'foo.twig'); $node = new ModuleNode($body, $extends, $blocks, $macros, $traits, new Node([]), $source); $tests[] = [$node, <<<EOF <?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Extension\SandboxExtension; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* foo.twig */ class __TwigTemplate_%x extends \Twig\Template { private \$source; private \$macros = []; public function __construct(Environment \$env) { parent::__construct(\$env); \$this->source = \$this->getSourceContext(); \$this->parent = false; \$this->blocks = [ ]; } protected function doDisplay(array \$context, array \$blocks = []) { \$macros = \$this->macros; // line 1 echo "foo"; } public function getTemplateName() { return "foo.twig"; } public function getDebugInfo() { return array ( 37 => 1,); } public function getSourceContext() { return new Source("", "foo.twig", ""); } } EOF , $twig, true]; $import = new ImportNode(new ConstantExpression('foo.twig', 1), new AssignNameExpression('macro', 1), 2); $body = new Node([$import]); $extends = new ConstantExpression('layout.twig', 1); $node = new ModuleNode($body, $extends, $blocks, $macros, $traits, new Node([]), $source); $tests[] = [$node, <<<EOF <?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Extension\SandboxExtension; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* foo.twig */ class __TwigTemplate_%x extends \Twig\Template { private \$source; private \$macros = []; public function __construct(Environment \$env) { parent::__construct(\$env); \$this->source = \$this->getSourceContext(); \$this->blocks = [ ]; } protected function doGetParent(array \$context) { // line 1 return "layout.twig"; } protected function doDisplay(array \$context, array \$blocks = []) { \$macros = \$this->macros; // line 2 \$macros["macro"] = \$this->macros["macro"] = \$this->loadTemplate("foo.twig", "foo.twig", 2)->unwrap(); // line 1 \$this->parent = \$this->loadTemplate("layout.twig", "foo.twig", 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 ( 43 => 1, 41 => 2, 34 => 1,); } public function getSourceContext() { return new Source("", "foo.twig", ""); } } EOF , $twig, true]; $set = new SetNode(false, new Node([new AssignNameExpression('foo', 4)]), new Node([new ConstantExpression('foo', 4)]), 4); $body = new Node([$set]); $extends = new ConditionalExpression( new ConstantExpression(true, 2), new ConstantExpression('foo', 2), new ConstantExpression('foo', 2), 2 ); $twig = new Environment($this->createMock(LoaderInterface::class), ['debug' => true]); $node = new ModuleNode($body, $extends, $blocks, $macros, $traits, new Node([]), $source); $tests[] = [$node, <<<EOF <?php use Twig\Environment; use Twig\Error\LoaderError; use Twig\Error\RuntimeError; use Twig\Extension\SandboxExtension; use Twig\Markup; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityNotAllowedTagError; use Twig\Sandbox\SecurityNotAllowedFilterError; use Twig\Sandbox\SecurityNotAllowedFunctionError; use Twig\Source; use Twig\Template; /* foo.twig */ class __TwigTemplate_%x extends \Twig\Template { private \$source; private \$macros = []; public function __construct(Environment \$env) { parent::__construct(\$env); \$this->source = \$this->getSourceContext(); \$this->blocks = [ ]; } protected function doGetParent(array \$context) { // line 2 return \$this->loadTemplate(((true) ? ("foo") : ("foo")), "foo.twig", 2); } protected function doDisplay(array \$context, array \$blocks = []) { \$macros = \$this->macros; // 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 ( 43 => 2, 41 => 4, 34 => 2,); } public function getSourceContext() { return new Source("{{ foo }}", "foo.twig", ""); } } EOF , $twig, true]; return $tests; } } �������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/PrintTest.php������������������������������������������������������������0000664�0000000�0000000�00000001372�13624573447�0020056�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Expression\ConstantExpression; use Twig\Node\PrintNode; use Twig\Test\NodeTestCase; class PrintTest extends NodeTestCase { public function testConstructor() { $expr = new ConstantExpression('foo', 1); $node = new PrintNode($expr, 1); $this->assertEquals($expr, $node->getNode('expr')); } public function getTests() { $tests = []; $tests[] = [new PrintNode(new ConstantExpression('foo', 1), 1), "// line 1\necho \"foo\";"]; return $tests; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Node/SandboxTest.php����������������������������������������������������������0000664�0000000�0000000�00000001700�13624573447�0020353�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\SandboxNode; use Twig\Node\TextNode; use Twig\Test\NodeTestCase; class SandboxTest extends NodeTestCase { public function testConstructor() { $body = new TextNode('foo', 1); $node = new SandboxNode($body, 1); $this->assertEquals($body, $node->getNode('body')); } public function getTests() { $tests = []; $body = new TextNode('foo', 1); $node = new SandboxNode($body, 1); $tests[] = [$node, <<<EOF // line 1 if (!\$alreadySandboxed = \$this->sandbox->isSandboxed()) { \$this->sandbox->enableSandbox(); } echo "foo"; if (!\$alreadySandboxed) { \$this->sandbox->disableSandbox(); } EOF ]; return $tests; } } ����������������������������������������������������������������php-twig-2.12.5/tests/Node/SetTest.php��������������������������������������������������������������0000664�0000000�0000000�00000004703�13624573447�0017516�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Expression\AssignNameExpression; use Twig\Node\Expression\ConstantExpression; use Twig\Node\Expression\NameExpression; use Twig\Node\Node; use Twig\Node\PrintNode; use Twig\Node\SetNode; use Twig\Node\TextNode; use Twig\Test\NodeTestCase; class SetTest extends NodeTestCase { public function testConstructor() { $names = new Node([new AssignNameExpression('foo', 1)], [], 1); $values = new Node([new ConstantExpression('foo', 1)], [], 1); $node = new SetNode(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 = []; $names = new Node([new AssignNameExpression('foo', 1)], [], 1); $values = new Node([new ConstantExpression('foo', 1)], [], 1); $node = new SetNode(false, $names, $values, 1); $tests[] = [$node, <<<EOF // line 1 \$context["foo"] = "foo"; EOF ]; $names = new Node([new AssignNameExpression('foo', 1)], [], 1); $values = new Node([new PrintNode(new ConstantExpression('foo', 1), 1)], [], 1); $node = new SetNode(true, $names, $values, 1); $tests[] = [$node, <<<EOF // line 1 ob_start(function () { return ''; }); echo "foo"; \$context["foo"] = ('' === \$tmp = ob_get_clean()) ? '' : new Markup(\$tmp, \$this->env->getCharset()); EOF ]; $names = new Node([new AssignNameExpression('foo', 1)], [], 1); $values = new TextNode('foo', 1); $node = new SetNode(true, $names, $values, 1); $tests[] = [$node, <<<EOF // line 1 \$context["foo"] = ('' === \$tmp = "foo") ? '' : new Markup(\$tmp, \$this->env->getCharset()); EOF ]; $names = new Node([new AssignNameExpression('foo', 1), new AssignNameExpression('bar', 1)], [], 1); $values = new Node([new ConstantExpression('foo', 1), new NameExpression('bar', 1)], [], 1); $node = new SetNode(false, $names, $values, 1); $tests[] = [$node, <<<EOF // line 1 list(\$context["foo"], \$context["bar"]) = ["foo", {$this->getVariableGetter('bar')}]; EOF ]; return $tests; } } �������������������������������������������������������������php-twig-2.12.5/tests/Node/SpacelessTest.php��������������������������������������������������������0000664�0000000�0000000�00000001775�13624573447�0020713�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\Node; use Twig\Node\SpacelessNode; use Twig\Node\TextNode; use Twig\Test\NodeTestCase; class SpacelessTest extends NodeTestCase { public function testConstructor() { $body = new Node([new TextNode('<div> <div> foo </div> </div>', 1)]); $node = new SpacelessNode($body, 1); $this->assertEquals($body, $node->getNode('body')); } public function getTests() { $body = new Node([new TextNode('<div> <div> foo </div> </div>', 1)]); $node = new SpacelessNode($body, 1); return [ [$node, <<<EOF // line 1 ob_start(function () { return ''; }); echo "<div> <div> foo </div> </div>"; echo trim(preg_replace('/>\s+</', '><', ob_get_clean())); EOF ], ]; } } ���php-twig-2.12.5/tests/Node/TextTest.php�������������������������������������������������������������0000664�0000000�0000000�00000001201�13624573447�0017675�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Node; /* * 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. */ use Twig\Node\TextNode; use Twig\Test\NodeTestCase; class TextTest extends NodeTestCase { public function testConstructor() { $node = new TextNode('foo', 1); $this->assertEquals('foo', $node->getAttribute('data')); } public function getTests() { $tests = []; $tests[] = [new TextNode('foo', 1), "// line 1\necho \"foo\";"]; return $tests; } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/NodeVisitor/������������������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0016766�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/NodeVisitor/OptimizerTest.php�������������������������������������������������0000664�0000000�0000000�00000010650�13624573447�0022323�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\NodeVisitor; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Environment; use Twig\Loader\LoaderInterface; use Twig\Node\Expression\BlockReferenceExpression; use Twig\Node\Expression\ParentExpression; use Twig\Node\ForNode; use Twig\Node\Node; use Twig\Source; class OptimizerTest extends TestCase { public function testRenderBlockOptimizer() { $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $stream = $env->parse($env->tokenize(new Source('{{ block("foo") }}', 'index'))); $node = $stream->getNode('body')->getNode(0); $this->assertInstanceOf(BlockReferenceExpression::class, $node); $this->assertTrue($node->getAttribute('output')); } public function testRenderParentBlockOptimizer() { $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false, 'autoescape' => false]); $stream = $env->parse($env->tokenize(new Source('{% extends "foo" %}{% block content %}{{ parent() }}{% endblock %}', 'index'))); $node = $stream->getNode('blocks')->getNode('content')->getNode(0)->getNode('body'); $this->assertInstanceOf(ParentExpression::class, $node); $this->assertTrue($node->getAttribute('output')); } /** * @dataProvider getTestsForForOptimizer */ public function testForOptimizer($template, $expected) { $env = new Environment($this->createMock(LoaderInterface::class), ['cache' => false]); $stream = $env->parse($env->tokenize(new 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 [ ['{% for i in foo %}{% endfor %}', ['i' => false]], ['{% for i in foo %}{{ loop.index }}{% endfor %}', ['i' => true]], ['{% for i in foo %}{% for j in foo %}{% endfor %}{% endfor %}', ['i' => false, 'j' => false]], ['{% for i in foo %}{% include "foo" %}{% endfor %}', ['i' => true]], ['{% for i in foo %}{% include "foo" only %}{% endfor %}', ['i' => false]], ['{% for i in foo %}{% include "foo" with { "foo": "bar" } only %}{% endfor %}', ['i' => false]], ['{% for i in foo %}{% include "foo" with { "foo": loop.index } only %}{% endfor %}', ['i' => true]], ['{% for i in foo %}{% for j in foo %}{{ loop.index }}{% endfor %}{% endfor %}', ['i' => false, 'j' => true]], ['{% for i in foo %}{% for j in foo %}{{ loop.parent.loop.index }}{% endfor %}{% endfor %}', ['i' => true, 'j' => true]], ['{% for i in foo %}{% set l = loop %}{% for j in foo %}{{ l.index }}{% endfor %}{% endfor %}', ['i' => true, 'j' => false]], ['{% for i in foo %}{% for j in foo %}{{ foo.parent.loop.index }}{% endfor %}{% endfor %}', ['i' => false, 'j' => false]], ['{% for i in foo %}{% for j in foo %}{{ loop["parent"].loop.index }}{% endfor %}{% endfor %}', ['i' => true, 'j' => true]], ['{% for i in foo %}{{ include("foo") }}{% endfor %}', ['i' => true]], ['{% for i in foo %}{{ include("foo", with_context = false) }}{% endfor %}', ['i' => false]], ['{% for i in foo %}{{ include("foo", with_context = true) }}{% endfor %}', ['i' => true]], ['{% for i in foo %}{{ include("foo", { "foo": "bar" }, with_context = false) }}{% endfor %}', ['i' => false]], ['{% for i in foo %}{{ include("foo", { "foo": loop.index }, with_context = false) }}{% endfor %}', ['i' => true]], ]; } public function checkForConfiguration(Node $node, $target, $withLoop) { foreach ($node as $n) { if ($n instanceof ForNode) { 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; } } } } ����������������������������������������������������������������������������������������php-twig-2.12.5/tests/ParserTest.php����������������������������������������������������������������0000664�0000000�0000000�00000013747�13624573447�0017342�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Environment; use Twig\Error\SyntaxError; use Twig\Loader\LoaderInterface; use Twig\Node\Node; use Twig\Node\SetNode; use Twig\Node\TextNode; use Twig\Parser; use Twig\Source; use Twig\Token; use Twig\TokenParser\AbstractTokenParser; use Twig\TokenStream; class ParserTest extends TestCase { public function testUnknownTag() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "foo" tag. Did you mean "for" at line 1?'); $stream = new TokenStream([ new Token(Token::BLOCK_START_TYPE, '', 1), new Token(Token::NAME_TYPE, 'foo', 1), new Token(Token::BLOCK_END_TYPE, '', 1), new Token(Token::EOF_TYPE, '', 1), ]); $parser = new Parser(new Environment($this->createMock(LoaderInterface::class))); $parser->parse($stream); } public function testUnknownTagWithoutSuggestions() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unknown "foobar" tag at line 1.'); $stream = new TokenStream([ new Token(Token::BLOCK_START_TYPE, '', 1), new Token(Token::NAME_TYPE, 'foobar', 1), new Token(Token::BLOCK_END_TYPE, '', 1), new Token(Token::EOF_TYPE, '', 1), ]); $parser = new Parser(new Environment($this->createMock(LoaderInterface::class))); $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 [ [ new Node([new TextNode(' ', 1)]), new Node([]), ], [ $input = new Node([new SetNode(false, new Node(), new Node(), 1)]), $input, ], [ $input = new Node([new SetNode(true, new Node(), new Node([new Node([new TextNode('foo', 1)])]), 1)]), $input, ], ]; } /** * @dataProvider getFilterBodyNodesDataThrowsException */ public function testFilterBodyNodesThrowsException($input) { $this->expectException(SyntaxError::class); $parser = $this->getParser(); $m = new \ReflectionMethod($parser, 'filterBodyNodes'); $m->setAccessible(true); $m->invoke($parser, $input); } public function getFilterBodyNodesDataThrowsException() { return [ [new TextNode('foo', 1)], [new Node([new Node([new TextNode('foo', 1)])])], ]; } /** * @dataProvider getFilterBodyNodesWithBOMData */ public function testFilterBodyNodesWithBOM($emptyNode) { $parser = $this->getParser(); $m = new \ReflectionMethod($parser, 'filterBodyNodes'); $m->setAccessible(true); $this->assertNull($m->invoke($parser, new TextNode(\chr(0xEF).\chr(0xBB).\chr(0xBF).$emptyNode, 1))); } public function getFilterBodyNodesWithBOMData() { return [ [' '], ["\t"], ["\n"], ["\n\t\n "], ]; } public function testParseIsReentrant() { $twig = new Environment($this->createMock(LoaderInterface::class), [ 'autoescape' => false, 'optimizations' => 0, ]); $twig->addTokenParser(new TestTokenParser()); $parser = new Parser($twig); $parser->parse(new TokenStream([ new Token(Token::BLOCK_START_TYPE, '', 1), new Token(Token::NAME_TYPE, 'test', 1), new Token(Token::BLOCK_END_TYPE, '', 1), new Token(Token::VAR_START_TYPE, '', 1), new Token(Token::NAME_TYPE, 'foo', 1), new Token(Token::VAR_END_TYPE, '', 1), new Token(Token::EOF_TYPE, '', 1), ])); $this->assertNull($parser->getParent()); } public function testGetVarName() { $twig = new Environment($this->createMock(LoaderInterface::class), [ 'autoescape' => false, 'optimizations' => 0, ]); $twig->parse($twig->tokenize(new 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 Parser(new Environment($this->createMock(LoaderInterface::class))); $parser->setParent(new Node()); $p = new \ReflectionProperty($parser, 'stream'); $p->setAccessible(true); $p->setValue($parser, new TokenStream([])); return $parser; } } class TestTokenParser extends AbstractTokenParser { public function parse(Token $token) { // simulate the parsing of another template right in the middle of the parsing of the current template $this->parser->parse(new TokenStream([ new Token(Token::BLOCK_START_TYPE, '', 1), new Token(Token::NAME_TYPE, 'extends', 1), new Token(Token::STRING_TYPE, 'base', 1), new Token(Token::BLOCK_END_TYPE, '', 1), new Token(Token::EOF_TYPE, '', 1), ])); $this->parser->getStream()->expect(Token::BLOCK_END_TYPE); return new Node([]); } public function getTag() { return 'test'; } } �������������������������php-twig-2.12.5/tests/Profiler/���������������������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0016303�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Profiler/Dumper/��������������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0017537�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Profiler/Dumper/AbstractTest.php����������������������������������������������0000664�0000000�0000000�00000006050�13624573447�0022654�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Profiler\Dumper; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Profiler\Profile; abstract class AbstractTest extends TestCase { protected function getProfile() { $profile = new Profile('main'); $subProfiles = [ $this->getIndexProfile( [ $this->getEmbeddedBlockProfile(), $this->getEmbeddedTemplateProfile( [ $this->getIncludedTemplateProfile(), ] ), $this->getMacroProfile(), $this->getEmbeddedTemplateProfile( [ $this->getIncludedTemplateProfile(), ] ), ] ), ]; $p = new \ReflectionProperty($profile, 'profiles'); $p->setAccessible(true); $p->setValue($profile, $subProfiles); return $profile; } private function getIndexProfile(array $subProfiles = []) { return $this->generateProfile('main', 1, 'template', 'index.twig', $subProfiles); } private function getEmbeddedBlockProfile(array $subProfiles = []) { return $this->generateProfile('body', 0.0001, 'block', 'embedded.twig', $subProfiles); } private function getEmbeddedTemplateProfile(array $subProfiles = []) { return $this->generateProfile('main', 0.0001, 'template', 'embedded.twig', $subProfiles); } private function getIncludedTemplateProfile(array $subProfiles = []) { return $this->generateProfile('main', 0.0001, 'template', 'included.twig', $subProfiles); } private function getMacroProfile(array $subProfiles = []) { return $this->generateProfile('foo', 0.0001, 'macro', 'index.twig', $subProfiles); } /** * @param string $name * @param float $duration * @param bool $isTemplate * @param string $type * @param string $templateName * @param array $subProfiles * * @return Profile */ private function generateProfile($name, $duration, $type, $templateName, array $subProfiles = []) { $profile = new Profile($templateName, $type, $name); $p = new \ReflectionProperty($profile, 'profiles'); $p->setAccessible(true); $p->setValue($profile, $subProfiles); $starts = new \ReflectionProperty($profile, 'starts'); $starts->setAccessible(true); $starts->setValue($profile, [ 'wt' => 0, 'mu' => 0, 'pmu' => 0, ]); $ends = new \ReflectionProperty($profile, 'ends'); $ends->setAccessible(true); $ends->setValue($profile, [ 'wt' => $duration, 'mu' => 0, 'pmu' => 0, ]); return $profile; } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Profiler/Dumper/BlackfireTest.php���������������������������������������������0000664�0000000�0000000�00000001465�13624573447�0023000�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Profiler\Dumper; /* * 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. */ use Twig\Profiler\Dumper\BlackfireDumper; class BlackfireTest extends AbstractTest { public function testDump() { $dumper = new BlackfireDumper(); $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())); } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Profiler/Dumper/HtmlTest.php��������������������������������������������������0000664�0000000�0000000�00000002063�13624573447�0022015�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Profiler\Dumper; /* * 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. */ use Twig\Profiler\Dumper\HtmlDumper; class HtmlTest extends AbstractTest { public function testDump() { $dumper = new HtmlDumper(); $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())); } } �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Profiler/Dumper/TextTest.php��������������������������������������������������0000664�0000000�0000000�00000001262�13624573447�0022035�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Profiler\Dumper; /* * 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. */ use Twig\Profiler\Dumper\TextDumper; class TextTest extends AbstractTest { public function testDump() { $dumper = new TextDumper(); $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())); } } ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Profiler/ProfileTest.php������������������������������������������������������0000664�0000000�0000000�00000006576�13624573447�0021272�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Profiler; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Profiler\Profile; class ProfileTest extends TestCase { public function testConstructor() { $profile = new Profile('template', 'type', 'name'); $this->assertEquals('template', $profile->getTemplate()); $this->assertEquals('type', $profile->getType()); $this->assertEquals('name', $profile->getName()); } public function testIsRoot() { $profile = new Profile('template', Profile::ROOT); $this->assertTrue($profile->isRoot()); $profile = new Profile('template', Profile::TEMPLATE); $this->assertFalse($profile->isRoot()); } public function testIsTemplate() { $profile = new Profile('template', Profile::TEMPLATE); $this->assertTrue($profile->isTemplate()); $profile = new Profile('template', Profile::ROOT); $this->assertFalse($profile->isTemplate()); } public function testIsBlock() { $profile = new Profile('template', Profile::BLOCK); $this->assertTrue($profile->isBlock()); $profile = new Profile('template', Profile::ROOT); $this->assertFalse($profile->isBlock()); } public function testIsMacro() { $profile = new Profile('template', Profile::MACRO); $this->assertTrue($profile->isMacro()); $profile = new Profile('template', Profile::ROOT); $this->assertFalse($profile->isMacro()); } public function testGetAddProfile() { $profile = new Profile(); $profile->addProfile($a = new Profile()); $profile->addProfile($b = new Profile()); $this->assertSame([$a, $b], $profile->getProfiles()); $this->assertSame([$a, $b], iterator_to_array($profile)); } public function testGetDuration() { $profile = new Profile(); usleep(1); $profile->leave(); $this->assertTrue($profile->getDuration() > 0, sprintf('Expected duration > 0, got: %f', $profile->getDuration())); } public function testSerialize() { $profile = new Profile('template', 'type', 'name'); $profile1 = new 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 Profile(); usleep(1); $profile->leave(); $profile->reset(); $this->assertEquals(0, $profile->getDuration()); } } ����������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/TemplateTest.php��������������������������������������������������������������0000664�0000000�0000000�00000056745�13624573447�0017666�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Environment; use Twig\Error\RuntimeError; use Twig\Extension\SandboxExtension; use Twig\Loader\ArrayLoader; use Twig\Loader\LoaderInterface; use Twig\Sandbox\SecurityError; use Twig\Sandbox\SecurityPolicy; use Twig\Template; class TemplateTest extends TestCase { public function testDisplayBlocksAcceptTemplateOnlyAsBlocks() { $this->expectException(\LogicException::class); $twig = new Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($twig); $template->displayBlock('foo', [], ['foo' => [new \stdClass(), 'foo']]); } /** * @dataProvider getAttributeExceptions */ public function testGetAttributeExceptions($template, $message) { $templates = ['index' => $template]; $env = new Environment(new ArrayLoader($templates), ['strict_variables' => true]); $template = $env->load('index'); $context = [ 'string' => 'foo', 'null' => null, 'empty_array' => [], 'array' => ['foo' => 'foo'], 'array_access' => new TemplateArrayAccessObject(), 'magic_exception' => new TemplateMagicPropertyObjectWithException(), 'object' => new \stdClass(), ]; try { $template->render($context); $this->fail('Accessing an invalid attribute should throw an exception.'); } catch (RuntimeError $e) { $this->assertSame(sprintf($message, 'index'), $e->getMessage()); } } public function getAttributeExceptions() { return [ ['{{ string["a"] }}', 'Impossible to access a key ("a") on a string variable ("foo") in "%s" at line 1.'], ['{{ null["a"] }}', 'Impossible to access a key ("a") on a null variable in "%s" at line 1.'], ['{{ empty_array["a"] }}', 'Key "a" does not exist as the array is empty in "%s" at line 1.'], ['{{ array["a"] }}', 'Key "a" for array with keys "foo" does not exist in "%s" at line 1.'], ['{{ array_access["a"] }}', 'Key "a" in object with ArrayAccess of class "Twig\Tests\TemplateArrayAccessObject" does not exist in "%s" at line 1.'], ['{{ string.a }}', 'Impossible to access an attribute ("a") on a string variable ("foo") in "%s" at line 1.'], ['{{ string.a() }}', 'Impossible to invoke a method ("a") on a string variable ("foo") in "%s" at line 1.'], ['{{ null.a }}', 'Impossible to access an attribute ("a") on a null variable in "%s" at line 1.'], ['{{ null.a() }}', 'Impossible to invoke a method ("a") on a null variable in "%s" at line 1.'], ['{{ array.a() }}', 'Impossible to invoke a method ("a") on an array in "%s" at line 1.'], ['{{ empty_array.a }}', 'Key "a" does not exist as the array is empty in "%s" at line 1.'], ['{{ array.a }}', 'Key "a" for array with keys "foo" does not exist in "%s" at line 1.'], ['{{ attribute(array, -10) }}', 'Key "-10" for array with keys "foo" does not exist in "%s" at line 1.'], ['{{ 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\Tests\TemplateArrayAccessObject" in "%s" at line 1.'], ['{% 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\Tests\TemplateArrayAccessObject" in "%s" at line 1.'], ['{{ 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.'], ['{{ 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 Environment($this->createMock(LoaderInterface::class)); $policy = new SecurityPolicy([], [], [/*method*/], [/*prop*/], []); $twig->addExtension(new SandboxExtension($policy, !$allowed)); $template = new TemplateForTest($twig); try { twig_get_attribute($twig, $template->getSourceContext(), $object, $item, [], 'any', false, false, true); if (!$allowed) { $this->fail(); } else { $this->addToAssertionCount(1); } } catch (SecurityError $e) { if ($allowed) { $this->fail(); } else { $this->addToAssertionCount(1); } $this->assertStringContainsString('is not allowed', $e->getMessage()); } } public function getGetAttributeWithSandbox() { return [ [new TemplatePropertyObject(), 'defined', false], [new TemplatePropertyObject(), 'defined', true], [new TemplateMethodObject(), 'defined', false], [new TemplateMethodObject(), 'defined', true], ]; } public function testRenderBlockWithUndefinedBlock() { $this->expectException(RuntimeError::class); $this->expectExceptionMessage('Block "unknown" on template "index.twig" does not exist in "index.twig".'); $twig = new Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($twig, 'index.twig'); try { $template->renderBlock('unknown', []); } catch (\Exception $e) { ob_end_clean(); throw $e; } } public function testDisplayBlockWithUndefinedBlock() { $this->expectException(RuntimeError::class); $this->expectExceptionMessage('Block "unknown" on template "index.twig" does not exist in "index.twig".'); $twig = new Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($twig, 'index.twig'); $template->displayBlock('unknown', []); } public function testDisplayBlockWithUndefinedParentBlock() { $this->expectException(RuntimeError::class); $this->expectExceptionMessage('Block "foo" should not call parent() in "index.twig" as the block does not exist in the parent template "parent.twig"'); $twig = new Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($twig, 'parent.twig'); $template->displayBlock('foo', [], ['foo' => [new TemplateForTest($twig, 'index.twig'), 'block_foo']], false); } public function testGetAttributeOnArrayWithConfusableKey() { $twig = new Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($twig); $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 Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($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 Environment($this->createMock(LoaderInterface::class), ['strict_variables' => true]); $template = new TemplateForTest($twig); if ($defined) { $this->assertEquals($value, twig_get_attribute($twig, $template->getSourceContext(), $object, $item, $arguments, $type)); } else { $this->expectException(RuntimeError::class); if (null !== $exceptionMessage) { $this->expectExceptionMessage($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 Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($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 Environment($this->createMock(LoaderInterface::class), ['strict_variables' => true]); $template = new TemplateForTest($twig); $this->assertEquals($defined, twig_get_attribute($twig, $template->getSourceContext(), $object, $item, $arguments, $type, true)); } public function testGetAttributeCallExceptions() { $twig = new Environment($this->createMock(LoaderInterface::class)); $template = new TemplateForTest($twig); $object = new TemplateMagicMethodExceptionObject(); $this->assertNull(twig_get_attribute($twig, $template->getSourceContext(), $object, 'foo')); } public function getGetAttributeTests() { $array = [ 'defined' => 'defined', 'zero' => 0, 'null' => null, '1' => 1, 'bar' => true, 'foo' => true, 'baz' => 'baz', 'baf' => 'baf', '09' => '09', '+4' => '+4', ]; $objectArray = new TemplateArrayAccessObject(); $arrayObject = new \ArrayObject($array); $stdObject = (object) $array; $magicPropertyObject = new TemplateMagicPropertyObject(); $propertyObject = new TemplatePropertyObject(); $propertyObject1 = new TemplatePropertyObjectAndIterator(); $propertyObject2 = new TemplatePropertyObjectAndArrayAccess(); $propertyObject3 = new TemplatePropertyObjectDefinedWithUndefinedValue(); $methodObject = new TemplateMethodObject(); $magicMethodObject = new TemplateMagicMethodObject(); $anyType = Template::ANY_CALL; $methodType = Template::METHOD_CALL; $arrayType = Template::ARRAY_CALL; $basicTests = [ // array(defined, value, property to fetch) [true, 'defined', 'defined'], [false, null, 'undefined'], [false, null, 'protected'], [true, 0, 'zero'], [true, 1, 1], [true, 1, 1.0], [true, null, 'null'], [true, true, 'bar'], [true, true, 'foo'], [true, 'baz', 'baz'], [true, 'baf', 'baf'], [true, '09', '09'], [true, '+4', '+4'], ]; $testObjects = [ // array(object, type of fetch) [$array, $arrayType], [$objectArray, $arrayType], [$arrayObject, $anyType], [$stdObject, $anyType], [$magicPropertyObject, $anyType], [$methodObject, $methodType], [$methodObject, $anyType], [$propertyObject, $anyType], [$propertyObject1, $anyType], [$propertyObject2, $anyType], ]; $tests = []; foreach ($testObjects as $testObject) { foreach ($basicTests as $test) { // properties cannot be numbers if (($testObject[0] instanceof \stdClass || $testObject[0] instanceof TemplatePropertyObject) && is_numeric($test[2])) { continue; } if ('+4' === $test[2] && $methodObject === $testObject[0]) { continue; } $tests[] = [$test[0], $test[1], $testObject[0], $test[2], [], $testObject[1]]; } } // additional properties tests $tests = array_merge($tests, [ [true, null, $propertyObject3, 'foo', [], $anyType], ]); // additional method tests $tests = array_merge($tests, [ [true, 'defined', $methodObject, 'defined', [], $methodType], [true, 'defined', $methodObject, 'DEFINED', [], $methodType], [true, 'defined', $methodObject, 'getDefined', [], $methodType], [true, 'defined', $methodObject, 'GETDEFINED', [], $methodType], [true, 'static', $methodObject, 'static', [], $methodType], [true, 'static', $methodObject, 'getStatic', [], $methodType], [true, '__call_undefined', $magicMethodObject, 'undefined', [], $methodType], [true, '__call_UNDEFINED', $magicMethodObject, 'UNDEFINED', [], $methodType], ]); // add the same tests for the any type foreach ($tests as $test) { if ($anyType !== $test[5]) { $test[5] = $anyType; $tests[] = $test; } } $methodAndPropObject = new TemplateMethodAndPropObject(); // additional method tests $tests = array_merge($tests, [ [true, 'a', $methodAndPropObject, 'a', [], $anyType], [true, 'a', $methodAndPropObject, 'a', [], $methodType], [false, null, $methodAndPropObject, 'a', [], $arrayType], [true, 'b_prop', $methodAndPropObject, 'b', [], $anyType], [true, 'b', $methodAndPropObject, 'B', [], $anyType], [true, 'b', $methodAndPropObject, 'b', [], $methodType], [true, 'b', $methodAndPropObject, 'B', [], $methodType], [false, null, $methodAndPropObject, 'b', [], $arrayType], [false, null, $methodAndPropObject, 'c', [], $anyType], [false, null, $methodAndPropObject, 'c', [], $methodType], [false, null, $methodAndPropObject, 'c', [], $arrayType], ]); $arrayAccess = new TemplateArrayAccess(); $tests = array_merge($tests, [ [true, ['foo' => 'bar'], $arrayAccess, 'vars', [], $anyType], ]); // tests when input is not an array or object $tests = array_merge($tests, [ [false, null, 42, 'a', [], $anyType, 'Impossible to access an attribute ("a") on a integer variable ("42") in "index.twig".'], [false, null, 'string', 'a', [], $anyType, 'Impossible to access an attribute ("a") on a string variable ("string") in "index.twig".'], [false, null, [], 'a', [], $anyType, 'Key "a" does not exist as the array is empty in "index.twig".'], ]); return $tests; } public function testGetIsMethods() { $twig = new Environment($this->createMock(LoaderInterface::class)); $getIsObject = new TemplateGetIsMethods(); $template = new TemplateForTest($twig, 'index.twig'); // 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 TemplateForTest extends Template { private $name; public function __construct(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 []; } protected function doGetParent(array $context) { return false; } protected function doDisplay(array $context, array $blocks = []) { } public function block_name($context, array $blocks = []) { } } class TemplateArrayAccessObject implements \ArrayAccess { protected $protected = 'protected'; public $attributes = [ '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 TemplateMagicPropertyObject { public $defined = 'defined'; public $attributes = [ '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 TemplateMagicPropertyObjectWithException { public function __isset($key) { throw new \Exception('Hey! Don\'t try to isset me!'); } } class 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 TemplatePropertyObjectAndIterator extends TemplatePropertyObject implements \IteratorAggregate { public function getIterator() { return new \ArrayIterator(['foo', 'bar']); } } class TemplatePropertyObjectAndArrayAccess extends TemplatePropertyObject implements \ArrayAccess { private $data = [ 'defined' => 'defined', 'zero' => 0, 'null' => null, 'bar' => true, 'foo' => true, 'baz' => 'baz', 'baf' => 'baf', ]; 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 TemplatePropertyObjectDefinedWithUndefinedValue { public $foo; public function __construct() { $this->foo = @$notExist; } } class 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 TemplateGetIsMethods { public function get() { } public function is() { } } class 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 TemplateArrayAccess implements \ArrayAccess { public $vars = [ 'foo' => 'bar', ]; private $children = []; public function offsetExists($offset) { return \array_key_exists($offset, $this->children); } public function offsetGet($offset) { return $this->children[$offset]; } public function offsetSet($offset, $value) { $this->children[$offset] = $value; } public function offsetUnset($offset) { unset($this->children[$offset]); } } class TemplateMagicMethodObject { public function __call($method, $arguments) { return '__call_'.$method; } } class TemplateMagicMethodExceptionObject { public function __call($method, $arguments) { throw new \BadMethodCallException(sprintf('Unknown method "%s".', $method)); } } ���������������������������php-twig-2.12.5/tests/TemplateWrapperTest.php�������������������������������������������������������0000664�0000000�0000000�00000004370�13624573447�0021212�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Environment; use Twig\Loader\ArrayLoader; class TemplateWrapperTest extends TestCase { public function testHasGetBlocks() { $twig = new Environment(new ArrayLoader([ '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 = $twig->load('index'); $this->assertTrue($wrapper->hasBlock('foo')); $this->assertFalse($wrapper->hasBlock('bar')); $this->assertEquals(['foo'], $wrapper->getBlockNames()); $wrapper = $twig->load('index_with_use'); $this->assertTrue($wrapper->hasBlock('foo')); $this->assertTrue($wrapper->hasBlock('imported')); $this->assertEquals(['imported', 'foo'], $wrapper->getBlockNames()); $wrapper = $twig->load('index_with_extends'); $this->assertTrue($wrapper->hasBlock('foo')); $this->assertTrue($wrapper->hasBlock('extended')); $this->assertEquals(['foo', 'extended'], $wrapper->getBlockNames()); } public function testRenderBlock() { $twig = new Environment(new ArrayLoader([ 'index' => '{% block foo %}{{ foo }}{{ bar }}{% endblock %}', ])); $twig->addGlobal('bar', 'BAR'); $wrapper = $twig->load('index'); $this->assertEquals('FOOBAR', $wrapper->renderBlock('foo', ['foo' => 'FOO'])); } public function testDisplayBlock() { $twig = new Environment(new ArrayLoader([ 'index' => '{% block foo %}{{ foo }}{{ bar }}{% endblock %}', ])); $twig->addGlobal('bar', 'BAR'); $wrapper = $twig->load('index'); ob_start(); $wrapper->displayBlock('foo', ['foo' => 'FOO']); $this->assertEquals('FOOBAR', ob_get_clean()); } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/TokenStreamTest.php�����������������������������������������������������������0000664�0000000�0000000�00000003664�13624573447�0020337�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Error\SyntaxError; use Twig\Token; use Twig\TokenStream; class TokenStreamTest extends TestCase { protected static $tokens; protected function setUp() { self::$tokens = [ new Token(Token::TEXT_TYPE, 1, 1), new Token(Token::TEXT_TYPE, 2, 1), new Token(Token::TEXT_TYPE, 3, 1), new Token(Token::TEXT_TYPE, 4, 1), new Token(Token::TEXT_TYPE, 5, 1), new Token(Token::TEXT_TYPE, 6, 1), new Token(Token::TEXT_TYPE, 7, 1), new Token(Token::EOF_TYPE, 0, 1), ]; } public function testNext() { $stream = new TokenStream(self::$tokens); $repr = []; 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'); } public function testEndOfTemplateNext() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unexpected end of template'); $stream = new TokenStream([ new Token(Token::BLOCK_START_TYPE, 1, 1), ]); while (!$stream->isEOF()) { $stream->next(); } } public function testEndOfTemplateLook() { $this->expectException(SyntaxError::class); $this->expectExceptionMessage('Unexpected end of template'); $stream = new TokenStream([ new Token(Token::BLOCK_START_TYPE, 1, 1), ]); while (!$stream->isEOF()) { $stream->look(); $stream->next(); } } } ����������������������������������������������������������������������������php-twig-2.12.5/tests/Util/�������������������������������������������������������������������������0000775�0000000�0000000�00000000000�13624573447�0015436�5����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������php-twig-2.12.5/tests/Util/DeprecationCollectorTest.php���������������������������������������������0000664�0000000�0000000�00000002314�13624573447�0023113�0����������������������������������������������������������������������������������������������������ustar�00root����������������������������root����������������������������0000000�0000000������������������������������������������������������������������������������������������������������������������������������������������������������������������������<?php namespace Twig\Tests\Util; /* * 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. */ use PHPUnit\Framework\TestCase; use Twig\Environment; use Twig\Loader\LoaderInterface; use Twig\TwigFunction; use Twig\Util\DeprecationCollector; class DeprecationCollectorTest extends TestCase { /** * @requires PHP 5.3 */ public function testCollect() { $twig = new Environment($this->createMock(LoaderInterface::class)); $twig->addFunction(new TwigFunction('deprec', [$this, 'deprec'], ['deprecated' => true])); $collector = new DeprecationCollector($twig); $deprecations = $collector->collect(new Twig_Tests_Util_Iterator()); $this->assertEquals(['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([ 'ok.twig' => '{{ foo }}', 'deprec.twig' => '{{ deprec("foo") }}', ]); } } ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������