Spade
Mini Shell
| Directory:~$ /home/lmsyaran/public_html/joomla4/ |
| [Home] [System Details] [Kill Me] |
twig/.php_cs.dist000064400000001437151161070030007734 0ustar00<?php
return PhpCsFixer\Config::create()
->setRules([
'@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__))
;
twig/composer.json000064400000002323151161070030010232 0ustar00{
"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": ">=5.5.0",
"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": "1.42-dev"
}
}
}
twig/lib/Twig/Autoloader.php000064400000002710151161070030012000
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Autoloader class is deprecated since version
1.21 and will be removed in 2.0. Use Composer instead.',
E_USER_DEPRECATED);
/**
* Autoloads Twig classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.21 and will be removed in 2.0. Use Composer instead.
2.0.
*/
class Twig_Autoloader
{
/**
* Registers Twig_Autoloader as an SPL autoloader.
*
* @param bool $prepend whether to prepend the autoloader or not
*/
public static function register($prepend = false)
{
@trigger_error('Using Twig_Autoloader is deprecated since
version 1.21. Use Composer instead.', E_USER_DEPRECATED);
spl_autoload_register([__CLASS__, 'autoload'], true,
$prepend);
}
/**
* Handles autoloading of classes.
*
* @param string $class a class name
*/
public static function autoload($class)
{
if (0 !== strpos($class, 'Twig')) {
return;
}
if (is_file($file =
__DIR__.'/../'.str_replace(['_', "\0"],
['/', ''], $class).'.php')) {
require $file;
} elseif (is_file($file =
__DIR__.'/../../src/'.str_replace(['Twig\\',
'\\', "\0"], ['', '/',
''], $class).'.php')) {
require $file;
}
}
}
twig/lib/Twig/BaseNodeVisitor.php000064400000000300151161070030012732
0ustar00<?php
use Twig\NodeVisitor\AbstractNodeVisitor;
class_exists('Twig\NodeVisitor\AbstractNodeVisitor');
if (\false) {
class Twig_BaseNodeVisitor extends AbstractNodeVisitor
{
}
}
twig/lib/Twig/Cache/Filesystem.php000064400000000251151161070030013026
0ustar00<?php
use Twig\Cache\FilesystemCache;
class_exists('Twig\Cache\FilesystemCache');
if (\false) {
class Twig_Cache_Filesystem extends FilesystemCache
{
}
}
twig/lib/Twig/Cache/Null.php000064400000000221151161070030011611
0ustar00<?php
use Twig\Cache\NullCache;
class_exists('Twig\Cache\NullCache');
if (\false) {
class Twig_Cache_Null extends NullCache
{
}
}
twig/lib/Twig/CacheInterface.php000064400000000244151161070030012525
0ustar00<?php
use Twig\Cache\CacheInterface;
class_exists('Twig\Cache\CacheInterface');
if (\false) {
class Twig_CacheInterface extends CacheInterface
{
}
}
twig/lib/Twig/Compiler.php000064400000000200151161070030011443
0ustar00<?php
use Twig\Compiler;
class_exists('Twig\Compiler');
if (\false) {
class Twig_Compiler extends Compiler
{
}
}
twig/lib/Twig/CompilerInterface.php000064400000001230151161070030013270
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Interface implemented by compiler classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 3.0)
*/
interface Twig_CompilerInterface
{
/**
* Compiles a node.
*
* @return $this
*/
public function compile(Twig_NodeInterface $node);
/**
* Gets the current PHP code after compilation.
*
* @return string The PHP code
*/
public function getSource();
}
twig/lib/Twig/ContainerRuntimeLoader.php000064400000000324151161070030014315
0ustar00<?php
use Twig\RuntimeLoader\ContainerRuntimeLoader;
class_exists('Twig\RuntimeLoader\ContainerRuntimeLoader');
if (\false) {
class Twig_ContainerRuntimeLoader extends ContainerRuntimeLoader
{
}
}
twig/lib/Twig/Environment.php000064400000000214151161070030012202
0ustar00<?php
use Twig\Environment;
class_exists('Twig\Environment');
if (\false) {
class Twig_Environment extends Environment
{
}
}
twig/lib/Twig/Error/Loader.php000064400000000231151161070030012174
0ustar00<?php
use Twig\Error\LoaderError;
class_exists('Twig\Error\LoaderError');
if (\false) {
class Twig_Error_Loader extends LoaderError
{
}
}
twig/lib/Twig/Error/Runtime.php000064400000000235151161070030012415
0ustar00<?php
use Twig\Error\RuntimeError;
class_exists('Twig\Error\RuntimeError');
if (\false) {
class Twig_Error_Runtime extends RuntimeError
{
}
}
twig/lib/Twig/Error/Syntax.php000064400000000231151161070030012254
0ustar00<?php
use Twig\Error\SyntaxError;
class_exists('Twig\Error\SyntaxError');
if (\false) {
class Twig_Error_Syntax extends SyntaxError
{
}
}
twig/lib/Twig/Error.php000064400000000200151161070030010762
0ustar00<?php
use Twig\Error\Error;
class_exists('Twig\Error\Error');
if (\false) {
class Twig_Error extends Error
{
}
}
twig/lib/Twig/ExistsLoaderInterface.php000064400000000302151161070030014123
0ustar00<?php
use Twig\Loader\ExistsLoaderInterface;
class_exists('Twig\Loader\ExistsLoaderInterface');
if (\false) {
class Twig_ExistsLoaderInterface extends ExistsLoaderInterface
{
}
}
twig/lib/Twig/ExpressionParser.php000064400000000240151161070030013211
0ustar00<?php
use Twig\ExpressionParser;
class_exists('Twig\ExpressionParser');
if (\false) {
class Twig_ExpressionParser extends ExpressionParser
{
}
}
twig/lib/Twig/Extension/Core.php000064400000000251151161070030012543
0ustar00<?php
use Twig\Extension\CoreExtension;
class_exists('Twig\Extension\CoreExtension');
if (\false) {
class Twig_Extension_Core extends CoreExtension
{
}
}
twig/lib/Twig/Extension/Debug.php000064400000000255151161070030012705
0ustar00<?php
use Twig\Extension\DebugExtension;
class_exists('Twig\Extension\DebugExtension');
if (\false) {
class Twig_Extension_Debug extends DebugExtension
{
}
}
twig/lib/Twig/Extension/Escaper.php000064400000000265151161070030013242
0ustar00<?php
use Twig\Extension\EscaperExtension;
class_exists('Twig\Extension\EscaperExtension');
if (\false) {
class Twig_Extension_Escaper extends EscaperExtension
{
}
}
twig/lib/Twig/Extension/GlobalsInterface.php000064400000000276151161070030015066
0ustar00<?php
use Twig\Extension\GlobalsInterface;
class_exists('Twig\Extension\GlobalsInterface');
if (\false) {
class Twig_Extension_GlobalsInterface extends GlobalsInterface
{
}
}
twig/lib/Twig/Extension/InitRuntimeInterface.php000064400000000316151161070030015745
0ustar00<?php
use Twig\Extension\InitRuntimeInterface;
class_exists('Twig\Extension\InitRuntimeInterface');
if (\false) {
class Twig_Extension_InitRuntimeInterface extends InitRuntimeInterface
{
}
}
twig/lib/Twig/Extension/Optimizer.php000064400000000275151161070030013643
0ustar00<?php
use Twig\Extension\OptimizerExtension;
class_exists('Twig\Extension\OptimizerExtension');
if (\false) {
class Twig_Extension_Optimizer extends OptimizerExtension
{
}
}
twig/lib/Twig/Extension/Profiler.php000064400000000271151161070030013437
0ustar00<?php
use Twig\Extension\ProfilerExtension;
class_exists('Twig\Extension\ProfilerExtension');
if (\false) {
class Twig_Extension_Profiler extends ProfilerExtension
{
}
}
twig/lib/Twig/Extension/Sandbox.php000064400000000265151161070030013256
0ustar00<?php
use Twig\Extension\SandboxExtension;
class_exists('Twig\Extension\SandboxExtension');
if (\false) {
class Twig_Extension_Sandbox extends SandboxExtension
{
}
}
twig/lib/Twig/Extension/Staging.php000064400000000265151161070030013254
0ustar00<?php
use Twig\Extension\StagingExtension;
class_exists('Twig\Extension\StagingExtension');
if (\false) {
class Twig_Extension_Staging extends StagingExtension
{
}
}
twig/lib/Twig/Extension/StringLoader.php000064400000000311151161070030014245
0ustar00<?php
use Twig\Extension\StringLoaderExtension;
class_exists('Twig\Extension\StringLoaderExtension');
if (\false) {
class Twig_Extension_StringLoader extends StringLoaderExtension
{
}
}
twig/lib/Twig/Extension.php000064400000000260151161070030011653
0ustar00<?php
use Twig\Extension\AbstractExtension;
class_exists('Twig\Extension\AbstractExtension');
if (\false) {
class Twig_Extension extends AbstractExtension
{
}
}
twig/lib/Twig/ExtensionInterface.php000064400000000274151161070030013501
0ustar00<?php
use Twig\Extension\ExtensionInterface;
class_exists('Twig\Extension\ExtensionInterface');
if (\false) {
class Twig_ExtensionInterface extends ExtensionInterface
{
}
}
twig/lib/Twig/FactoryRuntimeLoader.php000064400000000314151161070030014001
0ustar00<?php
use Twig\RuntimeLoader\FactoryRuntimeLoader;
class_exists('Twig\RuntimeLoader\FactoryRuntimeLoader');
if (\false) {
class Twig_FactoryRuntimeLoader extends FactoryRuntimeLoader
{
}
}
twig/lib/Twig/FileExtensionEscapingStrategy.php000064400000000324151161070030015651
0ustar00<?php
use Twig\FileExtensionEscapingStrategy;
class_exists('Twig\FileExtensionEscapingStrategy');
if (\false) {
class Twig_FileExtensionEscapingStrategy extends
FileExtensionEscapingStrategy
{
}
}
twig/lib/Twig/Filter/Function.php000064400000001605151161070030012715
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Filter_Function class is deprecated since
version 1.12 and will be removed in 2.0. Use \Twig\TwigFilter
instead.', E_USER_DEPRECATED);
/**
* Represents a function template filter.
*
* Use \Twig\TwigFilter instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Filter_Function extends Twig_Filter
{
protected $function;
public function __construct($function, array $options = [])
{
$options['callable'] = $function;
parent::__construct($options);
$this->function = $function;
}
public function compile()
{
return $this->function;
}
}
twig/lib/Twig/Filter/Method.php000064400000002130151161070030012342
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Extension\ExtensionInterface;
@trigger_error('The Twig_Filter_Method class is deprecated since
version 1.12 and will be removed in 2.0. Use \Twig\TwigFilter
instead.', E_USER_DEPRECATED);
/**
* Represents a method template filter.
*
* Use \Twig\TwigFilter instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Filter_Method extends Twig_Filter
{
protected $extension;
protected $method;
public function __construct(ExtensionInterface $extension, $method,
array $options = [])
{
$options['callable'] = [$extension, $method];
parent::__construct($options);
$this->extension = $extension;
$this->method = $method;
}
public function compile()
{
return
sprintf('$this->env->getExtension(\'%s\')->%s',
\get_class($this->extension), $this->method);
}
}
twig/lib/Twig/Filter/Node.php000064400000001560151161070030012015
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Filter_Node class is deprecated since version
1.12 and will be removed in 2.0. Use \Twig\TwigFilter instead.',
E_USER_DEPRECATED);
/**
* Represents a template filter as a node.
*
* Use \Twig\TwigFilter instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Filter_Node extends Twig_Filter
{
protected $class;
public function __construct($class, array $options = [])
{
parent::__construct($options);
$this->class = $class;
}
public function getClass()
{
return $this->class;
}
public function compile()
{
}
}
twig/lib/Twig/Filter.php000064400000003717151161070030011136
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Node\Node;
@trigger_error('The Twig_Filter class is deprecated since version 1.12
and will be removed in 2.0. Use \Twig\TwigFilter instead.',
E_USER_DEPRECATED);
/**
* Represents a template filter.
*
* Use \Twig\TwigFilter instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
abstract class Twig_Filter implements Twig_FilterInterface,
Twig_FilterCallableInterface
{
protected $options;
protected $arguments = [];
public function __construct(array $options = [])
{
$this->options = array_merge([
'needs_environment' => false,
'needs_context' => false,
'pre_escape' => null,
'preserves_safety' => null,
'callable' => null,
], $options);
}
public function setArguments($arguments)
{
$this->arguments = $arguments;
}
public function getArguments()
{
return $this->arguments;
}
public function needsEnvironment()
{
return $this->options['needs_environment'];
}
public function needsContext()
{
return $this->options['needs_context'];
}
public function getSafe(Node $filterArgs)
{
if (isset($this->options['is_safe'])) {
return $this->options['is_safe'];
}
if (isset($this->options['is_safe_callback'])) {
return
\call_user_func($this->options['is_safe_callback'],
$filterArgs);
}
}
public function getPreservesSafety()
{
return $this->options['preserves_safety'];
}
public function getPreEscape()
{
return $this->options['pre_escape'];
}
public function getCallable()
{
return $this->options['callable'];
}
}
twig/lib/Twig/FilterCallableInterface.php000064400000000726151161070030014374
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Represents a callable template filter.
*
* Use \Twig\TwigFilter instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
interface Twig_FilterCallableInterface
{
public function getCallable();
}
twig/lib/Twig/FilterInterface.php000064400000001533151161070030012751
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Node\Node;
/**
* Represents a template filter.
*
* Use \Twig\TwigFilter instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
interface Twig_FilterInterface
{
/**
* Compiles a filter.
*
* @return string The PHP code for the filter
*/
public function compile();
public function needsEnvironment();
public function needsContext();
public function getSafe(Node $filterArgs);
public function getPreservesSafety();
public function getPreEscape();
public function setArguments($arguments);
public function getArguments();
}
twig/lib/Twig/Function/Function.php000064400000001650151161070030013255
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Arnaud Le Blanc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Function_Function class is deprecated since
version 1.12 and will be removed in 2.0. Use \Twig\TwigFunction
instead.', E_USER_DEPRECATED);
/**
* Represents a function template function.
*
* Use \Twig\TwigFunction instead.
*
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Function_Function extends Twig_Function
{
protected $function;
public function __construct($function, array $options = [])
{
$options['callable'] = $function;
parent::__construct($options);
$this->function = $function;
}
public function compile()
{
return $this->function;
}
}
twig/lib/Twig/Function/Method.php000064400000002173151161070030012711
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Arnaud Le Blanc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Extension\ExtensionInterface;
@trigger_error('The Twig_Function_Method class is deprecated since
version 1.12 and will be removed in 2.0. Use \Twig\TwigFunction
instead.', E_USER_DEPRECATED);
/**
* Represents a method template function.
*
* Use \Twig\TwigFunction instead.
*
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Function_Method extends Twig_Function
{
protected $extension;
protected $method;
public function __construct(ExtensionInterface $extension, $method,
array $options = [])
{
$options['callable'] = [$extension, $method];
parent::__construct($options);
$this->extension = $extension;
$this->method = $method;
}
public function compile()
{
return
sprintf('$this->env->getExtension(\'%s\')->%s',
\get_class($this->extension), $this->method);
}
}
twig/lib/Twig/Function/Node.php000064400000001574151161070030012362
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Function_Node class is deprecated since
version 1.12 and will be removed in 2.0. Use \Twig\TwigFunction
instead.', E_USER_DEPRECATED);
/**
* Represents a template function as a node.
*
* Use \Twig\TwigFunction instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Function_Node extends Twig_Function
{
protected $class;
public function __construct($class, array $options = [])
{
parent::__construct($options);
$this->class = $class;
}
public function getClass()
{
return $this->class;
}
public function compile()
{
}
}
twig/lib/Twig/Function.php000064400000003345151161070030011473
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Node\Node;
@trigger_error('The Twig_Function class is deprecated since version
1.12 and will be removed in 2.0. Use \Twig\TwigFunction instead.',
E_USER_DEPRECATED);
/**
* Represents a template function.
*
* Use \Twig\TwigFunction instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
abstract class Twig_Function implements Twig_FunctionInterface,
Twig_FunctionCallableInterface
{
protected $options;
protected $arguments = [];
public function __construct(array $options = [])
{
$this->options = array_merge([
'needs_environment' => false,
'needs_context' => false,
'callable' => null,
], $options);
}
public function setArguments($arguments)
{
$this->arguments = $arguments;
}
public function getArguments()
{
return $this->arguments;
}
public function needsEnvironment()
{
return $this->options['needs_environment'];
}
public function needsContext()
{
return $this->options['needs_context'];
}
public function getSafe(Node $functionArgs)
{
if (isset($this->options['is_safe'])) {
return $this->options['is_safe'];
}
if (isset($this->options['is_safe_callback'])) {
return
\call_user_func($this->options['is_safe_callback'],
$functionArgs);
}
return [];
}
public function getCallable()
{
return $this->options['callable'];
}
}
twig/lib/Twig/FunctionCallableInterface.php000064400000000734151161070030014733
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Represents a callable template function.
*
* Use \Twig\TwigFunction instead.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
interface Twig_FunctionCallableInterface
{
public function getCallable();
}
twig/lib/Twig/FunctionInterface.php000064400000001454151161070030013313
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Arnaud Le Blanc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Node\Node;
/**
* Represents a template function.
*
* Use \Twig\TwigFunction instead.
*
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
interface Twig_FunctionInterface
{
/**
* Compiles a function.
*
* @return string The PHP code for the function
*/
public function compile();
public function needsEnvironment();
public function needsContext();
public function getSafe(Node $filterArgs);
public function setArguments($arguments);
public function getArguments();
}
twig/lib/Twig/Lexer.php000064400000000164151161070030010761
0ustar00<?php
use Twig\Lexer;
class_exists('Twig\Lexer');
if (\false) {
class Twig_Lexer extends Lexer
{
}
}
twig/lib/Twig/LexerInterface.php000064400000001432151161070030012601
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Error\SyntaxError;
use Twig\Source;
use Twig\TokenStream;
/**
* Interface implemented by lexer classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 3.0)
*/
interface Twig_LexerInterface
{
/**
* Tokenizes a source code.
*
* @param string|Source $code The source code
* @param string $name A unique identifier for the source code
*
* @return TokenStream
*
* @throws SyntaxError When the code is syntactically wrong
*/
public function tokenize($code, $name = null);
}
twig/lib/Twig/Loader/Array.php000064400000000233151161070030012163
0ustar00<?php
use Twig\Loader\ArrayLoader;
class_exists('Twig\Loader\ArrayLoader');
if (\false) {
class Twig_Loader_Array extends ArrayLoader
{
}
}
twig/lib/Twig/Loader/Chain.php000064400000000233151161070030012127
0ustar00<?php
use Twig\Loader\ChainLoader;
class_exists('Twig\Loader\ChainLoader');
if (\false) {
class Twig_Loader_Chain extends ChainLoader
{
}
}
twig/lib/Twig/Loader/Filesystem.php000064400000000257151161070030013237
0ustar00<?php
use Twig\Loader\FilesystemLoader;
class_exists('Twig\Loader\FilesystemLoader');
if (\false) {
class Twig_Loader_Filesystem extends FilesystemLoader
{
}
}
twig/lib/Twig/Loader/String.php000064400000003367151161070030012366
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Loader\ExistsLoaderInterface;
use Twig\Loader\LoaderInterface;
use Twig\Loader\SourceContextLoaderInterface;
use Twig\Source;
@trigger_error('The Twig_Loader_String class is deprecated since
version 1.18.1 and will be removed in 2.0. Use
"Twig\Loader\ArrayLoader" instead or
"Twig\Environment::createTemplate()".', E_USER_DEPRECATED);
/**
* Loads a template from a string.
*
* This loader should NEVER be used. It only exists for Twig internal
purposes.
*
* When using this 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.
*
* @deprecated since 1.18.1 (to be removed in 2.0)
*
* @internal
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Twig_Loader_String implements LoaderInterface, ExistsLoaderInterface,
SourceContextLoaderInterface
{
public function getSource($name)
{
@trigger_error(sprintf('Calling "getSource" on
"%s" is deprecated since 1.27. Use getSourceContext()
instead.', \get_class($this)), E_USER_DEPRECATED);
return $name;
}
public function getSourceContext($name)
{
return new Source($name, $name);
}
public function exists($name)
{
return true;
}
public function getCacheKey($name)
{
return $name;
}
public function isFresh($name, $time)
{
return true;
}
}
twig/lib/Twig/LoaderInterface.php000064400000000252151161070030012727
0ustar00<?php
use Twig\Loader\LoaderInterface;
class_exists('Twig\Loader\LoaderInterface');
if (\false) {
class Twig_LoaderInterface extends LoaderInterface
{
}
}
twig/lib/Twig/Markup.php000064400000000170151161070030011136
0ustar00<?php
use Twig\Markup;
class_exists('Twig\Markup');
if (\false) {
class Twig_Markup extends Markup
{
}
}
twig/lib/Twig/Node/AutoEscape.php000064400000000243151161070030012616
0ustar00<?php
use Twig\Node\AutoEscapeNode;
class_exists('Twig\Node\AutoEscapeNode');
if (\false) {
class Twig_Node_AutoEscape extends AutoEscapeNode
{
}
}
twig/lib/Twig/Node/Block.php000064400000000217151161070030011620
0ustar00<?php
use Twig\Node\BlockNode;
class_exists('Twig\Node\BlockNode');
if (\false) {
class Twig_Node_Block extends BlockNode
{
}
}
twig/lib/Twig/Node/BlockReference.php000064400000000263151161070030013440
0ustar00<?php
use Twig\Node\BlockReferenceNode;
class_exists('Twig\Node\BlockReferenceNode');
if (\false) {
class Twig_Node_BlockReference extends BlockReferenceNode
{
}
}
twig/lib/Twig/Node/Body.php000064400000000213151161070030011457
0ustar00<?php
use Twig\Node\BodyNode;
class_exists('Twig\Node\BodyNode');
if (\false) {
class Twig_Node_Body extends BodyNode
{
}
}
twig/lib/Twig/Node/CheckSecurity.php000064400000000257151161070030013337
0ustar00<?php
use Twig\Node\CheckSecurityNode;
class_exists('Twig\Node\CheckSecurityNode');
if (\false) {
class Twig_Node_CheckSecurity extends CheckSecurityNode
{
}
}
twig/lib/Twig/Node/Deprecated.php000064400000000243151161070030012625
0ustar00<?php
use Twig\Node\DeprecatedNode;
class_exists('Twig\Node\DeprecatedNode');
if (\false) {
class Twig_Node_Deprecated extends DeprecatedNode
{
}
}
twig/lib/Twig/Node/Do.php000064400000000203151161070030011123
0ustar00<?php
use Twig\Node\DoNode;
class_exists('Twig\Node\DoNode');
if (\false) {
class Twig_Node_Do extends DoNode
{
}
}
twig/lib/Twig/Node/Embed.php000064400000000217151161070030011602
0ustar00<?php
use Twig\Node\EmbedNode;
class_exists('Twig\Node\EmbedNode');
if (\false) {
class Twig_Node_Embed extends EmbedNode
{
}
}
twig/lib/Twig/Node/Expression/Array.php000064400000000302151161070030013776
0ustar00<?php
use Twig\Node\Expression\ArrayExpression;
class_exists('Twig\Node\Expression\ArrayExpression');
if (\false) {
class Twig_Node_Expression_Array extends ArrayExpression
{
}
}
twig/lib/Twig/Node/Expression/AssignName.php000064400000000326151161070030014753
0ustar00<?php
use Twig\Node\Expression\AssignNameExpression;
class_exists('Twig\Node\Expression\AssignNameExpression');
if (\false) {
class Twig_Node_Expression_AssignName extends AssignNameExpression
{
}
}
twig/lib/Twig/Node/Expression/Binary/Add.php000064400000000303151161070030014635
0ustar00<?php
use Twig\Node\Expression\Binary\AddBinary;
class_exists('Twig\Node\Expression\Binary\AddBinary');
if (\false) {
class Twig_Node_Expression_Binary_Add extends AddBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/And.php000064400000000303151161070030014647
0ustar00<?php
use Twig\Node\Expression\Binary\AndBinary;
class_exists('Twig\Node\Expression\Binary\AndBinary');
if (\false) {
class Twig_Node_Expression_Binary_And extends AndBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/BitwiseAnd.php000064400000000337151161070030016205
0ustar00<?php
use Twig\Node\Expression\Binary\BitwiseAndBinary;
class_exists('Twig\Node\Expression\Binary\BitwiseAndBinary');
if (\false) {
class Twig_Node_Expression_Binary_BitwiseAnd extends BitwiseAndBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/BitwiseOr.php000064400000000333151161070030016057
0ustar00<?php
use Twig\Node\Expression\Binary\BitwiseOrBinary;
class_exists('Twig\Node\Expression\Binary\BitwiseOrBinary');
if (\false) {
class Twig_Node_Expression_Binary_BitwiseOr extends BitwiseOrBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/BitwiseXor.php000064400000000337151161070030016253
0ustar00<?php
use Twig\Node\Expression\Binary\BitwiseXorBinary;
class_exists('Twig\Node\Expression\Binary\BitwiseXorBinary');
if (\false) {
class Twig_Node_Expression_Binary_BitwiseXor extends BitwiseXorBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Concat.php000064400000000317151161070030015361
0ustar00<?php
use Twig\Node\Expression\Binary\ConcatBinary;
class_exists('Twig\Node\Expression\Binary\ConcatBinary');
if (\false) {
class Twig_Node_Expression_Binary_Concat extends ConcatBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Div.php000064400000000303151161070030014667
0ustar00<?php
use Twig\Node\Expression\Binary\DivBinary;
class_exists('Twig\Node\Expression\Binary\DivBinary');
if (\false) {
class Twig_Node_Expression_Binary_Div extends DivBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/EndsWith.php000064400000000327151161070030015700
0ustar00<?php
use Twig\Node\Expression\Binary\EndsWithBinary;
class_exists('Twig\Node\Expression\Binary\EndsWithBinary');
if (\false) {
class Twig_Node_Expression_Binary_EndsWith extends EndsWithBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Equal.php000064400000000313151161070030015215
0ustar00<?php
use Twig\Node\Expression\Binary\EqualBinary;
class_exists('Twig\Node\Expression\Binary\EqualBinary');
if (\false) {
class Twig_Node_Expression_Binary_Equal extends EqualBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/FloorDiv.php000064400000000327151161070030015677
0ustar00<?php
use Twig\Node\Expression\Binary\FloorDivBinary;
class_exists('Twig\Node\Expression\Binary\FloorDivBinary');
if (\false) {
class Twig_Node_Expression_Binary_FloorDiv extends FloorDivBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Greater.php000064400000000323151161070030015540
0ustar00<?php
use Twig\Node\Expression\Binary\GreaterBinary;
class_exists('Twig\Node\Expression\Binary\GreaterBinary');
if (\false) {
class Twig_Node_Expression_Binary_Greater extends GreaterBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/GreaterEqual.php000064400000000347151161070030016536
0ustar00<?php
use Twig\Node\Expression\Binary\GreaterEqualBinary;
class_exists('Twig\Node\Expression\Binary\GreaterEqualBinary');
if (\false) {
class Twig_Node_Expression_Binary_GreaterEqual extends
GreaterEqualBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/In.php000064400000000277151161070030014525
0ustar00<?php
use Twig\Node\Expression\Binary\InBinary;
class_exists('Twig\Node\Expression\Binary\InBinary');
if (\false) {
class Twig_Node_Expression_Binary_In extends InBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Less.php000064400000000307151161070030015057
0ustar00<?php
use Twig\Node\Expression\Binary\LessBinary;
class_exists('Twig\Node\Expression\Binary\LessBinary');
if (\false) {
class Twig_Node_Expression_Binary_Less extends LessBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/LessEqual.php000064400000000333151161070030016046
0ustar00<?php
use Twig\Node\Expression\Binary\LessEqualBinary;
class_exists('Twig\Node\Expression\Binary\LessEqualBinary');
if (\false) {
class Twig_Node_Expression_Binary_LessEqual extends LessEqualBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Matches.php000064400000000323151161070030015533
0ustar00<?php
use Twig\Node\Expression\Binary\MatchesBinary;
class_exists('Twig\Node\Expression\Binary\MatchesBinary');
if (\false) {
class Twig_Node_Expression_Binary_Matches extends MatchesBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Mod.php000064400000000303151161070030014664
0ustar00<?php
use Twig\Node\Expression\Binary\ModBinary;
class_exists('Twig\Node\Expression\Binary\ModBinary');
if (\false) {
class Twig_Node_Expression_Binary_Mod extends ModBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Mul.php000064400000000303151161070030014702
0ustar00<?php
use Twig\Node\Expression\Binary\MulBinary;
class_exists('Twig\Node\Expression\Binary\MulBinary');
if (\false) {
class Twig_Node_Expression_Binary_Mul extends MulBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/NotEqual.php000064400000000327151161070030015703
0ustar00<?php
use Twig\Node\Expression\Binary\NotEqualBinary;
class_exists('Twig\Node\Expression\Binary\NotEqualBinary');
if (\false) {
class Twig_Node_Expression_Binary_NotEqual extends NotEqualBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/NotIn.php000064400000000313151161070030015175
0ustar00<?php
use Twig\Node\Expression\Binary\NotInBinary;
class_exists('Twig\Node\Expression\Binary\NotInBinary');
if (\false) {
class Twig_Node_Expression_Binary_NotIn extends NotInBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Or.php000064400000000277151161070030014537
0ustar00<?php
use Twig\Node\Expression\Binary\OrBinary;
class_exists('Twig\Node\Expression\Binary\OrBinary');
if (\false) {
class Twig_Node_Expression_Binary_Or extends OrBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Power.php000064400000000313151161070030015242
0ustar00<?php
use Twig\Node\Expression\Binary\PowerBinary;
class_exists('Twig\Node\Expression\Binary\PowerBinary');
if (\false) {
class Twig_Node_Expression_Binary_Power extends PowerBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Range.php000064400000000313151161070030015202
0ustar00<?php
use Twig\Node\Expression\Binary\RangeBinary;
class_exists('Twig\Node\Expression\Binary\RangeBinary');
if (\false) {
class Twig_Node_Expression_Binary_Range extends RangeBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/StartsWith.php000064400000000337151161070030016270
0ustar00<?php
use Twig\Node\Expression\Binary\StartsWithBinary;
class_exists('Twig\Node\Expression\Binary\StartsWithBinary');
if (\false) {
class Twig_Node_Expression_Binary_StartsWith extends StartsWithBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary/Sub.php000064400000000303151161070030014676
0ustar00<?php
use Twig\Node\Expression\Binary\SubBinary;
class_exists('Twig\Node\Expression\Binary\SubBinary');
if (\false) {
class Twig_Node_Expression_Binary_Sub extends SubBinary
{
}
}
twig/lib/Twig/Node/Expression/Binary.php000064400000000316151161070030014151
0ustar00<?php
use Twig\Node\Expression\Binary\AbstractBinary;
class_exists('Twig\Node\Expression\Binary\AbstractBinary');
if (\false) {
class Twig_Node_Expression_Binary extends AbstractBinary
{
}
}
twig/lib/Twig/Node/Expression/BlockReference.php000064400000000346151161070030015601
0ustar00<?php
use Twig\Node\Expression\BlockReferenceExpression;
class_exists('Twig\Node\Expression\BlockReferenceExpression');
if (\false) {
class Twig_Node_Expression_BlockReference extends
BlockReferenceExpression
{
}
}
twig/lib/Twig/Node/Expression/Call.php000064400000000276151161070030013605
0ustar00<?php
use Twig\Node\Expression\CallExpression;
class_exists('Twig\Node\Expression\CallExpression');
if (\false) {
class Twig_Node_Expression_Call extends CallExpression
{
}
}
twig/lib/Twig/Node/Expression/Conditional.php000064400000000332151161070030015166
0ustar00<?php
use Twig\Node\Expression\ConditionalExpression;
class_exists('Twig\Node\Expression\ConditionalExpression');
if (\false) {
class Twig_Node_Expression_Conditional extends ConditionalExpression
{
}
}
twig/lib/Twig/Node/Expression/Constant.php000064400000000316151161070030014516
0ustar00<?php
use Twig\Node\Expression\ConstantExpression;
class_exists('Twig\Node\Expression\ConstantExpression');
if (\false) {
class Twig_Node_Expression_Constant extends ConstantExpression
{
}
}
twig/lib/Twig/Node/Expression/ExtensionReference.php000064400000001663151161070030016526
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
@trigger_error('The Twig_Node_Expression_ExtensionReference class is
deprecated since version 1.23 and will be removed in 2.0.',
E_USER_DEPRECATED);
/**
* Represents an extension call node.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.23 and will be removed in 2.0.
*/
class Twig_Node_Expression_ExtensionReference extends AbstractExpression
{
public function __construct($name, $lineno, $tag = null)
{
parent::__construct([], ['name' => $name], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
$compiler->raw(sprintf("\$this->env->getExtension('%s')",
$this->getAttribute('name')));
}
}
twig/lib/Twig/Node/Expression/Filter/Default.php000064400000000323151161070030015534
0ustar00<?php
use Twig\Node\Expression\Filter\DefaultFilter;
class_exists('Twig\Node\Expression\Filter\DefaultFilter');
if (\false) {
class Twig_Node_Expression_Filter_Default extends DefaultFilter
{
}
}
twig/lib/Twig/Node/Expression/Filter.php000064400000000306151161070030014151
0ustar00<?php
use Twig\Node\Expression\FilterExpression;
class_exists('Twig\Node\Expression\FilterExpression');
if (\false) {
class Twig_Node_Expression_Filter extends FilterExpression
{
}
}
twig/lib/Twig/Node/Expression/Function.php000064400000000316151161070030014512
0ustar00<?php
use Twig\Node\Expression\FunctionExpression;
class_exists('Twig\Node\Expression\FunctionExpression');
if (\false) {
class Twig_Node_Expression_Function extends FunctionExpression
{
}
}
twig/lib/Twig/Node/Expression/GetAttr.php000064400000000312151161070030014273
0ustar00<?php
use Twig\Node\Expression\GetAttrExpression;
class_exists('Twig\Node\Expression\GetAttrExpression');
if (\false) {
class Twig_Node_Expression_GetAttr extends GetAttrExpression
{
}
}
twig/lib/Twig/Node/Expression/MethodCall.php000064400000000326151161070030014742
0ustar00<?php
use Twig\Node\Expression\MethodCallExpression;
class_exists('Twig\Node\Expression\MethodCallExpression');
if (\false) {
class Twig_Node_Expression_MethodCall extends MethodCallExpression
{
}
}
twig/lib/Twig/Node/Expression/Name.php000064400000000276151161070030013612
0ustar00<?php
use Twig\Node\Expression\NameExpression;
class_exists('Twig\Node\Expression\NameExpression');
if (\false) {
class Twig_Node_Expression_Name extends NameExpression
{
}
}
twig/lib/Twig/Node/Expression/NullCoalesce.php000064400000000336151161070030015300
0ustar00<?php
use Twig\Node\Expression\NullCoalesceExpression;
class_exists('Twig\Node\Expression\NullCoalesceExpression');
if (\false) {
class Twig_Node_Expression_NullCoalesce extends NullCoalesceExpression
{
}
}
twig/lib/Twig/Node/Expression/Parent.php000064400000000306151161070030014155
0ustar00<?php
use Twig\Node\Expression\ParentExpression;
class_exists('Twig\Node\Expression\ParentExpression');
if (\false) {
class Twig_Node_Expression_Parent extends ParentExpression
{
}
}
twig/lib/Twig/Node/Expression/TempName.php000064400000000316151161070030014433
0ustar00<?php
use Twig\Node\Expression\TempNameExpression;
class_exists('Twig\Node\Expression\TempNameExpression');
if (\false) {
class Twig_Node_Expression_TempName extends TempNameExpression
{
}
}
twig/lib/Twig/Node/Expression/Test/Constant.php000064400000000313151161070030015432
0ustar00<?php
use Twig\Node\Expression\Test\ConstantTest;
class_exists('Twig\Node\Expression\Test\ConstantTest');
if (\false) {
class Twig_Node_Expression_Test_Constant extends ConstantTest
{
}
}
twig/lib/Twig/Node/Expression/Test/Defined.php000064400000000307151161070030015202
0ustar00<?php
use Twig\Node\Expression\Test\DefinedTest;
class_exists('Twig\Node\Expression\Test\DefinedTest');
if (\false) {
class Twig_Node_Expression_Test_Defined extends DefinedTest
{
}
}
twig/lib/Twig/Node/Expression/Test/Divisibleby.php000064400000000327151161070030016113
0ustar00<?php
use Twig\Node\Expression\Test\DivisiblebyTest;
class_exists('Twig\Node\Expression\Test\DivisiblebyTest');
if (\false) {
class Twig_Node_Expression_Test_Divisibleby extends DivisiblebyTest
{
}
}
twig/lib/Twig/Node/Expression/Test/Even.php000064400000000273151161070030014543
0ustar00<?php
use Twig\Node\Expression\Test\EvenTest;
class_exists('Twig\Node\Expression\Test\EvenTest');
if (\false) {
class Twig_Node_Expression_Test_Even extends EvenTest
{
}
}
twig/lib/Twig/Node/Expression/Test/Null.php000064400000000273151161070030014560
0ustar00<?php
use Twig\Node\Expression\Test\NullTest;
class_exists('Twig\Node\Expression\Test\NullTest');
if (\false) {
class Twig_Node_Expression_Test_Null extends NullTest
{
}
}
twig/lib/Twig/Node/Expression/Test/Odd.php000064400000000267151161070030014357
0ustar00<?php
use Twig\Node\Expression\Test\OddTest;
class_exists('Twig\Node\Expression\Test\OddTest');
if (\false) {
class Twig_Node_Expression_Test_Odd extends OddTest
{
}
}
twig/lib/Twig/Node/Expression/Test/Sameas.php000064400000000303151161070030015051
0ustar00<?php
use Twig\Node\Expression\Test\SameasTest;
class_exists('Twig\Node\Expression\Test\SameasTest');
if (\false) {
class Twig_Node_Expression_Test_Sameas extends SameasTest
{
}
}
twig/lib/Twig/Node/Expression/Test.php000064400000000276151161070030013651
0ustar00<?php
use Twig\Node\Expression\TestExpression;
class_exists('Twig\Node\Expression\TestExpression');
if (\false) {
class Twig_Node_Expression_Test extends TestExpression
{
}
}
twig/lib/Twig/Node/Expression/Unary/Neg.php000064400000000275151161070030014540
0ustar00<?php
use Twig\Node\Expression\Unary\NegUnary;
class_exists('Twig\Node\Expression\Unary\NegUnary');
if (\false) {
class Twig_Node_Expression_Unary_Neg extends NegUnary
{
}
}
twig/lib/Twig/Node/Expression/Unary/Not.php000064400000000275151161070030014567
0ustar00<?php
use Twig\Node\Expression\Unary\NotUnary;
class_exists('Twig\Node\Expression\Unary\NotUnary');
if (\false) {
class Twig_Node_Expression_Unary_Not extends NotUnary
{
}
}
twig/lib/Twig/Node/Expression/Unary/Pos.php000064400000000275151161070030014570
0ustar00<?php
use Twig\Node\Expression\Unary\PosUnary;
class_exists('Twig\Node\Expression\Unary\PosUnary');
if (\false) {
class Twig_Node_Expression_Unary_Pos extends PosUnary
{
}
}
twig/lib/Twig/Node/Expression/Unary.php000064400000000310151161070030014015
0ustar00<?php
use Twig\Node\Expression\Unary\AbstractUnary;
class_exists('Twig\Node\Expression\Unary\AbstractUnary');
if (\false) {
class Twig_Node_Expression_Unary extends AbstractUnary
{
}
}
twig/lib/Twig/Node/Expression.php000064400000000305151161070030012723
0ustar00<?php
use Twig\Node\Expression\AbstractExpression;
class_exists('Twig\Node\Expression\AbstractExpression');
if (\false) {
class Twig_Node_Expression extends AbstractExpression
{
}
}
twig/lib/Twig/Node/Flush.php000064400000000217151161070030011647
0ustar00<?php
use Twig\Node\FlushNode;
class_exists('Twig\Node\FlushNode');
if (\false) {
class Twig_Node_Flush extends FlushNode
{
}
}
twig/lib/Twig/Node/For.php000064400000000207151161070030011313
0ustar00<?php
use Twig\Node\ForNode;
class_exists('Twig\Node\ForNode');
if (\false) {
class Twig_Node_For extends ForNode
{
}
}
twig/lib/Twig/Node/ForLoop.php000064400000000227151161070030012147
0ustar00<?php
use Twig\Node\ForLoopNode;
class_exists('Twig\Node\ForLoopNode');
if (\false) {
class Twig_Node_ForLoop extends ForLoopNode
{
}
}
twig/lib/Twig/Node/If.php000064400000000203151161070030011117
0ustar00<?php
use Twig\Node\IfNode;
class_exists('Twig\Node\IfNode');
if (\false) {
class Twig_Node_If extends IfNode
{
}
}
twig/lib/Twig/Node/Import.php000064400000000223151161070030012035
0ustar00<?php
use Twig\Node\ImportNode;
class_exists('Twig\Node\ImportNode');
if (\false) {
class Twig_Node_Import extends ImportNode
{
}
}
twig/lib/Twig/Node/Include.php000064400000000227151161070030012152
0ustar00<?php
use Twig\Node\IncludeNode;
class_exists('Twig\Node\IncludeNode');
if (\false) {
class Twig_Node_Include extends IncludeNode
{
}
}
twig/lib/Twig/Node/Macro.php000064400000000217151161070030011627
0ustar00<?php
use Twig\Node\MacroNode;
class_exists('Twig\Node\MacroNode');
if (\false) {
class Twig_Node_Macro extends MacroNode
{
}
}
twig/lib/Twig/Node/Module.php000064400000000223151161070030012010
0ustar00<?php
use Twig\Node\ModuleNode;
class_exists('Twig\Node\ModuleNode');
if (\false) {
class Twig_Node_Module extends ModuleNode
{
}
}
twig/lib/Twig/Node/Print.php000064400000000217151161070030011662
0ustar00<?php
use Twig\Node\PrintNode;
class_exists('Twig\Node\PrintNode');
if (\false) {
class Twig_Node_Print extends PrintNode
{
}
}
twig/lib/Twig/Node/Sandbox.php000064400000000227151161070030012165
0ustar00<?php
use Twig\Node\SandboxNode;
class_exists('Twig\Node\SandboxNode');
if (\false) {
class Twig_Node_Sandbox extends SandboxNode
{
}
}
twig/lib/Twig/Node/SandboxedPrint.php000064400000000263151161070030013513
0ustar00<?php
use Twig\Node\SandboxedPrintNode;
class_exists('Twig\Node\SandboxedPrintNode');
if (\false) {
class Twig_Node_SandboxedPrint extends SandboxedPrintNode
{
}
}
twig/lib/Twig/Node/Set.php000064400000000207151161070030011320
0ustar00<?php
use Twig\Node\SetNode;
class_exists('Twig\Node\SetNode');
if (\false) {
class Twig_Node_Set extends SetNode
{
}
}
twig/lib/Twig/Node/SetTemp.php000064400000000227151161070030012150
0ustar00<?php
use Twig\Node\SetTempNode;
class_exists('Twig\Node\SetTempNode');
if (\false) {
class Twig_Node_SetTemp extends SetTempNode
{
}
}
twig/lib/Twig/Node/Spaceless.php000064400000000237151161070030012512
0ustar00<?php
use Twig\Node\SpacelessNode;
class_exists('Twig\Node\SpacelessNode');
if (\false) {
class Twig_Node_Spaceless extends SpacelessNode
{
}
}
twig/lib/Twig/Node/Text.php000064400000000213151161070030011506
0ustar00<?php
use Twig\Node\TextNode;
class_exists('Twig\Node\TextNode');
if (\false) {
class Twig_Node_Text extends TextNode
{
}
}
twig/lib/Twig/Node/With.php000064400000000213151161070030011475
0ustar00<?php
use Twig\Node\WithNode;
class_exists('Twig\Node\WithNode');
if (\false) {
class Twig_Node_With extends WithNode
{
}
}
twig/lib/Twig/Node.php000064400000000172151161070030010566 0ustar00<?php
use Twig\Node\Node;
class_exists('Twig\Node\Node');
if (\false) {
class Twig_Node extends Node
{
}
}
twig/lib/Twig/NodeCaptureInterface.php000064400000000272151161070030013734
0ustar00<?php
use Twig\Node\NodeCaptureInterface;
class_exists('Twig\Node\NodeCaptureInterface');
if (\false) {
class Twig_NodeCaptureInterface extends NodeCaptureInterface
{
}
}
twig/lib/Twig/NodeInterface.php000064400000001241151161070030012405
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Compiler;
/**
* Represents a node in the AST.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 3.0)
*/
interface Twig_NodeInterface extends \Countable, \IteratorAggregate
{
/**
* Compiles the node to PHP.
*/
public function compile(Compiler $compiler);
/**
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function getLine();
public function getNodeTag();
}
twig/lib/Twig/NodeOutputInterface.php000064400000000266151161070030013634
0ustar00<?php
use Twig\Node\NodeOutputInterface;
class_exists('Twig\Node\NodeOutputInterface');
if (\false) {
class Twig_NodeOutputInterface extends NodeOutputInterface
{
}
}
twig/lib/Twig/NodeTraverser.php000064400000000224151161070030012462
0ustar00<?php
use Twig\NodeTraverser;
class_exists('Twig\NodeTraverser');
if (\false) {
class Twig_NodeTraverser extends NodeTraverser
{
}
}
twig/lib/Twig/NodeVisitor/Escaper.php000064400000000301151161070030013522
0ustar00<?php
use Twig\NodeVisitor\EscaperNodeVisitor;
class_exists('Twig\NodeVisitor\EscaperNodeVisitor');
if (\false) {
class Twig_NodeVisitor_Escaper extends EscaperNodeVisitor
{
}
}
twig/lib/Twig/NodeVisitor/Optimizer.php000064400000000311151161070030014123
0ustar00<?php
use Twig\NodeVisitor\OptimizerNodeVisitor;
class_exists('Twig\NodeVisitor\OptimizerNodeVisitor');
if (\false) {
class Twig_NodeVisitor_Optimizer extends OptimizerNodeVisitor
{
}
}
twig/lib/Twig/NodeVisitor/SafeAnalysis.php000064400000000325151161070030014530
0ustar00<?php
use Twig\NodeVisitor\SafeAnalysisNodeVisitor;
class_exists('Twig\NodeVisitor\SafeAnalysisNodeVisitor');
if (\false) {
class Twig_NodeVisitor_SafeAnalysis extends SafeAnalysisNodeVisitor
{
}
}
twig/lib/Twig/NodeVisitor/Sandbox.php000064400000000301151161070030013536
0ustar00<?php
use Twig\NodeVisitor\SandboxNodeVisitor;
class_exists('Twig\NodeVisitor\SandboxNodeVisitor');
if (\false) {
class Twig_NodeVisitor_Sandbox extends SandboxNodeVisitor
{
}
}
twig/lib/Twig/NodeVisitorInterface.php000064400000000310151161070030013761
0ustar00<?php
use Twig\NodeVisitor\NodeVisitorInterface;
class_exists('Twig\NodeVisitor\NodeVisitorInterface');
if (\false) {
class Twig_NodeVisitorInterface extends NodeVisitorInterface
{
}
}
twig/lib/Twig/Parser.php000064400000000170151161070030011133
0ustar00<?php
use Twig\Parser;
class_exists('Twig\Parser');
if (\false) {
class Twig_Parser extends Parser
{
}
}
twig/lib/Twig/ParserInterface.php000064400000001305151161070030012755
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Error\SyntaxError;
use Twig\Node\ModuleNode;
use Twig\TokenStream;
/**
* Interface implemented by parser classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 3.0)
*/
interface Twig_ParserInterface
{
/**
* 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);
}
twig/lib/Twig/Profiler/Dumper/Base.php000064400000000262151161070030013571
0ustar00<?php
use Twig\Profiler\Dumper\BaseDumper;
class_exists('Twig\Profiler\Dumper\BaseDumper');
if (\false) {
class Twig_Profiler_Dumper_Base extends BaseDumper
{
}
}
twig/lib/Twig/Profiler/Dumper/Blackfire.php000064400000000306151161070030014600
0ustar00<?php
use Twig\Profiler\Dumper\BlackfireDumper;
class_exists('Twig\Profiler\Dumper\BlackfireDumper');
if (\false) {
class Twig_Profiler_Dumper_Blackfire extends BlackfireDumper
{
}
}
twig/lib/Twig/Profiler/Dumper/Html.php000064400000000262151161070030013623
0ustar00<?php
use Twig\Profiler\Dumper\HtmlDumper;
class_exists('Twig\Profiler\Dumper\HtmlDumper');
if (\false) {
class Twig_Profiler_Dumper_Html extends HtmlDumper
{
}
}
twig/lib/Twig/Profiler/Dumper/Text.php000064400000000262151161070030013643
0ustar00<?php
use Twig\Profiler\Dumper\TextDumper;
class_exists('Twig\Profiler\Dumper\TextDumper');
if (\false) {
class Twig_Profiler_Dumper_Text extends TextDumper
{
}
}
twig/lib/Twig/Profiler/Node/EnterProfile.php000064400000000306151161070030014745
0ustar00<?php
use Twig\Profiler\Node\EnterProfileNode;
class_exists('Twig\Profiler\Node\EnterProfileNode');
if (\false) {
class Twig_Profiler_Node_EnterProfile extends EnterProfileNode
{
}
}
twig/lib/Twig/Profiler/Node/LeaveProfile.php000064400000000306151161070030014724
0ustar00<?php
use Twig\Profiler\Node\LeaveProfileNode;
class_exists('Twig\Profiler\Node\LeaveProfileNode');
if (\false) {
class Twig_Profiler_Node_LeaveProfile extends LeaveProfileNode
{
}
}
twig/lib/Twig/Profiler/NodeVisitor/Profiler.php000064400000000340151161070030015507
0ustar00<?php
use Twig\Profiler\NodeVisitor\ProfilerNodeVisitor;
class_exists('Twig\Profiler\NodeVisitor\ProfilerNodeVisitor');
if (\false) {
class Twig_Profiler_NodeVisitor_Profiler extends ProfilerNodeVisitor
{
}
}
twig/lib/Twig/Profiler/Profile.php000064400000000227151161070030013064
0ustar00<?php
use Twig\Profiler\Profile;
class_exists('Twig\Profiler\Profile');
if (\false) {
class Twig_Profiler_Profile extends Profile
{
}
}
twig/lib/Twig/RuntimeLoaderInterface.php000064400000000324151161070030014273
0ustar00<?php
use Twig\RuntimeLoader\RuntimeLoaderInterface;
class_exists('Twig\RuntimeLoader\RuntimeLoaderInterface');
if (\false) {
class Twig_RuntimeLoaderInterface extends RuntimeLoaderInterface
{
}
}
twig/lib/Twig/Sandbox/SecurityError.php000064400000000254151161070030014121
0ustar00<?php
use Twig\Sandbox\SecurityError;
class_exists('Twig\Sandbox\SecurityError');
if (\false) {
class Twig_Sandbox_SecurityError extends SecurityError
{
}
}
twig/lib/Twig/Sandbox/SecurityNotAllowedFilterError.php000064400000000354151161070030017261
0ustar00<?php
use Twig\Sandbox\SecurityNotAllowedFilterError;
class_exists('Twig\Sandbox\SecurityNotAllowedFilterError');
if (\false) {
class Twig_Sandbox_SecurityNotAllowedFilterError extends
SecurityNotAllowedFilterError
{
}
}
twig/lib/Twig/Sandbox/SecurityNotAllowedFunctionError.php000064400000000364151161070030017622
0ustar00<?php
use Twig\Sandbox\SecurityNotAllowedFunctionError;
class_exists('Twig\Sandbox\SecurityNotAllowedFunctionError');
if (\false) {
class Twig_Sandbox_SecurityNotAllowedFunctionError extends
SecurityNotAllowedFunctionError
{
}
}
twig/lib/Twig/Sandbox/SecurityNotAllowedMethodError.php000064400000000354151161070030017254
0ustar00<?php
use Twig\Sandbox\SecurityNotAllowedMethodError;
class_exists('Twig\Sandbox\SecurityNotAllowedMethodError');
if (\false) {
class Twig_Sandbox_SecurityNotAllowedMethodError extends
SecurityNotAllowedMethodError
{
}
}
twig/lib/Twig/Sandbox/SecurityNotAllowedPropertyError.php000064400000000364151161070030017661
0ustar00<?php
use Twig\Sandbox\SecurityNotAllowedPropertyError;
class_exists('Twig\Sandbox\SecurityNotAllowedPropertyError');
if (\false) {
class Twig_Sandbox_SecurityNotAllowedPropertyError extends
SecurityNotAllowedPropertyError
{
}
}
twig/lib/Twig/Sandbox/SecurityNotAllowedTagError.php000064400000000340151161070030016542
0ustar00<?php
use Twig\Sandbox\SecurityNotAllowedTagError;
class_exists('Twig\Sandbox\SecurityNotAllowedTagError');
if (\false) {
class Twig_Sandbox_SecurityNotAllowedTagError extends
SecurityNotAllowedTagError
{
}
}
twig/lib/Twig/Sandbox/SecurityPolicy.php000064400000000260151161070030014264
0ustar00<?php
use Twig\Sandbox\SecurityPolicy;
class_exists('Twig\Sandbox\SecurityPolicy');
if (\false) {
class Twig_Sandbox_SecurityPolicy extends SecurityPolicy
{
}
}
twig/lib/Twig/Sandbox/SecurityPolicyInterface.php000064400000000324151161070030016106
0ustar00<?php
use Twig\Sandbox\SecurityPolicyInterface;
class_exists('Twig\Sandbox\SecurityPolicyInterface');
if (\false) {
class Twig_Sandbox_SecurityPolicyInterface extends
SecurityPolicyInterface
{
}
}
twig/lib/Twig/SimpleFilter.php000064400000000212151161070030012273
0ustar00<?php
use Twig\TwigFilter;
class_exists('Twig\TwigFilter');
if (\false) {
class Twig_SimpleFilter extends TwigFilter
{
}
}
twig/lib/Twig/SimpleFunction.php000064400000000222151161070030012634
0ustar00<?php
use Twig\TwigFunction;
class_exists('Twig\TwigFunction');
if (\false) {
class Twig_SimpleFunction extends TwigFunction
{
}
}
twig/lib/Twig/SimpleTest.php000064400000000202151161070030011764
0ustar00<?php
use Twig\TwigTest;
class_exists('Twig\TwigTest');
if (\false) {
class Twig_SimpleTest extends TwigTest
{
}
}
twig/lib/Twig/Source.php000064400000000170151161070030011137
0ustar00<?php
use Twig\Source;
class_exists('Twig\Source');
if (\false) {
class Twig_Source extends Source
{
}
}
twig/lib/Twig/SourceContextLoaderInterface.php000064400000000336151161070030015460
0ustar00<?php
use Twig\Loader\SourceContextLoaderInterface;
class_exists('Twig\Loader\SourceContextLoaderInterface');
if (\false) {
class Twig_SourceContextLoaderInterface extends
SourceContextLoaderInterface
{
}
}
twig/lib/Twig/Template.php000064400000000200151161070030011444
0ustar00<?php
use Twig\Template;
class_exists('Twig\Template');
if (\false) {
class Twig_Template extends Template
{
}
}
twig/lib/Twig/TemplateInterface.php000064400000002313151161070030013274
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Environment;
/**
* Interface implemented by all compiled templates.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 3.0)
*/
interface Twig_TemplateInterface
{
const ANY_CALL = 'any';
const ARRAY_CALL = 'array';
const METHOD_CALL = 'method';
/**
* Renders the template with the given context and returns it as
string.
*
* @param array $context An array of parameters to pass to the template
*
* @return string The rendered template
*/
public function render(array $context);
/**
* Displays the template with the given context.
*
* @param array $context An array of parameters to pass to the template
* @param array $blocks An array of blocks to pass to the template
*/
public function display(array $context, array $blocks = []);
/**
* Returns the bound environment for this template.
*
* @return Environment
*/
public function getEnvironment();
}
twig/lib/Twig/TemplateWrapper.php000064400000000234151161070030013014
0ustar00<?php
use Twig\TemplateWrapper;
class_exists('Twig\TemplateWrapper');
if (\false) {
class Twig_TemplateWrapper extends TemplateWrapper
{
}
}
twig/lib/Twig/Test/Function.php000064400000001527151161070030012412
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Test_Function class is deprecated since
version 1.12 and will be removed in 2.0. Use \Twig\TwigTest instead.',
E_USER_DEPRECATED);
/**
* Represents a function template test.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Test_Function extends Twig_Test
{
protected $function;
public function __construct($function, array $options = [])
{
$options['callable'] = $function;
parent::__construct($options);
$this->function = $function;
}
public function compile()
{
return $this->function;
}
}
twig/lib/Twig/Test/IntegrationTestCase.php000064400000000273151161070030014541
0ustar00<?php
use Twig\Test\IntegrationTestCase;
class_exists('Twig\Test\IntegrationTestCase');
if (\false) {
class Twig_Test_IntegrationTestCase extends IntegrationTestCase
{
}
}
twig/lib/Twig/Test/Method.php000064400000002052151161070030012037
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\Extension\ExtensionInterface;
@trigger_error('The Twig_Test_Method class is deprecated since version
1.12 and will be removed in 2.0. Use \Twig\TwigTest instead.',
E_USER_DEPRECATED);
/**
* Represents a method template test.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Test_Method extends Twig_Test
{
protected $extension;
protected $method;
public function __construct(ExtensionInterface $extension, $method,
array $options = [])
{
$options['callable'] = [$extension, $method];
parent::__construct($options);
$this->extension = $extension;
$this->method = $method;
}
public function compile()
{
return
sprintf('$this->env->getExtension(\'%s\')->%s',
\get_class($this->extension), $this->method);
}
}
twig/lib/Twig/Test/Node.php000064400000001446151161070030011512
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Test_Node class is deprecated since version
1.12 and will be removed in 2.0.', E_USER_DEPRECATED);
/**
* Represents a template test as a Node.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_Test_Node extends Twig_Test
{
protected $class;
public function __construct($class, array $options = [])
{
parent::__construct($options);
$this->class = $class;
}
public function getClass()
{
return $this->class;
}
public function compile()
{
}
}
twig/lib/Twig/Test/NodeTestCase.php000064400000000237151161070030013143
0ustar00<?php
use Twig\Test\NodeTestCase;
class_exists('Twig\Test\NodeTestCase');
if (\false) {
class Twig_Test_NodeTestCase extends NodeTestCase
{
}
}
twig/lib/Twig/Test.php000064400000001564151161070030010626 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@trigger_error('The Twig_Test class is deprecated since version 1.12
and will be removed in 2.0. Use \Twig\TwigTest instead.',
E_USER_DEPRECATED);
/**
* Represents a template test.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
abstract class Twig_Test implements Twig_TestInterface,
Twig_TestCallableInterface
{
protected $options;
protected $arguments = [];
public function __construct(array $options = [])
{
$this->options = array_merge([
'callable' => null,
], $options);
}
public function getCallable()
{
return $this->options['callable'];
}
}
twig/lib/Twig/TestCallableInterface.php000064400000000656151161070030014070
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Represents a callable template test.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
interface Twig_TestCallableInterface
{
public function getCallable();
}
twig/lib/Twig/TestInterface.php000064400000000770151161070030012445
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Represents a template test.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
interface Twig_TestInterface
{
/**
* Compiles a test.
*
* @return string The PHP code for the test
*/
public function compile();
}
twig/lib/Twig/Token.php000064400000000164151161070030010762
0ustar00<?php
use Twig\Token;
class_exists('Twig\Token');
if (\false) {
class Twig_Token extends Token
{
}
}
twig/lib/Twig/TokenParser/AutoEscape.php000064400000000315151161070030014166
0ustar00<?php
use Twig\TokenParser\AutoEscapeTokenParser;
class_exists('Twig\TokenParser\AutoEscapeTokenParser');
if (\false) {
class Twig_TokenParser_AutoEscape extends AutoEscapeTokenParser
{
}
}
twig/lib/Twig/TokenParser/Block.php000064400000000271151161070030013170
0ustar00<?php
use Twig\TokenParser\BlockTokenParser;
class_exists('Twig\TokenParser\BlockTokenParser');
if (\false) {
class Twig_TokenParser_Block extends BlockTokenParser
{
}
}
twig/lib/Twig/TokenParser/Deprecated.php000064400000000315151161070030014175
0ustar00<?php
use Twig\TokenParser\DeprecatedTokenParser;
class_exists('Twig\TokenParser\DeprecatedTokenParser');
if (\false) {
class Twig_TokenParser_Deprecated extends DeprecatedTokenParser
{
}
}
twig/lib/Twig/TokenParser/Do.php000064400000000255151161070030012502
0ustar00<?php
use Twig\TokenParser\DoTokenParser;
class_exists('Twig\TokenParser\DoTokenParser');
if (\false) {
class Twig_TokenParser_Do extends DoTokenParser
{
}
}
twig/lib/Twig/TokenParser/Embed.php000064400000000271151161070030013152
0ustar00<?php
use Twig\TokenParser\EmbedTokenParser;
class_exists('Twig\TokenParser\EmbedTokenParser');
if (\false) {
class Twig_TokenParser_Embed extends EmbedTokenParser
{
}
}
twig/lib/Twig/TokenParser/Extends.php000064400000000301151161070030013542
0ustar00<?php
use Twig\TokenParser\ExtendsTokenParser;
class_exists('Twig\TokenParser\ExtendsTokenParser');
if (\false) {
class Twig_TokenParser_Extends extends ExtendsTokenParser
{
}
}
twig/lib/Twig/TokenParser/Filter.php000064400000000275151161070030013367
0ustar00<?php
use Twig\TokenParser\FilterTokenParser;
class_exists('Twig\TokenParser\FilterTokenParser');
if (\false) {
class Twig_TokenParser_Filter extends FilterTokenParser
{
}
}
twig/lib/Twig/TokenParser/Flush.php000064400000000271151161070030013217
0ustar00<?php
use Twig\TokenParser\FlushTokenParser;
class_exists('Twig\TokenParser\FlushTokenParser');
if (\false) {
class Twig_TokenParser_Flush extends FlushTokenParser
{
}
}
twig/lib/Twig/TokenParser/For.php000064400000000261151161070030012663
0ustar00<?php
use Twig\TokenParser\ForTokenParser;
class_exists('Twig\TokenParser\ForTokenParser');
if (\false) {
class Twig_TokenParser_For extends ForTokenParser
{
}
}
twig/lib/Twig/TokenParser/From.php000064400000000265151161070030013044
0ustar00<?php
use Twig\TokenParser\FromTokenParser;
class_exists('Twig\TokenParser\FromTokenParser');
if (\false) {
class Twig_TokenParser_From extends FromTokenParser
{
}
}
twig/lib/Twig/TokenParser/If.php000064400000000255151161070030012476
0ustar00<?php
use Twig\TokenParser\IfTokenParser;
class_exists('Twig\TokenParser\IfTokenParser');
if (\false) {
class Twig_TokenParser_If extends IfTokenParser
{
}
}
twig/lib/Twig/TokenParser/Import.php000064400000000275151161070030013414
0ustar00<?php
use Twig\TokenParser\ImportTokenParser;
class_exists('Twig\TokenParser\ImportTokenParser');
if (\false) {
class Twig_TokenParser_Import extends ImportTokenParser
{
}
}
twig/lib/Twig/TokenParser/Include.php000064400000000301151161070030013513
0ustar00<?php
use Twig\TokenParser\IncludeTokenParser;
class_exists('Twig\TokenParser\IncludeTokenParser');
if (\false) {
class Twig_TokenParser_Include extends IncludeTokenParser
{
}
}
twig/lib/Twig/TokenParser/Macro.php000064400000000271151161070030013177
0ustar00<?php
use Twig\TokenParser\MacroTokenParser;
class_exists('Twig\TokenParser\MacroTokenParser');
if (\false) {
class Twig_TokenParser_Macro extends MacroTokenParser
{
}
}
twig/lib/Twig/TokenParser/Sandbox.php000064400000000301151161070030013526
0ustar00<?php
use Twig\TokenParser\SandboxTokenParser;
class_exists('Twig\TokenParser\SandboxTokenParser');
if (\false) {
class Twig_TokenParser_Sandbox extends SandboxTokenParser
{
}
}
twig/lib/Twig/TokenParser/Set.php000064400000000261151161070030012670
0ustar00<?php
use Twig\TokenParser\SetTokenParser;
class_exists('Twig\TokenParser\SetTokenParser');
if (\false) {
class Twig_TokenParser_Set extends SetTokenParser
{
}
}
twig/lib/Twig/TokenParser/Spaceless.php000064400000000311151161070030014053
0ustar00<?php
use Twig\TokenParser\SpacelessTokenParser;
class_exists('Twig\TokenParser\SpacelessTokenParser');
if (\false) {
class Twig_TokenParser_Spaceless extends SpacelessTokenParser
{
}
}
twig/lib/Twig/TokenParser/Use.php000064400000000261151161070030012671
0ustar00<?php
use Twig\TokenParser\UseTokenParser;
class_exists('Twig\TokenParser\UseTokenParser');
if (\false) {
class Twig_TokenParser_Use extends UseTokenParser
{
}
}
twig/lib/Twig/TokenParser/With.php000064400000000265151161070030013054
0ustar00<?php
use Twig\TokenParser\WithTokenParser;
class_exists('Twig\TokenParser\WithTokenParser');
if (\false) {
class Twig_TokenParser_With extends WithTokenParser
{
}
}
twig/lib/Twig/TokenParser.php000064400000000274151161070030012141
0ustar00<?php
use Twig\TokenParser\AbstractTokenParser;
class_exists('Twig\TokenParser\AbstractTokenParser');
if (\false) {
class Twig_TokenParser extends AbstractTokenParser
{
}
}
twig/lib/Twig/TokenParserBroker.php000064400000007000151161070030013300
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Arnaud Le Blanc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\TokenParser\TokenParserInterface;
/**
* Default implementation of a token parser broker.
*
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
class Twig_TokenParserBroker implements Twig_TokenParserBrokerInterface
{
protected $parser;
protected $parsers = [];
protected $brokers = [];
/**
* @param array|\Traversable $parsers A \Traversable of
Twig_TokenParserInterface instances
* @param array|\Traversable $brokers A \Traversable of
Twig_TokenParserBrokerInterface instances
* @param bool $triggerDeprecationError
*/
public function __construct($parsers = [], $brokers = [],
$triggerDeprecationError = true)
{
if ($triggerDeprecationError) {
@trigger_error('The '.__CLASS__.' class is
deprecated since version 1.12 and will be removed in 2.0.',
E_USER_DEPRECATED);
}
foreach ($parsers as $parser) {
if (!$parser instanceof TokenParserInterface) {
throw new \LogicException('$parsers must a an array of
Twig_TokenParserInterface.');
}
$this->parsers[$parser->getTag()] = $parser;
}
foreach ($brokers as $broker) {
if (!$broker instanceof Twig_TokenParserBrokerInterface) {
throw new \LogicException('$brokers must a an array of
Twig_TokenParserBrokerInterface.');
}
$this->brokers[] = $broker;
}
}
public function addTokenParser(TokenParserInterface $parser)
{
$this->parsers[$parser->getTag()] = $parser;
}
public function removeTokenParser(TokenParserInterface $parser)
{
$name = $parser->getTag();
if (isset($this->parsers[$name]) && $parser ===
$this->parsers[$name]) {
unset($this->parsers[$name]);
}
}
public function addTokenParserBroker(self $broker)
{
$this->brokers[] = $broker;
}
public function removeTokenParserBroker(self $broker)
{
if (false !== $pos = array_search($broker, $this->brokers)) {
unset($this->brokers[$pos]);
}
}
/**
* Gets a suitable TokenParser for a tag.
*
* First looks in parsers, then in brokers.
*
* @param string $tag A tag name
*
* @return TokenParserInterface|null A Twig_TokenParserInterface or
null if no suitable TokenParser was found
*/
public function getTokenParser($tag)
{
if (isset($this->parsers[$tag])) {
return $this->parsers[$tag];
}
$broker = end($this->brokers);
while (false !== $broker) {
$parser = $broker->getTokenParser($tag);
if (null !== $parser) {
return $parser;
}
$broker = prev($this->brokers);
}
}
public function getParsers()
{
return $this->parsers;
}
public function getParser()
{
return $this->parser;
}
public function setParser(Twig_ParserInterface $parser)
{
$this->parser = $parser;
foreach ($this->parsers as $tokenParser) {
$tokenParser->setParser($parser);
}
foreach ($this->brokers as $broker) {
$broker->setParser($parser);
}
}
}
twig/lib/Twig/TokenParserBrokerInterface.php000064400000002317151161070030015127
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Arnaud Le Blanc
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Twig\TokenParser\TokenParserInterface;
/**
* Interface implemented by token parser brokers.
*
* Token parser brokers allows to implement custom logic in the process of
resolving a token parser for a given tag name.
*
* @author Arnaud Le Blanc <arnaud.lb@gmail.com>
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
interface Twig_TokenParserBrokerInterface
{
/**
* Gets a TokenParser suitable for a tag.
*
* @param string $tag A tag name
*
* @return TokenParserInterface|null A Twig_TokenParserInterface or
null if no suitable TokenParser was found
*/
public function getTokenParser($tag);
/**
* Calls Twig\TokenParser\TokenParserInterface::setParser on all
parsers the implementation knows of.
*/
public function setParser(Twig_ParserInterface $parser);
/**
* Gets the Twig_ParserInterface.
*
* @return Twig_ParserInterface|null A Twig_ParserInterface instance or
null
*/
public function getParser();
}
twig/lib/Twig/TokenParserInterface.php000064400000000310151161070030013751
0ustar00<?php
use Twig\TokenParser\TokenParserInterface;
class_exists('Twig\TokenParser\TokenParserInterface');
if (\false) {
class Twig_TokenParserInterface extends TokenParserInterface
{
}
}
twig/lib/Twig/TokenStream.php000064400000000214151161070030012132
0ustar00<?php
use Twig\TokenStream;
class_exists('Twig\TokenStream');
if (\false) {
class Twig_TokenStream extends TokenStream
{
}
}
twig/lib/Twig/Util/DeprecationCollector.php000064400000000277151161070030014730
0ustar00<?php
use Twig\Util\DeprecationCollector;
class_exists('Twig\Util\DeprecationCollector');
if (\false) {
class Twig_Util_DeprecationCollector extends DeprecationCollector
{
}
}
twig/lib/Twig/Util/TemplateDirIterator.php000064400000000273151161070030014544
0ustar00<?php
use Twig\Util\TemplateDirIterator;
class_exists('Twig\Util\TemplateDirIterator');
if (\false) {
class Twig_Util_TemplateDirIterator extends TemplateDirIterator
{
}
}
twig/src/Cache/CacheInterface.php000064400000002676151161070030012652
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Cache;
/**
* Interface implemented by cache classes.
*
* It is highly recommended to always store templates on the filesystem to
* benefit from the PHP opcode cache. This interface is mostly useful if
you
* need to implement a custom strategy for storing templates on the
filesystem.
*
* @author Andrew Tch <andrew@noop.lv>
*/
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');
twig/src/Cache/FilesystemCache.php000064400000005060151161070030013064
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Cache;
/**
* Implements a cache on the filesystem.
*
* @author Andrew Tch <andrew@noop.lv>
*/
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');
twig/src/Cache/NullCache.php000064400000001257151161070030011656
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Cache;
/**
* Implements a no-cache strategy.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Compiler.php000064400000016172151161070030010571 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Node\ModuleNode;
/**
* Compiles a node to PHP code.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Compiler implements \Twig_CompilerInterface
{
protected $lastLine;
protected $source;
protected $indentation;
protected $env;
protected $debugInfo = [];
protected $sourceOffset;
protected $sourceLine;
protected $filename;
private $varNameSalt = 0;
public function __construct(Environment $env)
{
$this->env = $env;
}
/**
* @deprecated since 1.25 (to be removed in 2.0)
*/
public function getFilename()
{
@trigger_error(sprintf('The %s() method is deprecated since
version 1.25 and will be removed in 2.0.', __FUNCTION__),
E_USER_DEPRECATED);
return $this->filename;
}
/**
* Returns the environment instance related to this compiler.
*
* @return 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(\Twig_NodeInterface $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;
if ($node instanceof ModuleNode) {
// to be removed in 2.0
$this->filename = $node->getTemplateName();
}
$node->compile($this);
return $this;
}
public function subcompile(\Twig_NodeInterface $node, $raw = true)
{
if (false === $raw) {
$this->source .= str_repeat(' ',
$this->indentation * 4);
}
$node->compile($this);
return $this;
}
/**
* Adds a raw string to the compiled code.
*
* @param string $string The string
*
* @return $this
*/
public function raw($string)
{
$this->source .= $string;
return $this;
}
/**
* Writes a string to the compiled code by adding indentation.
*
* @return $this
*/
public function write()
{
$strings = \func_get_args();
foreach ($strings as $string) {
$this->source .= str_repeat(' ',
$this->indentation * 4).$string;
}
return $this;
}
/**
* Appends an indentation to the current PHP code after compilation.
*
* @return $this
*
* @deprecated since 1.27 (to be removed in 2.0).
*/
public function addIndentation()
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0. Use
write(\'\') instead.', E_USER_DEPRECATED);
$this->source .= str_repeat(' ', $this->indentation
* 4);
return $this;
}
/**
* Adds a quoted string to the compiled code.
*
* @param string $value The string
*
* @return $this
*/
public function string($value)
{
$this->source .= sprintf('"%s"',
addcslashes($value, "\0\t\"\$\\"));
return $this;
}
/**
* Returns a PHP representation of a given value.
*
* @param mixed $value The value to convert
*
* @return $this
*/
public function repr($value)
{
if (\is_int($value) || \is_float($value)) {
if (false !== $locale = setlocale(LC_NUMERIC, '0')) {
setlocale(LC_NUMERIC, 'C');
}
$this->raw(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('[');
$first = true;
foreach ($value as $key => $v) {
if (!$first) {
$this->raw(', ');
}
$first = false;
$this->repr($key);
$this->raw(' => ');
$this->repr($v);
}
$this->raw(']');
} else {
$this->string($value);
}
return $this;
}
/**
* Adds debugging information.
*
* @return $this
*/
public function addDebugInfo(\Twig_NodeInterface $node)
{
if ($node->getTemplateLine() != $this->lastLine) {
$this->write(sprintf("// line %d\n",
$node->getTemplateLine()));
// when mbstring.func_overload is set to 2
// mb_substr_count() replaces substr_count()
// but they have different signatures!
if (((int) ini_get('mbstring.func_overload')) &
2) {
@trigger_error('Support for having
"mbstring.func_overload" different from 0 is deprecated version
1.29 and will be removed in 2.0.', E_USER_DEPRECATED);
// this is much slower than the "right" version
$this->sourceLine +=
mb_substr_count(mb_substr($this->source, $this->sourceOffset),
"\n");
} else {
$this->sourceLine += substr_count($this->source,
"\n", $this->sourceOffset);
}
$this->sourceOffset = \strlen($this->source);
$this->debugInfo[$this->sourceLine] =
$node->getTemplateLine();
$this->lastLine = $node->getTemplateLine();
}
return $this;
}
public function getDebugInfo()
{
ksort($this->debugInfo);
return $this->debugInfo;
}
/**
* Indents the generated code.
*
* @param int $step The number of indentation to add
*
* @return $this
*/
public function indent($step = 1)
{
$this->indentation += $step;
return $this;
}
/**
* Outdents the generated code.
*
* @param int $step The number of indentation to remove
*
* @return $this
*
* @throws \LogicException When trying to outdent too much so the
indentation would become negative
*/
public function outdent($step = 1)
{
// can't outdent by more steps than the current indentation
level
if ($this->indentation < $step) {
throw new \LogicException('Unable to call outdent() as the
indentation would become negative.');
}
$this->indentation -= $step;
return $this;
}
public function getVarName()
{
return sprintf('__internal_%s', hash('sha256',
__METHOD__.$this->varNameSalt++));
}
}
class_alias('Twig\Compiler', 'Twig_Compiler');
twig/src/Environment.php000064400000147340151161070030011325
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Cache\CacheInterface;
use Twig\Cache\FilesystemCache;
use Twig\Cache\NullCache;
use Twig\Error\Error;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Error\SyntaxError;
use Twig\Extension\CoreExtension;
use Twig\Extension\EscaperExtension;
use Twig\Extension\ExtensionInterface;
use Twig\Extension\GlobalsInterface;
use Twig\Extension\InitRuntimeInterface;
use Twig\Extension\OptimizerExtension;
use Twig\Extension\StagingExtension;
use Twig\Loader\ArrayLoader;
use Twig\Loader\ChainLoader;
use Twig\Loader\LoaderInterface;
use Twig\Loader\SourceContextLoaderInterface;
use Twig\Node\ModuleNode;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\RuntimeLoader\RuntimeLoaderInterface;
use Twig\TokenParser\TokenParserInterface;
/**
* Stores the Twig configuration.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Environment
{
const VERSION = '1.42.5';
const VERSION_ID = 14205;
const MAJOR_VERSION = 1;
const MINOR_VERSION = 42;
const RELEASE_VERSION = 5;
const EXTRA_VERSION = '';
protected $charset;
protected $loader;
protected $debug;
protected $autoReload;
protected $cache;
protected $lexer;
protected $parser;
protected $compiler;
protected $baseTemplateClass;
protected $extensions;
protected $parsers;
protected $visitors;
protected $filters;
protected $tests;
protected $functions;
protected $globals;
protected $runtimeInitialized = false;
protected $extensionInitialized = false;
protected $loadedTemplates;
protected $strictVariables;
protected $unaryOperators;
protected $binaryOperators;
protected $templateClassPrefix = '__TwigTemplate_';
protected $functionCallbacks = [];
protected $filterCallbacks = [];
protected $staging;
private $originalCache;
private $bcWriteCacheFile = false;
private $bcGetCacheFilename = false;
private $lastModifiedExtension = 0;
private $extensionsByClass = [];
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
* * true: equivalent to html
* * html, js: set the autoescaping to one of the
supported strategies
* * name: set the autoescaping strategy based on the
template name extension
* * PHP callback: a PHP callback that returns an
escaping strategy based on the template "name"
*
* * optimizations: A flag that indicates which optimizations to apply
* (default to -1 which means that all optimizations
are enabled;
* set it to 0 to disable).
*/
public function __construct(LoaderInterface $loader = null, $options =
[])
{
if (null !== $loader) {
$this->setLoader($loader);
} else {
@trigger_error('Not passing a
"Twig\Lodaer\LoaderInterface" as the first constructor argument
of "Twig\Environment" is deprecated since version 1.21.',
E_USER_DEPRECATED);
}
$options = array_merge([
'debug' => false,
'charset' => 'UTF-8',
'base_template_class' =>
'\Twig\Template',
'strict_variables' => false,
'autoescape' => 'html',
'cache' => false,
'auto_reload' => null,
'optimizations' => -1,
], $options);
$this->debug = (bool) $options['debug'];
$this->charset = strtoupper($options['charset']);
$this->baseTemplateClass =
$options['base_template_class'];
$this->autoReload = null === $options['auto_reload'] ?
$this->debug : (bool) $options['auto_reload'];
$this->strictVariables = (bool)
$options['strict_variables'];
$this->setCache($options['cache']);
$this->addExtension(new CoreExtension());
$this->addExtension(new
EscaperExtension($options['autoescape']));
$this->addExtension(new
OptimizerExtension($options['optimizations']));
$this->staging = new StagingExtension();
// For BC
if (\is_string($this->originalCache)) {
$r = new \ReflectionMethod($this, 'writeCacheFile');
if (__CLASS__ !== $r->getDeclaringClass()->getName()) {
@trigger_error('The Twig\Environment::writeCacheFile
method is deprecated since version 1.22 and will be removed in Twig
2.0.', E_USER_DEPRECATED);
$this->bcWriteCacheFile = true;
}
$r = new \ReflectionMethod($this,
'getCacheFilename');
if (__CLASS__ !== $r->getDeclaringClass()->getName()) {
@trigger_error('The Twig\Environment::getCacheFilename
method is deprecated since version 1.22 and will be removed in Twig
2.0.', E_USER_DEPRECATED);
$this->bcGetCacheFilename = true;
}
}
}
/**
* Gets the base template class for compiled templates.
*
* @return string The base template class name
*/
public function getBaseTemplateClass()
{
return $this->baseTemplateClass;
}
/**
* Sets the base template class for compiled templates.
*
* @param string $class The base template class name
*/
public function setBaseTemplateClass($class)
{
$this->baseTemplateClass = $class;
$this->updateOptionsHash();
}
/**
* Enables debugging mode.
*/
public function enableDebug()
{
$this->debug = true;
$this->updateOptionsHash();
}
/**
* Disables debugging mode.
*/
public function disableDebug()
{
$this->debug = false;
$this->updateOptionsHash();
}
/**
* Checks if debug mode is enabled.
*
* @return bool true if debug mode is enabled, false otherwise
*/
public function isDebug()
{
return $this->debug;
}
/**
* Enables the auto_reload option.
*/
public function enableAutoReload()
{
$this->autoReload = true;
}
/**
* Disables the auto_reload option.
*/
public function disableAutoReload()
{
$this->autoReload = false;
}
/**
* Checks if the auto_reload option is enabled.
*
* @return bool true if auto_reload is enabled, false otherwise
*/
public function isAutoReload()
{
return $this->autoReload;
}
/**
* Enables the strict_variables option.
*/
public function enableStrictVariables()
{
$this->strictVariables = true;
$this->updateOptionsHash();
}
/**
* Disables the strict_variables option.
*/
public function disableStrictVariables()
{
$this->strictVariables = false;
$this->updateOptionsHash();
}
/**
* Checks if the strict_variables option is enabled.
*
* @return bool true if strict_variables is enabled, false otherwise
*/
public function isStrictVariables()
{
return $this->strictVariables;
}
/**
* Gets the current cache implementation.
*
* @param bool $original Whether to return the original cache option or
the real cache instance
*
* @return 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 (null === $cache) {
@trigger_error('Using "null" as the cache
strategy is deprecated since version 1.23 and will be removed in Twig
2.0.', E_USER_DEPRECATED);
$this->originalCache = false;
$this->cache = new NullCache();
} elseif ($cache instanceof CacheInterface) {
$this->originalCache = $this->cache = $cache;
} else {
throw new \LogicException(sprintf('Cache can only be a
string, false, or a \Twig\Cache\CacheInterface implementation.'));
}
}
/**
* Gets the cache filename for a given template.
*
* @param string $name The template name
*
* @return string|false The cache file name or false when caching is
disabled
*
* @deprecated since 1.22 (to be removed in 2.0)
*/
public function getCacheFilename($name)
{
@trigger_error(sprintf('The %s method is deprecated since
version 1.22 and will be removed in Twig 2.0.', __METHOD__),
E_USER_DEPRECATED);
$key = $this->cache->generateKey($name,
$this->getTemplateClass($name));
return !$key ? false : $key;
}
/**
* Gets the template class associated with the given string.
*
* The generated template class is based on the following parameters:
*
* * The cache key for the given template;
* * The currently enabled extensions;
* * Whether the Twig C extension is available or not;
* * PHP version;
* * Twig version;
* * Options with what environment was created.
*
* @param string $name The name for which to calculate the template
class name
* @param int|null $index The index if it is an embedded template
*
* @return string The template class name
*/
public function getTemplateClass($name, $index = null)
{
$key =
$this->getLoader()->getCacheKey($name).$this->optionsHash;
return $this->templateClassPrefix.hash('sha256',
$key).(null === $index ? '' : '___'.$index);
}
/**
* Gets the template class prefix.
*
* @return string The template class prefix
*
* @deprecated since 1.22 (to be removed in 2.0)
*/
public function getTemplateClassPrefix()
{
@trigger_error(sprintf('The %s method is deprecated since
version 1.22 and will be removed in Twig 2.0.', __METHOD__),
E_USER_DEPRECATED);
return $this->templateClassPrefix;
}
/**
* Renders a template.
*
* @param string|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|\Twig\Template $name The template name
*
* @throws LoaderError When the template cannot be found
* @throws RuntimeError When a previously generated cache is corrupted
* @throws SyntaxError When an error occurred during compilation
*
* @return TemplateWrapper
*/
public function load($name)
{
if ($name instanceof TemplateWrapper) {
return $name;
}
if ($name instanceof Template) {
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 \Twig_TemplateInterface A template instance representing the
given template name
*
* @throws LoaderError When the template cannot be found
* @throws RuntimeError When a previously generated cache is corrupted
* @throws SyntaxError When an error occurred during compilation
*
* @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)) {
if ($this->bcGetCacheFilename) {
$key = $this->getCacheFilename($name);
} else {
$key = $this->cache->generateKey($name, $mainCls);
}
if (!$this->isAutoReload() ||
$this->isTemplateFresh($name, $this->cache->getTimestamp($key))) {
$this->cache->load($key);
}
$source = null;
if (!class_exists($cls, false)) {
$loader = $this->getLoader();
if (!$loader instanceof SourceContextLoaderInterface) {
$source = new Source($loader->getSource($name),
$name);
} else {
$source = $loader->getSourceContext($name);
}
$content = $this->compileSource($source);
if ($this->bcWriteCacheFile) {
$this->writeCacheFile($key, $content);
} else {
$this->cache->write($key, $content);
$this->cache->load($key);
}
if (!class_exists($mainCls, false)) {
/* Last line of defense if either
$this->bcWriteCacheFile was used,
* $this->cache is implemented as a no-op or we have
a race condition
* where the cache was cleared between the above calls
to write to and load from
* the cache.
*/
eval('?>'.$content);
}
}
if (!class_exists($cls, false)) {
throw new RuntimeError(sprintf('Failed to load Twig
template "%s", index "%s": cache might be
corrupted.', $name, $index), -1, $source);
}
}
if (!$this->runtimeInitialized) {
$this->initRuntime();
}
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, $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 {
$template = new TemplateWrapper($this,
$this->loadTemplate($name));
} catch (\Exception $e) {
$this->setLoader($current);
throw $e;
} catch (\Throwable $e) {
$this->setLoader($current);
throw $e;
}
$this->setLoader($current);
return $template;
}
/**
* Returns true if the template is still fresh.
*
* Besides checking the loader for freshness information,
* this method also checks if the enabled extensions have
* not changed.
*
* @param string $name The template name
* @param int $time The last modification time of the cached
template
*
* @return bool true if the template is fresh, false otherwise
*/
public function isTemplateFresh($name, $time)
{
if (0 === $this->lastModifiedExtension) {
foreach ($this->extensions as $extension) {
$r = new \ReflectionObject($extension);
if (file_exists($r->getFileName()) &&
($extensionTime = filemtime($r->getFileName())) >
$this->lastModifiedExtension) {
$this->lastModifiedExtension = $extensionTime;
}
}
}
return $this->lastModifiedExtension <= $time &&
$this->getLoader()->isFresh($name, $time);
}
/**
* Tries to load a template consecutively from an array.
*
* Similar to 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|Template|\Twig\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)));
}
/**
* Clears the internal template cache.
*
* @deprecated since 1.18.3 (to be removed in 2.0)
*/
public function clearTemplateCache()
{
@trigger_error(sprintf('The %s method is deprecated since
version 1.18.3 and will be removed in Twig 2.0.', __METHOD__),
E_USER_DEPRECATED);
$this->loadedTemplates = [];
}
/**
* Clears the template cache files on the filesystem.
*
* @deprecated since 1.22 (to be removed in 2.0)
*/
public function clearCacheFiles()
{
@trigger_error(sprintf('The %s method is deprecated since
version 1.22 and will be removed in Twig 2.0.', __METHOD__),
E_USER_DEPRECATED);
if (\is_string($this->originalCache)) {
foreach (new \RecursiveIteratorIterator(new
\RecursiveDirectoryIterator($this->originalCache),
\RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($file->isFile()) {
@unlink($file->getPathname());
}
}
}
}
/**
* Gets the Lexer instance.
*
* @return \Twig_LexerInterface
*
* @deprecated since 1.25 (to be removed in 2.0)
*/
public function getLexer()
{
@trigger_error(sprintf('The %s() method is deprecated since
version 1.25 and will be removed in 2.0.', __FUNCTION__),
E_USER_DEPRECATED);
if (null === $this->lexer) {
$this->lexer = new Lexer($this);
}
return $this->lexer;
}
public function setLexer(\Twig_LexerInterface $lexer)
{
$this->lexer = $lexer;
}
/**
* Tokenizes a source code.
*
* @param string|Source $source The template source code
* @param string $name The template name (deprecated)
*
* @return TokenStream
*
* @throws SyntaxError When the code is syntactically wrong
*/
public function tokenize($source, $name = null)
{
if (!$source instanceof Source) {
@trigger_error(sprintf('Passing a string as the $source
argument of %s() is deprecated since version 1.27. Pass a Twig\Source
instance instead.', __METHOD__), E_USER_DEPRECATED);
$source = new Source($source, $name);
}
if (null === $this->lexer) {
$this->lexer = new Lexer($this);
}
return $this->lexer->tokenize($source);
}
/**
* Gets the Parser instance.
*
* @return \Twig_ParserInterface
*
* @deprecated since 1.25 (to be removed in 2.0)
*/
public function getParser()
{
@trigger_error(sprintf('The %s() method is deprecated since
version 1.25 and will be removed in 2.0.', __FUNCTION__),
E_USER_DEPRECATED);
if (null === $this->parser) {
$this->parser = new Parser($this);
}
return $this->parser;
}
public function setParser(\Twig_ParserInterface $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);
}
/**
* Gets the Compiler instance.
*
* @return \Twig_CompilerInterface
*
* @deprecated since 1.25 (to be removed in 2.0)
*/
public function getCompiler()
{
@trigger_error(sprintf('The %s() method is deprecated since
version 1.25 and will be removed in 2.0.', __FUNCTION__),
E_USER_DEPRECATED);
if (null === $this->compiler) {
$this->compiler = new Compiler($this);
}
return $this->compiler;
}
public function setCompiler(\Twig_CompilerInterface $compiler)
{
$this->compiler = $compiler;
}
/**
* Compiles a node and returns the PHP code.
*
* @return string The compiled PHP source code
*/
public function compile(\Twig_NodeInterface $node)
{
if (null === $this->compiler) {
$this->compiler = new Compiler($this);
}
return $this->compiler->compile($node)->getSource();
}
/**
* Compiles a template source code.
*
* @param string|Source $source The template source code
* @param string $name The template name (deprecated)
*
* @return string The compiled PHP source code
*
* @throws SyntaxError When there was an error during tokenizing,
parsing or compiling
*/
public function compileSource($source, $name = null)
{
if (!$source instanceof Source) {
@trigger_error(sprintf('Passing a string as the $source
argument of %s() is deprecated since version 1.27. Pass a Twig\Source
instance instead.', __METHOD__), E_USER_DEPRECATED);
$source = new Source($source, $name);
}
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)
{
if (!$loader instanceof SourceContextLoaderInterface && 0
!== strpos(\get_class($loader), 'Mock_')) {
@trigger_error(sprintf('Twig loader "%s" should
implement Twig\Loader\SourceContextLoaderInterface since version
1.27.', \get_class($loader)), E_USER_DEPRECATED);
}
$this->loader = $loader;
}
/**
* Gets the Loader instance.
*
* @return LoaderInterface
*/
public function getLoader()
{
if (null === $this->loader) {
throw new \LogicException('You must set a loader
first.');
}
return $this->loader;
}
/**
* Sets the default template charset.
*
* @param string $charset The default charset
*/
public function setCharset($charset)
{
$this->charset = strtoupper($charset);
}
/**
* Gets the default template charset.
*
* @return string The default charset
*/
public function getCharset()
{
return $this->charset;
}
/**
* Initializes the runtime environment.
*
* @deprecated since 1.23 (to be removed in 2.0)
*/
public function initRuntime()
{
$this->runtimeInitialized = true;
foreach ($this->getExtensions() as $name => $extension) {
if (!$extension instanceof InitRuntimeInterface) {
$m = new \ReflectionMethod($extension,
'initRuntime');
$parentClass = $m->getDeclaringClass()->getName();
if ('Twig_Extension' !== $parentClass &&
'Twig\Extension\AbstractExtension' !== $parentClass) {
@trigger_error(sprintf('Defining the initRuntime()
method in the "%s" extension is deprecated since version 1.23.
Use the `needs_environment` option to get the \Twig_Environment instance in
filters, functions, or tests; or explicitly implement
Twig\Extension\InitRuntimeInterface if needed (not recommended).',
$name), E_USER_DEPRECATED);
}
}
$extension->initRuntime($this);
}
}
/**
* Returns true if the given extension is registered.
*
* @param string $class The extension class name
*
* @return bool Whether the extension is registered or not
*/
public function hasExtension($class)
{
$class = ltrim($class, '\\');
if (!isset($this->extensionsByClass[$class]) &&
class_exists($class, false)) {
// For BC/FC with namespaced aliases
$class = new \ReflectionClass($class);
$class = $class->name;
}
if (isset($this->extensions[$class])) {
if ($class !== \get_class($this->extensions[$class])) {
@trigger_error(sprintf('Referencing the "%s"
extension by its name (defined by getName()) is deprecated since 1.26 and
will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name
instead.', $class), E_USER_DEPRECATED);
}
return true;
}
return isset($this->extensionsByClass[$class]);
}
/**
* Adds a runtime loader.
*/
public function addRuntimeLoader(RuntimeLoaderInterface $loader)
{
$this->runtimeLoaders[] = $loader;
}
/**
* Gets an extension by class name.
*
* @param string $class The extension class name
*
* @return ExtensionInterface
*/
public function getExtension($class)
{
$class = ltrim($class, '\\');
if (!isset($this->extensionsByClass[$class]) &&
class_exists($class, false)) {
// For BC/FC with namespaced aliases
$class = new \ReflectionClass($class);
$class = $class->name;
}
if (isset($this->extensions[$class])) {
if ($class !== \get_class($this->extensions[$class])) {
@trigger_error(sprintf('Referencing the "%s"
extension by its name (defined by getName()) is deprecated since 1.26 and
will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name
instead.', $class), E_USER_DEPRECATED);
}
return $this->extensions[$class];
}
if (!isset($this->extensionsByClass[$class])) {
throw new RuntimeError(sprintf('The "%s"
extension is not enabled.', $class));
}
return $this->extensionsByClass[$class];
}
/**
* Returns the runtime implementation of a Twig element
(filter/function/test).
*
* @param string $class A runtime class name
*
* @return object The runtime implementation
*
* @throws 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)
{
if ($this->extensionInitialized) {
throw new \LogicException(sprintf('Unable to register
extension "%s" as extensions have already been
initialized.', $extension->getName()));
}
$class = \get_class($extension);
if ($class !== $extension->getName()) {
if (isset($this->extensions[$extension->getName()])) {
unset($this->extensions[$extension->getName()],
$this->extensionsByClass[$class]);
@trigger_error(sprintf('The possibility to register
the same extension twice ("%s") is deprecated since version 1.23
and will be removed in Twig 2.0. Use proper PHP inheritance instead.',
$extension->getName()), E_USER_DEPRECATED);
}
}
$this->lastModifiedExtension = 0;
$this->extensionsByClass[$class] = $extension;
$this->extensions[$extension->getName()] = $extension;
$this->updateOptionsHash();
}
/**
* Removes an extension by name.
*
* This method is deprecated and you should not use it.
*
* @param string $name The extension name
*
* @deprecated since 1.12 (to be removed in 2.0)
*/
public function removeExtension($name)
{
@trigger_error(sprintf('The %s method is deprecated since
version 1.12 and will be removed in Twig 2.0.', __METHOD__),
E_USER_DEPRECATED);
if ($this->extensionInitialized) {
throw new \LogicException(sprintf('Unable to remove
extension "%s" as extensions have already been
initialized.', $name));
}
$class = ltrim($name, '\\');
if (!isset($this->extensionsByClass[$class]) &&
class_exists($class, false)) {
// For BC/FC with namespaced aliases
$class = new \ReflectionClass($class);
$class = $class->name;
}
if (isset($this->extensions[$class])) {
if ($class !== \get_class($this->extensions[$class])) {
@trigger_error(sprintf('Referencing the "%s"
extension by its name (defined by getName()) is deprecated since 1.26 and
will be removed in Twig 2.0. Use the Fully Qualified Extension Class Name
instead.', $class), E_USER_DEPRECATED);
}
unset($this->extensions[$class]);
}
unset($this->extensions[$class]);
$this->updateOptionsHash();
}
/**
* Registers an array of extensions.
*
* @param array $extensions An array of extensions
*/
public function setExtensions(array $extensions)
{
foreach ($extensions as $extension) {
$this->addExtension($extension);
}
}
/**
* Returns all registered extensions.
*
* @return ExtensionInterface[] An array of extensions (keys are for
internal usage only and should not be relied on)
*/
public function getExtensions()
{
return $this->extensions;
}
public function addTokenParser(TokenParserInterface $parser)
{
if ($this->extensionInitialized) {
throw new \LogicException('Unable to add a token parser as
extensions have already been initialized.');
}
$this->staging->addTokenParser($parser);
}
/**
* Gets the registered Token Parsers.
*
* @return \Twig_TokenParserBrokerInterface
*
* @internal
*/
public function getTokenParsers()
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
return $this->parsers;
}
/**
* Gets registered tags.
*
* Be warned that this method cannot return tags defined by
\Twig_TokenParserBrokerInterface classes.
*
* @return TokenParserInterface[]
*
* @internal
*/
public function getTags()
{
$tags = [];
foreach ($this->getTokenParsers()->getParsers() as $parser) {
if ($parser instanceof TokenParserInterface) {
$tags[$parser->getTag()] = $parser;
}
}
return $tags;
}
public function addNodeVisitor(NodeVisitorInterface $visitor)
{
if ($this->extensionInitialized) {
throw new \LogicException('Unable to add a node visitor as
extensions have already been initialized.');
}
$this->staging->addNodeVisitor($visitor);
}
/**
* Gets the registered Node Visitors.
*
* @return NodeVisitorInterface[]
*
* @internal
*/
public function getNodeVisitors()
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
return $this->visitors;
}
/**
* Registers a Filter.
*
* @param string|TwigFilter $name The filter name or a
\Twig_SimpleFilter instance
* @param \Twig_FilterInterface|TwigFilter $filter
*/
public function addFilter($name, $filter = null)
{
if (!$name instanceof TwigFilter && !($filter instanceof
TwigFilter || $filter instanceof \Twig_FilterInterface)) {
throw new \LogicException('A filter must be an instance of
\Twig_FilterInterface or \Twig_SimpleFilter.');
}
if ($name instanceof TwigFilter) {
$filter = $name;
$name = $filter->getName();
} else {
@trigger_error(sprintf('Passing a name as a first argument
to the %s method is deprecated since version 1.21. Pass an instance of
"Twig_SimpleFilter" instead when defining filter
"%s".', __METHOD__, $name), E_USER_DEPRECATED);
}
if ($this->extensionInitialized) {
throw new \LogicException(sprintf('Unable to add filter
"%s" as extensions have already been initialized.', $name));
}
$this->staging->addFilter($name, $filter);
}
/**
* Get a filter by name.
*
* Subclasses may override this method and load filters differently;
* so no list of filters is available.
*
* @param string $name The filter name
*
* @return \Twig_Filter|false
*
* @internal
*/
public function getFilter($name)
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
if (isset($this->filters[$name])) {
return $this->filters[$name];
}
foreach ($this->filters as $pattern => $filter) {
$pattern = str_replace('\\*', '(.*?)',
preg_quote($pattern, '#'), $count);
if ($count) {
if (preg_match('#^'.$pattern.'$#',
$name, $matches)) {
array_shift($matches);
$filter->setArguments($matches);
return $filter;
}
}
}
foreach ($this->filterCallbacks as $callback) {
if (false !== $filter = \call_user_func($callback, $name)) {
return $filter;
}
}
return false;
}
public function registerUndefinedFilterCallback($callable)
{
$this->filterCallbacks[] = $callable;
}
/**
* Gets the registered Filters.
*
* Be warned that this method cannot return filters defined with
registerUndefinedFilterCallback.
*
* @return \Twig_FilterInterface[]
*
* @see registerUndefinedFilterCallback
*
* @internal
*/
public function getFilters()
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
return $this->filters;
}
/**
* Registers a Test.
*
* @param string|TwigTest $name The test name or a
\Twig_SimpleTest instance
* @param \Twig_TestInterface|TwigTest $test A \Twig_TestInterface
instance or a \Twig_SimpleTest instance
*/
public function addTest($name, $test = null)
{
if (!$name instanceof TwigTest && !($test instanceof
TwigTest || $test instanceof \Twig_TestInterface)) {
throw new \LogicException('A test must be an instance of
\Twig_TestInterface or \Twig_SimpleTest.');
}
if ($name instanceof TwigTest) {
$test = $name;
$name = $test->getName();
} else {
@trigger_error(sprintf('Passing a name as a first argument
to the %s method is deprecated since version 1.21. Pass an instance of
"Twig_SimpleTest" instead when defining test
"%s".', __METHOD__, $name), E_USER_DEPRECATED);
}
if ($this->extensionInitialized) {
throw new \LogicException(sprintf('Unable to add test
"%s" as extensions have already been initialized.', $name));
}
$this->staging->addTest($name, $test);
}
/**
* Gets the registered Tests.
*
* @return \Twig_TestInterface[]
*
* @internal
*/
public function getTests()
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
return $this->tests;
}
/**
* Gets a test by name.
*
* @param string $name The test name
*
* @return \Twig_Test|false
*
* @internal
*/
public function getTest($name)
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
if (isset($this->tests[$name])) {
return $this->tests[$name];
}
foreach ($this->tests as $pattern => $test) {
$pattern = str_replace('\\*', '(.*?)',
preg_quote($pattern, '#'), $count);
if ($count) {
if (preg_match('#^'.$pattern.'$#',
$name, $matches)) {
array_shift($matches);
$test->setArguments($matches);
return $test;
}
}
}
return false;
}
/**
* Registers a Function.
*
* @param string|TwigFunction $name The function
name or a \Twig_SimpleFunction instance
* @param \Twig_FunctionInterface|TwigFunction $function
*/
public function addFunction($name, $function = null)
{
if (!$name instanceof TwigFunction && !($function
instanceof TwigFunction || $function instanceof \Twig_FunctionInterface)) {
throw new \LogicException('A function must be an instance
of \Twig_FunctionInterface or \Twig_SimpleFunction.');
}
if ($name instanceof TwigFunction) {
$function = $name;
$name = $function->getName();
} else {
@trigger_error(sprintf('Passing a name as a first argument
to the %s method is deprecated since version 1.21. Pass an instance of
"Twig_SimpleFunction" instead when defining function
"%s".', __METHOD__, $name), E_USER_DEPRECATED);
}
if ($this->extensionInitialized) {
throw new \LogicException(sprintf('Unable to add function
"%s" as extensions have already been initialized.', $name));
}
$this->staging->addFunction($name, $function);
}
/**
* Get a function by name.
*
* Subclasses may override this method and load functions differently;
* so no list of functions is available.
*
* @param string $name function name
*
* @return \Twig_Function|false
*
* @internal
*/
public function getFunction($name)
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
if (isset($this->functions[$name])) {
return $this->functions[$name];
}
foreach ($this->functions as $pattern => $function) {
$pattern = str_replace('\\*', '(.*?)',
preg_quote($pattern, '#'), $count);
if ($count) {
if (preg_match('#^'.$pattern.'$#',
$name, $matches)) {
array_shift($matches);
$function->setArguments($matches);
return $function;
}
}
}
foreach ($this->functionCallbacks as $callback) {
if (false !== $function = \call_user_func($callback, $name)) {
return $function;
}
}
return false;
}
public function registerUndefinedFunctionCallback($callable)
{
$this->functionCallbacks[] = $callable;
}
/**
* Gets registered functions.
*
* Be warned that this method cannot return functions defined with
registerUndefinedFunctionCallback.
*
* @return \Twig_FunctionInterface[]
*
* @see registerUndefinedFunctionCallback
*
* @internal
*/
public function getFunctions()
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
return $this->functions;
}
/**
* Registers a Global.
*
* New globals can be added before compiling or rendering a template;
* but after, you can only update existing globals.
*
* @param string $name The global name
* @param mixed $value The global value
*/
public function addGlobal($name, $value)
{
if ($this->extensionInitialized || $this->runtimeInitialized)
{
if (null === $this->globals) {
$this->globals = $this->initGlobals();
}
if (!\array_key_exists($name, $this->globals)) {
// The deprecation notice must be turned into the following
exception in Twig 2.0
@trigger_error(sprintf('Registering global variable
"%s" at runtime or when the extensions have already been
initialized is deprecated since version 1.21.', $name),
E_USER_DEPRECATED);
//throw new \LogicException(sprintf('Unable to add
global "%s" as the runtime or the extensions have already been
initialized.', $name));
}
}
if ($this->extensionInitialized || $this->runtimeInitialized)
{
// update the value
$this->globals[$name] = $value;
} else {
$this->staging->addGlobal($name, $value);
}
}
/**
* Gets the registered Globals.
*
* @return array An array of globals
*
* @internal
*/
public function getGlobals()
{
if (!$this->runtimeInitialized &&
!$this->extensionInitialized) {
return $this->initGlobals();
}
if (null === $this->globals) {
$this->globals = $this->initGlobals();
}
return $this->globals;
}
/**
* Merges a context with the defined globals.
*
* @param array $context An array representing the context
*
* @return array The context merged with the globals
*/
public function mergeGlobals(array $context)
{
// we don't use array_merge as the context being generally
// bigger than globals, this code is faster.
foreach ($this->getGlobals() as $key => $value) {
if (!\array_key_exists($key, $context)) {
$context[$key] = $value;
}
}
return $context;
}
/**
* Gets the registered unary Operators.
*
* @return array An array of unary operators
*
* @internal
*/
public function getUnaryOperators()
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
return $this->unaryOperators;
}
/**
* Gets the registered binary Operators.
*
* @return array An array of binary operators
*
* @internal
*/
public function getBinaryOperators()
{
if (!$this->extensionInitialized) {
$this->initExtensions();
}
return $this->binaryOperators;
}
/**
* @deprecated since 1.23 (to be removed in 2.0)
*/
public function computeAlternatives($name, $items)
{
@trigger_error(sprintf('The %s method is deprecated since
version 1.23 and will be removed in Twig 2.0.', __METHOD__),
E_USER_DEPRECATED);
return SyntaxError::computeAlternatives($name, $items);
}
/**
* @internal
*/
protected function initGlobals()
{
$globals = [];
foreach ($this->extensions as $name => $extension) {
if (!$extension instanceof GlobalsInterface) {
$m = new \ReflectionMethod($extension,
'getGlobals');
$parentClass = $m->getDeclaringClass()->getName();
if ('Twig_Extension' !== $parentClass &&
'Twig\Extension\AbstractExtension' !== $parentClass) {
@trigger_error(sprintf('Defining the getGlobals()
method in the "%s" extension without explicitly implementing
Twig\Extension\GlobalsInterface is deprecated since version 1.23.',
$name), E_USER_DEPRECATED);
}
}
$extGlob = $extension->getGlobals();
if (!\is_array($extGlob)) {
throw new
\UnexpectedValueException(sprintf('"%s::getGlobals()" must
return an array of globals.', \get_class($extension)));
}
$globals[] = $extGlob;
}
$globals[] = $this->staging->getGlobals();
return \call_user_func_array('array_merge', $globals);
}
/**
* @internal
*/
protected function initExtensions()
{
if ($this->extensionInitialized) {
return;
}
$this->parsers = new \Twig_TokenParserBroker([], [], false);
$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->extensionInitialized = true;
}
/**
* @internal
*/
protected function initExtension(ExtensionInterface $extension)
{
// filters
foreach ($extension->getFilters() as $name => $filter) {
if ($filter instanceof TwigFilter) {
$name = $filter->getName();
} else {
@trigger_error(sprintf('Using an instance of
"%s" for filter "%s" is deprecated since version 1.21.
Use \Twig_SimpleFilter instead.', \get_class($filter), $name),
E_USER_DEPRECATED);
}
$this->filters[$name] = $filter;
}
// functions
foreach ($extension->getFunctions() as $name => $function) {
if ($function instanceof TwigFunction) {
$name = $function->getName();
} else {
@trigger_error(sprintf('Using an instance of
"%s" for function "%s" is deprecated since version
1.21. Use \Twig_SimpleFunction instead.', \get_class($function),
$name), E_USER_DEPRECATED);
}
$this->functions[$name] = $function;
}
// tests
foreach ($extension->getTests() as $name => $test) {
if ($test instanceof TwigTest) {
$name = $test->getName();
} else {
@trigger_error(sprintf('Using an instance of
"%s" for test "%s" is deprecated since version 1.21.
Use \Twig_SimpleTest instead.', \get_class($test), $name),
E_USER_DEPRECATED);
}
$this->tests[$name] = $test;
}
// token parsers
foreach ($extension->getTokenParsers() as $parser) {
if ($parser instanceof TokenParserInterface) {
$this->parsers->addTokenParser($parser);
} elseif ($parser instanceof \Twig_TokenParserBrokerInterface)
{
@trigger_error('Registering a
\Twig_TokenParserBrokerInterface instance is deprecated since version
1.21.', E_USER_DEPRECATED);
$this->parsers->addTokenParserBroker($parser);
} else {
throw new \LogicException('getTokenParsers() must
return an array of \Twig_TokenParserInterface or
\Twig_TokenParserBrokerInterface instances.');
}
}
// node visitors
foreach ($extension->getNodeVisitors() as $visitor) {
$this->visitors[] = $visitor;
}
// operators
if ($operators = $extension->getOperators()) {
if (!\is_array($operators)) {
throw new
\InvalidArgumentException(sprintf('"%s::getOperators()" must
return an array with operators, got "%s".',
\get_class($extension), \is_object($operators) ? \get_class($operators) :
\gettype($operators).(\is_resource($operators) ? '' :
'#'.$operators)));
}
if (2 !== \count($operators)) {
throw new
\InvalidArgumentException(sprintf('"%s::getOperators()" must
return an array of 2 elements, got %d.', \get_class($extension),
\count($operators)));
}
$this->unaryOperators =
array_merge($this->unaryOperators, $operators[0]);
$this->binaryOperators =
array_merge($this->binaryOperators, $operators[1]);
}
}
/**
* @deprecated since 1.22 (to be removed in 2.0)
*/
protected function writeCacheFile($file, $content)
{
$this->cache->write($file, $content);
}
private function updateOptionsHash()
{
$hashParts = array_merge(
array_keys($this->extensions),
[
(int)
\function_exists('twig_template_get_attributes'),
PHP_MAJOR_VERSION,
PHP_MINOR_VERSION,
self::VERSION,
(int) $this->debug,
$this->baseTemplateClass,
(int) $this->strictVariables,
]
);
$this->optionsHash = implode(':', $hashParts);
}
}
class_alias('Twig\Environment', 'Twig_Environment');
twig/src/Error/Error.php000064400000023330151161070030011173
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
use Twig\Source;
use Twig\Template;
/**
* Twig base exception.
*
* This exception class and its children must only be used when
* an error occurs during the loading of a template, when a syntax error
* is detected in a template, or when rendering a template. Other
* errors must use regular PHP exception classes (like when the template
* cache directory is not writable for instance).
*
* To help debugging template issues, this class tracks the original
template
* name and line where the error occurred.
*
* Whenever possible, you must set these information (original template
name
* and line number) yourself by passing them to the constructor. If some or
all
* these information are not available from where you throw the exception,
then
* this class will guess them automatically (when the line number is set to
-1
* and/or the name is set to null). As this is a costly operation, this
* can be disabled by passing false for both the name and the line number
* when creating a new instance of this class.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Error extends \Exception
{
protected $lineno;
// to be renamed to name in 2.0
protected $filename;
protected $rawMessage;
private $sourcePath;
private $sourceCode;
/**
* Constructor.
*
* Set the line number to -1 to enable its automatic guessing.
* Set the name to null to enable its automatic guessing.
*
* @param string $message The error message
* @param int $lineno The template line where the
error occurred
* @param Source|string|null $source The source context where the
error occurred
* @param \Exception $previous The previous exception
*/
public function __construct($message, $lineno = -1, $source = null,
\Exception $previous = null)
{
if (null === $source) {
$name = null;
} elseif (!$source instanceof Source) {
// for compat with the Twig C ext., passing the template name
as string is accepted
$name = $source;
} else {
$name = $source->getName();
$this->sourceCode = $source->getCode();
$this->sourcePath = $source->getPath();
}
parent::__construct('', 0, $previous);
$this->lineno = $lineno;
$this->filename = $name;
$this->rawMessage = $message;
$this->updateRepr();
}
/**
* Gets the raw message.
*
* @return string The raw message
*/
public function getRawMessage()
{
return $this->rawMessage;
}
/**
* Gets the logical name where the error occurred.
*
* @return string The name
*
* @deprecated since 1.27 (to be removed in 2.0). Use
getSourceContext() instead.
*/
public function getTemplateFile()
{
@trigger_error(sprintf('The "%s" method is
deprecated since version 1.27 and will be removed in 2.0. Use
getSourceContext() instead.', __METHOD__), E_USER_DEPRECATED);
return $this->filename;
}
/**
* Sets the logical name where the error occurred.
*
* @param string $name The name
*
* @deprecated since 1.27 (to be removed in 2.0). Use
setSourceContext() instead.
*/
public function setTemplateFile($name)
{
@trigger_error(sprintf('The "%s" method is
deprecated since version 1.27 and will be removed in 2.0. Use
setSourceContext() instead.', __METHOD__), E_USER_DEPRECATED);
$this->filename = $name;
$this->updateRepr();
}
/**
* Gets the logical name where the error occurred.
*
* @return string The name
*
* @deprecated since 1.29 (to be removed in 2.0). Use
getSourceContext() instead.
*/
public function getTemplateName()
{
@trigger_error(sprintf('The "%s" method is
deprecated since version 1.29 and will be removed in 2.0. Use
getSourceContext() instead.', __METHOD__), E_USER_DEPRECATED);
return $this->filename;
}
/**
* Sets the logical name where the error occurred.
*
* @param string $name The name
*
* @deprecated since 1.29 (to be removed in 2.0). Use
setSourceContext() instead.
*/
public function setTemplateName($name)
{
@trigger_error(sprintf('The "%s" method is
deprecated since version 1.29 and will be removed in 2.0. Use
setSourceContext() instead.', __METHOD__), E_USER_DEPRECATED);
$this->filename = $name;
$this->sourceCode = $this->sourcePath = null;
$this->updateRepr();
}
/**
* Gets the template line where the error occurred.
*
* @return int The template line
*/
public function getTemplateLine()
{
return $this->lineno;
}
/**
* Sets the template line where the error occurred.
*
* @param int $lineno The template line
*/
public function setTemplateLine($lineno)
{
$this->lineno = $lineno;
$this->updateRepr();
}
/**
* Gets the source context of the Twig template where the error
occurred.
*
* @return Source|null
*/
public function getSourceContext()
{
return $this->filename ? new Source($this->sourceCode,
$this->filename, $this->sourcePath) : null;
}
/**
* Sets the source context of the Twig template where the error
occurred.
*/
public function setSourceContext(Source $source = null)
{
if (null === $source) {
$this->sourceCode = $this->filename =
$this->sourcePath = null;
} else {
$this->sourceCode = $source->getCode();
$this->filename = $source->getName();
$this->sourcePath = $source->getPath();
}
$this->updateRepr();
}
public function guess()
{
$this->guessTemplateInfo();
$this->updateRepr();
}
public function appendMessage($rawMessage)
{
$this->rawMessage .= $rawMessage;
$this->updateRepr();
}
/**
* @internal
*/
protected function updateRepr()
{
$this->message = $this->rawMessage;
if ($this->sourcePath && $this->lineno > 0) {
$this->file = $this->sourcePath;
$this->line = $this->lineno;
return;
}
$dot = false;
if ('.' === substr($this->message, -1)) {
$this->message = substr($this->message, 0, -1);
$dot = true;
}
$questionMark = false;
if ('?' === substr($this->message, -1)) {
$this->message = substr($this->message, 0, -1);
$questionMark = true;
}
if ($this->filename) {
if (\is_string($this->filename) ||
(\is_object($this->filename) &&
method_exists($this->filename, '__toString'))) {
$name = sprintf('"%s"',
$this->filename);
} else {
$name = json_encode($this->filename);
}
$this->message .= sprintf(' in %s', $name);
}
if ($this->lineno && $this->lineno >= 0) {
$this->message .= sprintf(' at line %d',
$this->lineno);
}
if ($dot) {
$this->message .= '.';
}
if ($questionMark) {
$this->message .= '?';
}
}
/**
* @internal
*/
protected function guessTemplateInfo()
{
$template = null;
$templateClass = null;
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS |
DEBUG_BACKTRACE_PROVIDE_OBJECT);
foreach ($backtrace as $trace) {
if (isset($trace['object']) &&
$trace['object'] instanceof Template &&
'Twig_Template' !== \get_class($trace['object'])) {
$currentClass = \get_class($trace['object']);
$isEmbedContainer = 0 === strpos($templateClass,
$currentClass);
if (null === $this->filename || ($this->filename ==
$trace['object']->getTemplateName() &&
!$isEmbedContainer)) {
$template = $trace['object'];
$templateClass =
\get_class($trace['object']);
}
}
}
// update template name
if (null !== $template && null === $this->filename) {
$this->filename = $template->getTemplateName();
}
// update template path if any
if (null !== $template && null === $this->sourcePath) {
$src = $template->getSourceContext();
$this->sourceCode = $src->getCode();
$this->sourcePath = $src->getPath();
}
if (null === $template || $this->lineno > -1) {
return;
}
$r = new \ReflectionObject($template);
$file = $r->getFileName();
$exceptions = [$e = $this];
while ($e instanceof self && $e = $e->getPrevious()) {
$exceptions[] = $e;
}
while ($e = array_pop($exceptions)) {
$traces = $e->getTrace();
array_unshift($traces, ['file' =>
$e->getFile(), 'line' => $e->getLine()]);
while ($trace = array_shift($traces)) {
if (!isset($trace['file']) ||
!isset($trace['line']) || $file != $trace['file']) {
continue;
}
foreach ($template->getDebugInfo() as $codeLine =>
$templateLine) {
if ($codeLine <= $trace['line']) {
// update template line
$this->lineno = $templateLine;
return;
}
}
}
}
}
}
class_alias('Twig\Error\Error', 'Twig_Error');
twig/src/Error/LoaderError.php000064400000000700151161070030012316
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
/**
* Exception thrown when an error occurs during template loading.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class LoaderError extends Error
{
}
class_alias('Twig\Error\LoaderError',
'Twig_Error_Loader');
twig/src/Error/RuntimeError.php000064400000000714151161070030012540
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
/**
* Exception thrown when an error occurs at runtime.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RuntimeError extends Error
{
}
class_alias('Twig\Error\RuntimeError',
'Twig_Error_Runtime');
twig/src/Error/SyntaxError.php000064400000002706151161070030012406
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Error;
/**
* \Exception thrown when a syntax error occurs during lexing or parsing of
a template.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SyntaxError extends Error
{
/**
* Tweaks the error message to include suggestions.
*
* @param string $name The original name of the item that does not
exist
* @param array $items An array of possible items
*/
public function addSuggestions($name, array $items)
{
if (!$alternatives = self::computeAlternatives($name, $items)) {
return;
}
$this->appendMessage(sprintf(' Did you mean
"%s"?', implode('", "',
$alternatives)));
}
/**
* @internal
*
* To be merged with the addSuggestions() method in 2.0.
*/
public static function computeAlternatives($name, $items)
{
$alternatives = [];
foreach ($items as $item) {
$lev = levenshtein($name, $item);
if ($lev <= \strlen($name) / 3 || false !== strpos($item,
$name)) {
$alternatives[$item] = $lev;
}
}
asort($alternatives);
return array_keys($alternatives);
}
}
class_alias('Twig\Error\SyntaxError',
'Twig_Error_Syntax');
twig/src/ExpressionParser.php000064400000077767151161070030012354
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
use Twig\Node\Expression\ArrayExpression;
use Twig\Node\Expression\ArrowFunctionExpression;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\Expression\Binary\ConcatBinary;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\MethodCallExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\ParentExpression;
use Twig\Node\Expression\Unary\NegUnary;
use Twig\Node\Expression\Unary\NotUnary;
use Twig\Node\Expression\Unary\PosUnary;
use Twig\Node\Node;
/**
* Parses expressions.
*
* This parser implements a "Precedence climbing" algorithm.
*
* @see https://www.engr.mun.ca/~theo/Misc/exp_parsing.htm
* @see https://en.wikipedia.org/wiki/Operator-precedence_parser
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @internal
*/
class ExpressionParser
{
const OPERATOR_LEFT = 1;
const OPERATOR_RIGHT = 2;
protected $parser;
protected $unaryOperators;
protected $binaryOperators;
private $env;
public function __construct(Parser $parser, $env = null)
{
$this->parser = $parser;
if ($env instanceof Environment) {
$this->env = $env;
$this->unaryOperators = $env->getUnaryOperators();
$this->binaryOperators = $env->getBinaryOperators();
} else {
@trigger_error('Passing the operators as constructor
arguments to '.__METHOD__.' is deprecated since version 1.27.
Pass the environment instead.', E_USER_DEPRECATED);
$this->env = $parser->getEnvironment();
$this->unaryOperators = func_get_arg(1);
$this->binaryOperators = func_get_arg(2);
}
}
public function parseExpression($precedence = 0, $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 = \call_user_func($op['callable'],
$this->parser, $expr);
} else {
$expr1 = $this->parseExpression(self::OPERATOR_LEFT ===
$op['associativity'] ? $op['precedence'] + 1 :
$op['precedence']);
$class = $op['class'];
$expr = new $class($expr, $expr1, $token->getLine());
}
$token = $this->parser->getCurrentToken();
}
if (0 === $precedence) {
return $this->parseConditionalExpression($expr);
}
return $expr;
}
/**
* @return ArrowFunctionExpression|null
*/
private function parseArrow()
{
$stream = $this->parser->getStream();
// short array syntax (one argument, no parentheses)?
if ($stream->look(1)->test(Token::ARROW_TYPE)) {
$line = $stream->getCurrent()->getLine();
$token = $stream->expect(Token::NAME_TYPE);
$names = [new AssignNameExpression($token->getValue(),
$token->getLine())];
$stream->expect(Token::ARROW_TYPE);
return new
ArrowFunctionExpression($this->parseExpression(0), new Node($names),
$line);
}
// first, determine if we are parsing an arrow function by finding
=> (long form)
$i = 0;
if (!$stream->look($i)->test(Token::PUNCTUATION_TYPE,
'(')) {
return null;
}
++$i;
while (true) {
// variable name
++$i;
if (!$stream->look($i)->test(Token::PUNCTUATION_TYPE,
',')) {
break;
}
++$i;
}
if (!$stream->look($i)->test(Token::PUNCTUATION_TYPE,
')')) {
return null;
}
++$i;
if (!$stream->look($i)->test(Token::ARROW_TYPE)) {
return null;
}
// yes, let's parse it properly
$token = $stream->expect(Token::PUNCTUATION_TYPE,
'(');
$line = $token->getLine();
$names = [];
while (true) {
$token = $stream->expect(Token::NAME_TYPE);
$names[] = new AssignNameExpression($token->getValue(),
$token->getLine());
if (!$stream->nextIf(Token::PUNCTUATION_TYPE,
',')) {
break;
}
}
$stream->expect(Token::PUNCTUATION_TYPE, ')');
$stream->expect(Token::ARROW_TYPE);
return new ArrowFunctionExpression($this->parseExpression(0),
new Node($names), $line);
}
protected function getPrimary()
{
$token = $this->parser->getCurrentToken();
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, '('))
{
$this->parser->getStream()->next();
$expr = $this->parseExpression();
$this->parser->getStream()->expect(Token::PUNCTUATION_TYPE,
')', 'An opened parenthesis is not properly closed');
return $this->parsePostfixExpression($expr);
}
return $this->parsePrimaryExpression();
}
protected function parseConditionalExpression($expr)
{
while
($this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE,
'?')) {
if
(!$this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE,
':')) {
$expr2 = $this->parseExpression();
if
($this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE,
':')) {
$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;
}
protected function isUnary(Token $token)
{
return $token->test(Token::OPERATOR_TYPE) &&
isset($this->unaryOperators[$token->getValue()]);
}
protected function isBinary(Token $token)
{
return $token->test(Token::OPERATOR_TYPE) &&
isset($this->binaryOperators[$token->getValue()]);
}
public function parsePrimaryExpression()
{
$token = $this->parser->getCurrentToken();
switch ($token->getType()) {
case Token::NAME_TYPE:
$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:
$this->parser->getStream()->next();
$node = new ConstantExpression($token->getValue(),
$token->getLine());
break;
case Token::STRING_TYPE:
case Token::INTERPOLATION_START_TYPE:
$node = $this->parseStringExpression();
break;
case Token::OPERATOR_TYPE:
if (preg_match(Lexer::REGEX_NAME, $token->getValue(),
$matches) && $matches[0] == $token->getValue()) {
// 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);
$negClass =
'Twig\Node\Expression\Unary\NegUnary';
$posClass =
'Twig\Node\Expression\Unary\PosUnary';
if (!(\in_array($ref->getName(), [$negClass,
$posClass, 'Twig_Node_Expression_Unary_Neg',
'Twig_Node_Expression_Unary_Pos'])
|| $ref->isSubclassOf($negClass) ||
$ref->isSubclassOf($posClass)
||
$ref->isSubclassOf('Twig_Node_Expression_Unary_Neg') ||
$ref->isSubclassOf('Twig_Node_Expression_Unary_Pos'))
) {
throw new SyntaxError(sprintf('Unexpected
unary operator "%s".', $token->getValue()),
$token->getLine(),
$this->parser->getStream()->getSourceContext());
}
$this->parser->getStream()->next();
$expr = $this->parsePrimaryExpression();
$node = new $class($expr, $token->getLine());
break;
}
// no break
default:
if ($token->test(Token::PUNCTUATION_TYPE,
'[')) {
$node = $this->parseArrayExpression();
} elseif ($token->test(Token::PUNCTUATION_TYPE,
'{')) {
$node = $this->parseHashExpression();
} elseif ($token->test(Token::OPERATOR_TYPE,
'=') && ('==' ===
$this->parser->getStream()->look(-1)->getValue() ||
'!=' ===
$this->parser->getStream()->look(-1)->getValue())) {
throw new SyntaxError(sprintf('Unexpected operator
of value "%s". Did you try to use "===" or
"!==" for strict comparison? Use "is same as(value)"
instead.', $token->getValue()), $token->getLine(),
$this->parser->getStream()->getSourceContext());
} else {
throw new SyntaxError(sprintf('Unexpected token
"%s" of value "%s".',
Token::typeToEnglish($token->getType()), $token->getValue()),
$token->getLine(),
$this->parser->getStream()->getSourceContext());
}
}
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)) {
$nodes[] = new ConstantExpression($token->getValue(),
$token->getLine());
$nextCanBeString = false;
} elseif ($stream->nextIf(Token::INTERPOLATION_START_TYPE))
{
$nodes[] = $this->parseExpression();
$stream->expect(Token::INTERPOLATION_END_TYPE);
$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, '[', 'An
array element was expected');
$node = new ArrayExpression([],
$stream->getCurrent()->getLine());
$first = true;
while (!$stream->test(Token::PUNCTUATION_TYPE, ']')) {
if (!$first) {
$stream->expect(Token::PUNCTUATION_TYPE, ',',
'An array element must be followed by a comma');
// trailing ,?
if ($stream->test(Token::PUNCTUATION_TYPE,
']')) {
break;
}
}
$first = false;
$node->addElement($this->parseExpression());
}
$stream->expect(Token::PUNCTUATION_TYPE, ']', 'An
opened array is not properly closed');
return $node;
}
public function parseHashExpression()
{
$stream = $this->parser->getStream();
$stream->expect(Token::PUNCTUATION_TYPE, '{', 'A
hash element was expected');
$node = new ArrayExpression([],
$stream->getCurrent()->getLine());
$first = true;
while (!$stream->test(Token::PUNCTUATION_TYPE, '}')) {
if (!$first) {
$stream->expect(Token::PUNCTUATION_TYPE, ',',
'A hash value must be followed by a comma');
// trailing ,?
if ($stream->test(Token::PUNCTUATION_TYPE,
'}')) {
break;
}
}
$first = false;
// a hash key can be:
//
// * a number -- 12
// * a string -- 'a'
// * a name, which is equivalent to a string -- a
// * an expression, which must be enclosed in parentheses --
(1 + 2)
if (($token = $stream->nextIf(Token::STRING_TYPE)) ||
($token = $stream->nextIf(Token::NAME_TYPE)) || $token =
$stream->nextIf(Token::NUMBER_TYPE)) {
$key = new ConstantExpression($token->getValue(),
$token->getLine());
} elseif ($stream->test(Token::PUNCTUATION_TYPE,
'(')) {
$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, ':',
'A hash key must be followed by a colon (:)');
$value = $this->parseExpression();
$node->addElement($value, $key);
}
$stream->expect(Token::PUNCTUATION_TYPE, '}', 'An
opened hash is not properly closed');
return $node;
}
public function parsePostfixExpression($node)
{
while (true) {
$token = $this->parser->getCurrentToken();
if (Token::PUNCTUATION_TYPE == $token->getType()) {
if ('.' == $token->getValue() || '['
== $token->getValue()) {
$node = $this->parseSubscriptExpression($node);
} elseif ('|' == $token->getValue()) {
$node = $this->parseFilterExpression($node);
} else {
break;
}
} else {
break;
}
}
return $node;
}
public function getFunctionNode($name, $line)
{
switch ($name) {
case 'parent':
$this->parseArguments();
if (!\count($this->parser->getBlockStack())) {
throw new 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 == $token->getType()
||
Token::NUMBER_TYPE == $token->getType()
||
(Token::OPERATOR_TYPE == $token->getType() &&
preg_match(Lexer::REGEX_NAME, $token->getValue()))
) {
$arg = new ConstantExpression($token->getValue(),
$lineno);
if ($stream->test(Token::PUNCTUATION_TYPE,
'(')) {
$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');
if ($this->parser->isReservedMacroName($name)) {
throw new SyntaxError(sprintf('"%s"
cannot be called as macro as it is a reserved keyword.', $name),
$token->getLine(), $stream->getSourceContext());
}
$node = new MethodCallExpression($node,
'get'.$name, $arguments, $lineno);
$node->setAttribute('safe', true);
return $node;
}
} else {
$type = Template::ARRAY_CALL;
// slice?
$slice = false;
if ($stream->test(Token::PUNCTUATION_TYPE, ':')) {
$slice = true;
$arg = new ConstantExpression(0, $token->getLine());
} else {
$arg = $this->parseExpression();
}
if ($stream->nextIf(Token::PUNCTUATION_TYPE, ':'))
{
$slice = true;
}
if ($slice) {
if ($stream->test(Token::PUNCTUATION_TYPE,
']')) {
$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, ']');
return $filter;
}
$stream->expect(Token::PUNCTUATION_TYPE, ']');
}
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);
$name = new ConstantExpression($token->getValue(),
$token->getLine());
if
(!$this->parser->getStream()->test(Token::PUNCTUATION_TYPE,
'(')) {
$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,
'|')) {
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, '(', 'A
list of arguments must begin with an opening parenthesis');
while (!$stream->test(Token::PUNCTUATION_TYPE, ')')) {
if (!empty($args)) {
$stream->expect(Token::PUNCTUATION_TYPE, ',',
'Arguments must be separated by a comma');
}
if ($definition) {
$token = $stream->expect(Token::NAME_TYPE, null,
'An argument must be a name');
$value = new NameExpression($token->getValue(),
$this->parser->getCurrentToken()->getLine());
} else {
$value = $this->parseExpression(0, $allowArrow);
}
$name = null;
if ($namedArguments && $token =
$stream->nextIf(Token::OPERATOR_TYPE, '=')) {
if (!$value instanceof NameExpression) {
throw new SyntaxError(sprintf('A parameter name
must be a string, "%s" given.', \get_class($value)),
$token->getLine(), $stream->getSourceContext());
}
$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, ')', '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) &&
preg_match(Lexer::REGEX_NAME, $token->getValue())) {
// in this context, string operators are variable names
$this->parser->getStream()->next();
} else {
$stream->expect(Token::NAME_TYPE, null, 'Only
variables can be assigned to');
}
$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,
',')) {
break;
}
}
return new Node($targets);
}
public function parseMultitargetExpression()
{
$targets = [];
while (true) {
$targets[] = $this->parseExpression();
if
(!$this->parser->getStream()->nextIf(Token::PUNCTUATION_TYPE,
',')) {
break;
}
}
return new Node($targets);
}
private function parseNotTestExpression(\Twig_NodeInterface $node)
{
return new NotUnary($this->parseTestExpression($node),
$this->parser->getCurrentToken()->getLine());
}
private function parseTestExpression(\Twig_NodeInterface $node)
{
$stream = $this->parser->getStream();
list($name, $test) =
$this->getTest($node->getTemplateLine());
$class = $this->getTestNodeClass($test);
$arguments = null;
if ($stream->test(Token::PUNCTUATION_TYPE, '(')) {
$arguments = $this->parseArguments(true);
}
return new $class($node, $name, $arguments,
$this->parser->getCurrentToken()->getLine());
}
private function getTest($line)
{
$stream = $this->parser->getStream();
$name = $stream->expect(Token::NAME_TYPE)->getValue();
if ($test = $this->env->getTest($name)) {
return [$name, $test];
}
if ($stream->test(Token::NAME_TYPE)) {
// 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($test)
{
if ($test instanceof TwigTest && $test->isDeprecated())
{
$stream = $this->parser->getStream();
$message = sprintf('Twig Test "%s" is
deprecated', $test->getName());
if (!\is_bool($test->getDeprecatedVersion())) {
$message .= sprintf(' since version %s',
$test->getDeprecatedVersion());
}
if ($test->getAlternative()) {
$message .= sprintf('. Use "%s"
instead', $test->getAlternative());
}
$src = $stream->getSourceContext();
$message .= sprintf(' in %s at line %d.',
$src->getPath() ? $src->getPath() : $src->getName(),
$stream->getCurrent()->getLine());
@trigger_error($message, E_USER_DEPRECATED);
}
if ($test instanceof TwigTest) {
return $test->getNodeClass();
}
return $test instanceof \Twig_Test_Node ? $test->getClass() :
'Twig\Node\Expression\TestExpression';
}
protected function getFunctionNodeClass($name, $line)
{
if (false === $function = $this->env->getFunction($name)) {
$e = new SyntaxError(sprintf('Unknown "%s"
function.', $name), $line,
$this->parser->getStream()->getSourceContext());
$e->addSuggestions($name,
array_keys($this->env->getFunctions()));
throw $e;
}
if ($function instanceof TwigFunction &&
$function->isDeprecated()) {
$message = sprintf('Twig Function "%s" is
deprecated', $function->getName());
if (!\is_bool($function->getDeprecatedVersion())) {
$message .= sprintf(' since version %s',
$function->getDeprecatedVersion());
}
if ($function->getAlternative()) {
$message .= sprintf('. Use "%s"
instead', $function->getAlternative());
}
$src = $this->parser->getStream()->getSourceContext();
$message .= sprintf(' in %s at line %d.',
$src->getPath() ? $src->getPath() : $src->getName(), $line);
@trigger_error($message, E_USER_DEPRECATED);
}
if ($function instanceof TwigFunction) {
return $function->getNodeClass();
}
return $function instanceof \Twig_Function_Node ?
$function->getClass() :
'Twig\Node\Expression\FunctionExpression';
}
protected function getFilterNodeClass($name, $line)
{
if (false === $filter = $this->env->getFilter($name)) {
$e = new SyntaxError(sprintf('Unknown "%s"
filter.', $name), $line,
$this->parser->getStream()->getSourceContext());
$e->addSuggestions($name,
array_keys($this->env->getFilters()));
throw $e;
}
if ($filter instanceof TwigFilter &&
$filter->isDeprecated()) {
$message = sprintf('Twig Filter "%s" is
deprecated', $filter->getName());
if (!\is_bool($filter->getDeprecatedVersion())) {
$message .= sprintf(' since version %s',
$filter->getDeprecatedVersion());
}
if ($filter->getAlternative()) {
$message .= sprintf('. Use "%s"
instead', $filter->getAlternative());
}
$src = $this->parser->getStream()->getSourceContext();
$message .= sprintf(' in %s at line %d.',
$src->getPath() ? $src->getPath() : $src->getName(), $line);
@trigger_error($message, E_USER_DEPRECATED);
}
if ($filter instanceof TwigFilter) {
return $filter->getNodeClass();
}
return $filter instanceof \Twig_Filter_Node ?
$filter->getClass() : 'Twig\Node\Expression\FilterExpression';
}
// checks that the node only contains "constant" elements
protected function checkConstantExpression(\Twig_NodeInterface $node)
{
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');
twig/src/Extension/AbstractExtension.php000064400000002501151161070030014422
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\Environment;
abstract class AbstractExtension implements ExtensionInterface
{
/**
* @deprecated since 1.23 (to be removed in 2.0), implement
\Twig_Extension_InitRuntimeInterface instead
*/
public function initRuntime(Environment $environment)
{
}
public function getTokenParsers()
{
return [];
}
public function getNodeVisitors()
{
return [];
}
public function getFilters()
{
return [];
}
public function getTests()
{
return [];
}
public function getFunctions()
{
return [];
}
public function getOperators()
{
return [];
}
/**
* @deprecated since 1.23 (to be removed in 2.0), implement
\Twig_Extension_GlobalsInterface instead
*/
public function getGlobals()
{
return [];
}
/**
* @deprecated since 1.26 (to be removed in 2.0), not used anymore
internally
*/
public function getName()
{
return \get_class($this);
}
}
class_alias('Twig\Extension\AbstractExtension',
'Twig_Extension');
twig/src/Extension/CoreExtension.php000064400000153077151161070030013566
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\ExpressionParser;
use Twig\TokenParser\ApplyTokenParser;
use Twig\TokenParser\BlockTokenParser;
use Twig\TokenParser\DeprecatedTokenParser;
use Twig\TokenParser\DoTokenParser;
use Twig\TokenParser\EmbedTokenParser;
use Twig\TokenParser\ExtendsTokenParser;
use Twig\TokenParser\FilterTokenParser;
use Twig\TokenParser\FlushTokenParser;
use Twig\TokenParser\ForTokenParser;
use Twig\TokenParser\FromTokenParser;
use Twig\TokenParser\IfTokenParser;
use Twig\TokenParser\ImportTokenParser;
use Twig\TokenParser\IncludeTokenParser;
use Twig\TokenParser\MacroTokenParser;
use Twig\TokenParser\SetTokenParser;
use Twig\TokenParser\SpacelessTokenParser;
use Twig\TokenParser\UseTokenParser;
use Twig\TokenParser\WithTokenParser;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
/**
* @final
*/
class CoreExtension extends AbstractExtension
{
protected $dateFormats = ['F j, Y H:i', '%d days'];
protected $numberFormat = [0, '.', ','];
protected $timezone = null;
protected $escapers = [];
/**
* 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)
{
$this->escapers[$strategy] = $callable;
}
/**
* Gets all defined escapers.
*
* @return array An array of escapers
*/
public function getEscapers()
{
return $this->escapers;
}
/**
* Sets the default format to be used by the date filter.
*
* @param string $format The default date format string
* @param string $dateIntervalFormat The default date interval format
string
*/
public function setDateFormat($format = null, $dateIntervalFormat =
null)
{
if (null !== $format) {
$this->dateFormats[0] = $format;
}
if (null !== $dateIntervalFormat) {
$this->dateFormats[1] = $dateIntervalFormat;
}
}
/**
* Gets the default format to be used by the date filter.
*
* @return array The default date format string and the default date
interval format string
*/
public function getDateFormat()
{
return $this->dateFormats;
}
/**
* Sets the default timezone to be used by the date filter.
*
* @param \DateTimeZone|string $timezone The default timezone string or
a \DateTimeZone object
*/
public function setTimezone($timezone)
{
$this->timezone = $timezone instanceof \DateTimeZone ? $timezone
: new \DateTimeZone($timezone);
}
/**
* Gets the default timezone to be used by the date filter.
*
* @return \DateTimeZone The default timezone currently in use
*/
public function getTimezone()
{
if (null === $this->timezone) {
$this->timezone = new
\DateTimeZone(date_default_timezone_get());
}
return $this->timezone;
}
/**
* Sets the default format to be used by the number_format filter.
*
* @param int $decimal the number of decimal places to use
* @param string $decimalPoint the character(s) to use for the decimal
point
* @param string $thousandSep the character(s) to use for the
thousands separator
*/
public function setNumberFormat($decimal, $decimalPoint, $thousandSep)
{
$this->numberFormat = [$decimal, $decimalPoint, $thousandSep];
}
/**
* Get the default format used by the number_format filter.
*
* @return array The arguments for number_format()
*/
public function getNumberFormat()
{
return $this->numberFormat;
}
public function getTokenParsers()
{
return [
new ApplyTokenParser(),
new ForTokenParser(),
new IfTokenParser(),
new ExtendsTokenParser(),
new IncludeTokenParser(),
new BlockTokenParser(),
new UseTokenParser(),
new FilterTokenParser(),
new MacroTokenParser(),
new ImportTokenParser(),
new FromTokenParser(),
new SetTokenParser(),
new SpacelessTokenParser(),
new FlushTokenParser(),
new DoTokenParser(),
new EmbedTokenParser(),
new WithTokenParser(),
new DeprecatedTokenParser(),
];
}
public function getFilters()
{
$filters = [
// formatting filters
new TwigFilter('date',
'twig_date_format_filter', ['needs_environment' =>
true]),
new TwigFilter('date_modify',
'twig_date_modify_filter', ['needs_environment' =>
true]),
new TwigFilter('format', 'sprintf'),
new TwigFilter('replace',
'twig_replace_filter'),
new TwigFilter('number_format',
'twig_number_format_filter', ['needs_environment' =>
true]),
new TwigFilter('abs', 'abs'),
new TwigFilter('round', 'twig_round'),
// encoding
new TwigFilter('url_encode',
'twig_urlencode_filter'),
new TwigFilter('json_encode',
'twig_jsonencode_filter'),
new TwigFilter('convert_encoding',
'twig_convert_encoding'),
// string filters
new TwigFilter('title',
'twig_title_string_filter', ['needs_environment' =>
true]),
new TwigFilter('capitalize',
'twig_capitalize_string_filter', ['needs_environment'
=> true]),
new TwigFilter('upper', 'strtoupper'),
new TwigFilter('lower', 'strtolower'),
new TwigFilter('striptags', 'strip_tags'),
new TwigFilter('trim', 'twig_trim_filter'),
new TwigFilter('nl2br', 'nl2br',
['pre_escape' => 'html', 'is_safe' =>
['html']]),
new TwigFilter('spaceless',
'twig_spaceless', ['is_safe' =>
['html']]),
// array helpers
new TwigFilter('join', 'twig_join_filter'),
new TwigFilter('split',
'twig_split_filter', ['needs_environment' => true]),
new TwigFilter('sort', 'twig_sort_filter'),
new TwigFilter('merge',
'twig_array_merge'),
new TwigFilter('batch',
'twig_array_batch'),
new TwigFilter('filter',
'twig_array_filter'),
new TwigFilter('map', 'twig_array_map'),
new TwigFilter('reduce',
'twig_array_reduce'),
// string/array filters
new TwigFilter('reverse',
'twig_reverse_filter', ['needs_environment' =>
true]),
new TwigFilter('length',
'twig_length_filter', ['needs_environment' =>
true]),
new TwigFilter('slice', 'twig_slice',
['needs_environment' => true]),
new TwigFilter('first', 'twig_first',
['needs_environment' => true]),
new TwigFilter('last', 'twig_last',
['needs_environment' => true]),
// iteration and runtime
new TwigFilter('default',
'_twig_default_filter', ['node_class' =>
'\Twig\Node\Expression\Filter\DefaultFilter']),
new TwigFilter('keys',
'twig_get_array_keys_filter'),
// escaping
new TwigFilter('escape',
'twig_escape_filter', ['needs_environment' => true,
'is_safe_callback' =>
'twig_escape_filter_is_safe']),
new TwigFilter('e', 'twig_escape_filter',
['needs_environment' => true, 'is_safe_callback'
=> 'twig_escape_filter_is_safe']),
];
if (\function_exists('mb_get_info')) {
$filters[] = new TwigFilter('upper',
'twig_upper_filter', ['needs_environment' => true]);
$filters[] = new TwigFilter('lower',
'twig_lower_filter', ['needs_environment' => true]);
}
return $filters;
}
public function getFunctions()
{
return [
new TwigFunction('max', 'max'),
new TwigFunction('min', 'min'),
new TwigFunction('range', 'range'),
new TwigFunction('constant',
'twig_constant'),
new TwigFunction('cycle', 'twig_cycle'),
new TwigFunction('random', 'twig_random',
['needs_environment' => true]),
new TwigFunction('date',
'twig_date_converter', ['needs_environment' =>
true]),
new TwigFunction('include', 'twig_include',
['needs_environment' => true, 'needs_context' =>
true, 'is_safe' => ['all']]),
new TwigFunction('source', 'twig_source',
['needs_environment' => true, 'is_safe' =>
['all']]),
];
}
public function getTests()
{
return [
new TwigTest('even', null, ['node_class'
=> '\Twig\Node\Expression\Test\EvenTest']),
new TwigTest('odd', null, ['node_class'
=> '\Twig\Node\Expression\Test\OddTest']),
new TwigTest('defined', null, ['node_class'
=> '\Twig\Node\Expression\Test\DefinedTest']),
new TwigTest('sameas', null, ['node_class'
=> '\Twig\Node\Expression\Test\SameasTest',
'deprecated' => '1.21', 'alternative'
=> 'same as']),
new TwigTest('same as', null, ['node_class'
=> '\Twig\Node\Expression\Test\SameasTest']),
new TwigTest('none', null, ['node_class'
=> '\Twig\Node\Expression\Test\NullTest']),
new TwigTest('null', null, ['node_class'
=> '\Twig\Node\Expression\Test\NullTest']),
new TwigTest('divisibleby', null,
['node_class' =>
'\Twig\Node\Expression\Test\DivisiblebyTest',
'deprecated' => '1.21', 'alternative'
=> 'divisible by']),
new TwigTest('divisible by', null,
['node_class' =>
'\Twig\Node\Expression\Test\DivisiblebyTest']),
new TwigTest('constant', null,
['node_class' =>
'\Twig\Node\Expression\Test\ConstantTest']),
new TwigTest('empty', 'twig_test_empty'),
new TwigTest('iterable',
'twig_test_iterable'),
];
}
public function getOperators()
{
return [
[
'not' => ['precedence' => 50,
'class' => '\Twig\Node\Expression\Unary\NotUnary'],
'-' => ['precedence' => 500,
'class' => '\Twig\Node\Expression\Unary\NegUnary'],
'+' => ['precedence' => 500,
'class' => '\Twig\Node\Expression\Unary\PosUnary'],
],
[
'or' => ['precedence' => 10,
'class' => '\Twig\Node\Expression\Binary\OrBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'and' => ['precedence' => 15,
'class' => '\Twig\Node\Expression\Binary\AndBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'b-or' => ['precedence' => 16,
'class' =>
'\Twig\Node\Expression\Binary\BitwiseOrBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'b-xor' => ['precedence' => 17,
'class' =>
'\Twig\Node\Expression\Binary\BitwiseXorBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'b-and' => ['precedence' => 18,
'class' =>
'\Twig\Node\Expression\Binary\BitwiseAndBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'==' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\EqualBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'!=' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\NotEqualBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'<' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\LessBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'>' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\GreaterBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'>=' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\GreaterEqualBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'<=' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\LessEqualBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'not in' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\NotInBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'in' => ['precedence' => 20,
'class' => '\Twig\Node\Expression\Binary\InBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'matches' => ['precedence' => 20,
'class' =>
'\Twig\Node\Expression\Binary\MatchesBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'starts with' => ['precedence' =>
20, 'class' =>
'\Twig\Node\Expression\Binary\StartsWithBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'ends with' => ['precedence' =>
20, 'class' =>
'\Twig\Node\Expression\Binary\EndsWithBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'..' => ['precedence' => 25,
'class' =>
'\Twig\Node\Expression\Binary\RangeBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'+' => ['precedence' => 30,
'class' => '\Twig\Node\Expression\Binary\AddBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'-' => ['precedence' => 30,
'class' => '\Twig\Node\Expression\Binary\SubBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'~' => ['precedence' => 40,
'class' =>
'\Twig\Node\Expression\Binary\ConcatBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'*' => ['precedence' => 60,
'class' => '\Twig\Node\Expression\Binary\MulBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'/' => ['precedence' => 60,
'class' => '\Twig\Node\Expression\Binary\DivBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'//' => ['precedence' => 60,
'class' =>
'\Twig\Node\Expression\Binary\FloorDivBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'%' => ['precedence' => 60,
'class' => '\Twig\Node\Expression\Binary\ModBinary',
'associativity' => ExpressionParser::OPERATOR_LEFT],
'is' => ['precedence' => 100,
'associativity' => ExpressionParser::OPERATOR_LEFT],
'is not' => ['precedence' => 100,
'associativity' => ExpressionParser::OPERATOR_LEFT],
'**' => ['precedence' => 200,
'class' =>
'\Twig\Node\Expression\Binary\PowerBinary',
'associativity' => ExpressionParser::OPERATOR_RIGHT],
'??' => ['precedence' => 300,
'class' =>
'\Twig\Node\Expression\NullCoalesceExpression',
'associativity' => ExpressionParser::OPERATOR_RIGHT],
],
];
}
public function getName()
{
return 'core';
}
}
class_alias('Twig\Extension\CoreExtension',
'Twig_Extension_Core');
}
namespace {
use Twig\Environment;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
use Twig\Loader\SourceContextLoaderInterface;
use Twig\Markup;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Node;
/**
* Cycles over a value.
*
* @param \ArrayAccess|array $values
* @param int $position The cycle position
*
* @return string The next value in the cycle
*/
function twig_cycle($values, $position)
{
if (!\is_array($values) && !$values instanceof \ArrayAccess) {
return $values;
}
return $values[$position % \count($values)];
}
/**
* Returns a random value depending on the supplied parameter type:
* - a random item from a \Traversable or array
* - a random character from a string
* - a random integer between 0 and the integer parameter.
*
* @param \Traversable|array|int|float|string $values The values to pick a
random item from
* @param int|null $max Maximum value used
when $values is an int
*
* @throws RuntimeError when $values is an empty array (does not apply to
an empty string which is returned as is)
*
* @return mixed A random value from the given sequence
*/
function twig_random(Environment $env, $values = null, $max = null)
{
if (null === $values) {
return null === $max ? mt_rand() : mt_rand(0, $max);
}
if (\is_int($values) || \is_float($values)) {
if (null === $max) {
if ($values < 0) {
$max = 0;
$min = $values;
} else {
$max = $values;
$min = 0;
}
} else {
$min = $values;
$max = $max;
}
return mt_rand($min, $max);
}
if (\is_string($values)) {
if ('' === $values) {
return '';
}
if (null !== $charset = $env->getCharset()) {
if ('UTF-8' !== $charset) {
$values = twig_convert_encoding($values, 'UTF-8',
$charset);
}
// unicode version of str_split()
// split at all positions, but not after the start and not
before the end
$values = preg_split('/(?<!^)(?!$)/u', $values);
if ('UTF-8' !== $charset) {
foreach ($values as $i => $value) {
$values[$i] = twig_convert_encoding($value, $charset,
'UTF-8');
}
}
} else {
return $values[mt_rand(0, \strlen($values) - 1)];
}
}
if (!twig_test_iterable($values)) {
return $values;
}
$values = twig_to_array($values);
if (0 === \count($values)) {
throw new RuntimeError('The random function cannot pick from
an empty array.');
}
return $values[array_rand($values, 1)];
}
/**
* Converts a date to the given format.
*
* {{ post.published_at|date("m/d/Y") }}
*
* @param \DateTime|\DateTimeInterface|\DateInterval|string $date A
date
* @param string|null $format The
target format, null to use the default
* @param \DateTimeZone|string|false|null $timezone The
target timezone, null to use the default, false to leave unchanged
*
* @return string The formatted date
*/
function twig_date_format_filter(Environment $env, $date, $format = null,
$timezone = null)
{
if (null === $format) {
$formats =
$env->getExtension('\Twig\Extension\CoreExtension')->getDateFormat();
$format = $date instanceof \DateInterval ? $formats[1] :
$formats[0];
}
if ($date instanceof \DateInterval) {
return $date->format($format);
}
return twig_date_converter($env, $date, $timezone)->format($format);
}
/**
* Returns a new date object modified.
*
* {{
post.published_at|date_modify("-1day")|date("m/d/Y") }}
*
* @param \DateTime|string $date A date
* @param string $modifier A modifier string
*
* @return \DateTime
*/
function twig_date_modify_filter(Environment $env, $date, $modifier)
{
$date = twig_date_converter($env, $date, false);
$resultDate = $date->modify($modifier);
// This is a hack to ensure PHP 5.2 support and support for
\DateTimeImmutable
// \DateTime::modify does not return the modified \DateTime object <
5.3.0
// and \DateTimeImmutable does not modify $date.
return null === $resultDate ? $date : $resultDate;
}
/**
* Converts an input to a \DateTime instance.
*
* {% if date(user.created_at) < date('+2days') %}
* {# do something #}
* {% endif %}
*
* @param \DateTime|\DateTimeInterface|string|null $date A date
* @param \DateTimeZone|string|false|null $timezone The target
timezone, null to use the default, false to leave unchanged
*
* @return \DateTimeInterface
*/
function twig_date_converter(Environment $env, $date = null, $timezone =
null)
{
// determine the timezone
if (false !== $timezone) {
if (null === $timezone) {
$timezone =
$env->getExtension('\Twig\Extension\CoreExtension')->getTimezone();
} elseif (!$timezone instanceof \DateTimeZone) {
$timezone = new \DateTimeZone($timezone);
}
}
// immutable dates
if ($date instanceof \DateTimeImmutable) {
return false !== $timezone ? $date->setTimezone($timezone) :
$date;
}
if ($date instanceof \DateTime || $date instanceof \DateTimeInterface)
{
$date = clone $date;
if (false !== $timezone) {
$date->setTimezone($timezone);
}
return $date;
}
if (null === $date || 'now' === $date) {
return new \DateTime($date, false !== $timezone ? $timezone :
$env->getExtension('\Twig\Extension\CoreExtension')->getTimezone());
}
$asString = (string) $date;
if (ctype_digit($asString) || (!empty($asString) &&
'-' === $asString[0] && ctype_digit(substr($asString,
1)))) {
$date = new \DateTime('@'.$date);
} else {
$date = new \DateTime($date,
$env->getExtension('\Twig\Extension\CoreExtension')->getTimezone());
}
if (false !== $timezone) {
$date->setTimezone($timezone);
}
return $date;
}
/**
* Replaces strings within a string.
*
* @param string $str String to replace in
* @param array|\Traversable $from Replace values
* @param string|null $to Replace to, deprecated (@see
https://secure.php.net/manual/en/function.strtr.php)
*
* @return string
*/
function twig_replace_filter($str, $from, $to = null)
{
if (\is_string($from) && \is_string($to)) {
@trigger_error('Using "replace" with character by
character replacement is deprecated since version 1.22 and will be removed
in Twig 2.0', E_USER_DEPRECATED);
return strtr($str, $from, $to);
}
if (!twig_test_iterable($from)) {
throw new RuntimeError(sprintf('The "replace" filter
expects an array or "Traversable" as replace values, got
"%s".', \is_object($from) ? \get_class($from) :
\gettype($from)));
}
return strtr($str, twig_to_array($from));
}
/**
* Rounds a number.
*
* @param int|float $value The value to round
* @param int|float $precision The rounding precision
* @param string $method The method to use for rounding
*
* @return int|float The rounded number
*/
function twig_round($value, $precision = 0, $method = 'common')
{
if ('common' == $method) {
return round($value, $precision);
}
if ('ceil' != $method && 'floor' !=
$method) {
throw new RuntimeError('The round filter only supports the
"common", "ceil", and "floor"
methods.');
}
return $method($value * pow(10, $precision)) / pow(10, $precision);
}
/**
* Number format filter.
*
* All of the formatting options can be left null, in that case the
defaults will
* be used. Supplying any of the parameters will override the defaults set
in the
* environment object.
*
* @param mixed $number A float/int/string of the number to format
* @param int $decimal the number of decimal points to display
* @param string $decimalPoint the character(s) to use for the decimal
point
* @param string $thousandSep the character(s) to use for the thousands
separator
*
* @return string The formatted number
*/
function twig_number_format_filter(Environment $env, $number, $decimal =
null, $decimalPoint = null, $thousandSep = null)
{
$defaults =
$env->getExtension('\Twig\Extension\CoreExtension')->getNumberFormat();
if (null === $decimal) {
$decimal = $defaults[0];
}
if (null === $decimalPoint) {
$decimalPoint = $defaults[1];
}
if (null === $thousandSep) {
$thousandSep = $defaults[2];
}
return number_format((float) $number, $decimal, $decimalPoint,
$thousandSep);
}
/**
* URL encodes (RFC 3986) a string as a path segment or an array as a query
string.
*
* @param string|array $url A URL or an array of query parameters
*
* @return string The URL encoded value
*/
function twig_urlencode_filter($url)
{
if (\is_array($url)) {
if (\defined('PHP_QUERY_RFC3986')) {
return http_build_query($url, '', '&',
PHP_QUERY_RFC3986);
}
return http_build_query($url, '', '&');
}
return rawurlencode($url);
}
/**
* JSON encodes a variable.
*
* @param mixed $value the value to encode
* @param int $options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG,
JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT,
JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
*
* @return mixed The JSON encoded value
*/
function twig_jsonencode_filter($value, $options = 0)
{
if ($value instanceof Markup) {
$value = (string) $value;
} elseif (\is_array($value)) {
array_walk_recursive($value, '_twig_markup2string');
}
return json_encode($value, $options);
}
function _twig_markup2string(&$value)
{
if ($value instanceof Markup) {
$value = (string) $value;
}
}
/**
* Merges an array with another one.
*
* {% set items = { 'apple': 'fruit',
'orange': 'fruit' } %}
*
* {% set items = items|merge({ 'peugeot': 'car' }) %}
*
* {# items now contains { 'apple': 'fruit',
'orange': 'fruit', 'peugeot': 'car'
} #}
*
* @param array|\Traversable $arr1 An array
* @param array|\Traversable $arr2 An array
*
* @return array The merged array
*/
function twig_array_merge($arr1, $arr2)
{
if (!twig_test_iterable($arr1)) {
throw new RuntimeError(sprintf('The merge filter only works
with arrays or "Traversable", got "%s" as first
argument.', \gettype($arr1)));
}
if (!twig_test_iterable($arr2)) {
throw new RuntimeError(sprintf('The merge filter only works
with arrays or "Traversable", got "%s" as second
argument.', \gettype($arr2)));
}
return array_merge(twig_to_array($arr1), twig_to_array($arr2));
}
/**
* Slices a variable.
*
* @param mixed $item A variable
* @param int $start Start of the slice
* @param int $length Size of the slice
* @param bool $preserveKeys Whether to preserve key or not (when the
input is an array)
*
* @return mixed The sliced variable
*/
function twig_slice(Environment $env, $item, $start, $length = null,
$preserveKeys = false)
{
if ($item instanceof \Traversable) {
while ($item instanceof \IteratorAggregate) {
$item = $item->getIterator();
}
if ($start >= 0 && $length >= 0 && $item
instanceof \Iterator) {
try {
return iterator_to_array(new \LimitIterator($item, $start,
null === $length ? -1 : $length), $preserveKeys);
} catch (\OutOfBoundsException $e) {
return [];
}
}
$item = iterator_to_array($item, $preserveKeys);
}
if (\is_array($item)) {
return \array_slice($item, $start, $length, $preserveKeys);
}
$item = (string) $item;
if (\function_exists('mb_get_info') && null !==
$charset = $env->getCharset()) {
return (string) mb_substr($item, $start, null === $length ?
mb_strlen($item, $charset) - $start : $length, $charset);
}
return (string) (null === $length ? substr($item, $start) :
substr($item, $start, $length));
}
/**
* Returns the first element of the item.
*
* @param mixed $item A variable
*
* @return mixed The first element of the item
*/
function twig_first(Environment $env, $item)
{
$elements = twig_slice($env, $item, 0, 1, false);
return \is_string($elements) ? $elements : current($elements);
}
/**
* Returns the last element of the item.
*
* @param mixed $item A variable
*
* @return mixed The last element of the item
*/
function twig_last(Environment $env, $item)
{
$elements = twig_slice($env, $item, -1, 1, false);
return \is_string($elements) ? $elements : current($elements);
}
/**
* Joins the values to a string.
*
* The separators between elements are empty strings per default, you can
define them with the optional parameters.
*
* {{ [1, 2, 3]|join(', ', ' and ') }}
* {# returns 1, 2 and 3 #}
*
* {{ [1, 2, 3]|join('|') }}
* {# returns 1|2|3 #}
*
* {{ [1, 2, 3]|join }}
* {# returns 123 #}
*
* @param array $value An array
* @param string $glue The separator
* @param string|null $and The separator for the last pair
*
* @return string The concatenated string
*/
function twig_join_filter($value, $glue = '', $and = null)
{
if (!twig_test_iterable($value)) {
$value = (array) $value;
}
$value = twig_to_array($value, false);
if (0 === \count($value)) {
return '';
}
if (null === $and || $and === $glue) {
return implode($glue, $value);
}
if (1 === \count($value)) {
return $value[0];
}
return implode($glue, \array_slice($value, 0,
-1)).$and.$value[\count($value) - 1];
}
/**
* Splits the string into an array.
*
* {{ "one,two,three"|split(',') }}
* {# returns [one, two, three] #}
*
* {{ "one,two,three,four,five"|split(',', 3) }}
* {# returns [one, two, "three,four,five"] #}
*
* {{ "123"|split('') }}
* {# returns [1, 2, 3] #}
*
* {{ "aabbcc"|split('', 2) }}
* {# returns [aa, bb, cc] #}
*
* @param string $value A string
* @param string $delimiter The delimiter
* @param int $limit The limit
*
* @return array The split string as an array
*/
function twig_split_filter(Environment $env, $value, $delimiter, $limit =
null)
{
if (\strlen($delimiter) > 0) {
return null === $limit ? explode($delimiter, $value) :
explode($delimiter, $value, $limit);
}
if (!\function_exists('mb_get_info') || null === $charset =
$env->getCharset()) {
return str_split($value, null === $limit ? 1 : $limit);
}
if ($limit <= 1) {
return preg_split('/(?<!^)(?!$)/u', $value);
}
$length = mb_strlen($value, $charset);
if ($length < $limit) {
return [$value];
}
$r = [];
for ($i = 0; $i < $length; $i += $limit) {
$r[] = mb_substr($value, $i, $limit, $charset);
}
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);
}
if (null !== $charset = $env->getCharset()) {
$string = (string) $item;
if ('UTF-8' !== $charset) {
$item = twig_convert_encoding($string, 'UTF-8',
$charset);
}
preg_match_all('/./us', $item, $matches);
$string = implode('', array_reverse($matches[0]));
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, $charset,
'UTF-8');
}
return $string;
}
return strrev((string) $item);
}
/**
* Sorts an array.
*
* @param array|\Traversable $array
*
* @return array
*/
function twig_sort_filter($array)
{
if ($array instanceof \Traversable) {
$array = iterator_to_array($array);
} elseif (!\is_array($array)) {
throw new RuntimeError(sprintf('The sort filter only works
with arrays or "Traversable", got "%s".',
\gettype($array)));
}
asort($array);
return $array;
}
/**
* @internal
*/
function twig_in_filter($value, $compare)
{
if ($value instanceof Markup) {
$value = (string) $value;
}
if ($compare instanceof Markup) {
$compare = (string) $compare;
}
if (\is_array($compare)) {
return \in_array($value, $compare, \is_object($value) ||
\is_resource($value));
} elseif (\is_string($compare) && (\is_string($value) ||
\is_int($value) || \is_float($value))) {
return '' === $value || false !== strpos($compare,
(string) $value);
} elseif ($compare instanceof \Traversable) {
if (\is_object($value) || \is_resource($value)) {
foreach ($compare as $item) {
if ($item === $value) {
return true;
}
}
} else {
foreach ($compare as $item) {
if ($item == $value) {
return true;
}
}
}
return false;
}
return false;
}
/**
* Returns a trimmed string.
*
* @return string
*
* @throws RuntimeError When an invalid trimming side is used (not a string
or not 'left', 'right', or 'both')
*/
function twig_trim_filter($string, $characterMask = null, $side =
'both')
{
if (null === $characterMask) {
$characterMask = " \t\n\r\0\x0B";
}
switch ($side) {
case 'both':
return trim($string, $characterMask);
case 'left':
return ltrim($string, $characterMask);
case 'right':
return rtrim($string, $characterMask);
default:
throw new RuntimeError('Trimming side must be
"left", "right" or "both".');
}
}
/**
* Removes whitespaces between HTML tags.
*
* @return string
*/
function twig_spaceless($content)
{
return trim(preg_replace('/>\s+</',
'><', $content));
}
/**
* Escapes a string.
*
* @param mixed $string The value to be escaped
* @param string $strategy The escaping strategy
* @param string $charset The charset
* @param bool $autoescape Whether the function is called by the
auto-escaping feature (true) or by the developer (false)
*
* @return string
*/
function twig_escape_filter(Environment $env, $string, $strategy =
'html', $charset = null, $autoescape = false)
{
if ($autoescape && $string instanceof Markup) {
return $string;
}
if (!\is_string($string)) {
if (\is_object($string) && method_exists($string,
'__toString')) {
$string = (string) $string;
} elseif (\in_array($strategy, ['html', 'js',
'css', 'html_attr', 'url'])) {
return $string;
}
}
if ('' === $string) {
return '';
}
if (null === $charset) {
$charset = $env->getCharset();
}
switch ($strategy) {
case 'html':
// see https://secure.php.net/htmlspecialchars
// Using a static variable to avoid initializing the array
// each time the function is called. Moving the declaration on
the
// top of the function slow downs other escaping strategies.
static $htmlspecialcharsCharsets = [
'ISO-8859-1' => true, 'ISO8859-1'
=> true,
'ISO-8859-15' => true, 'ISO8859-15'
=> true,
'utf-8' => true, 'UTF-8' => true,
'CP866' => true, 'IBM866' =>
true, '866' => true,
'CP1251' => true, 'WINDOWS-1251'
=> true, 'WIN-1251' => true,
'1251' => true,
'CP1252' => true, 'WINDOWS-1252'
=> true, '1252' => true,
'KOI8-R' => true, 'KOI8-RU' =>
true, 'KOI8R' => true,
'BIG5' => true, '950' => true,
'GB2312' => true, '936' => true,
'BIG5-HKSCS' => true,
'SHIFT_JIS' => true, 'SJIS' =>
true, '932' => true,
'EUC-JP' => true, 'EUCJP' =>
true,
'ISO8859-5' => true, 'ISO-8859-5'
=> true, 'MACROMAN' => true,
];
if (isset($htmlspecialcharsCharsets[$charset])) {
return htmlspecialchars($string, ENT_QUOTES |
ENT_SUBSTITUTE, $charset);
}
if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) {
// cache the lowercase variant for future iterations
$htmlspecialcharsCharsets[$charset] = true;
return htmlspecialchars($string, ENT_QUOTES |
ENT_SUBSTITUTE, $charset);
}
$string = twig_convert_encoding($string, 'UTF-8',
$charset);
$string = htmlspecialchars($string, ENT_QUOTES |
ENT_SUBSTITUTE, 'UTF-8');
return twig_convert_encoding($string, $charset,
'UTF-8');
case 'js':
// escape all non-alphanumeric characters
// into their \x or \uHHHH representations
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, 'UTF-8',
$charset);
}
if (!preg_match('//u', $string)) {
throw new RuntimeError('The string to escape is not a
valid UTF-8 string.');
}
$string =
preg_replace_callback('#[^a-zA-Z0-9,\._]#Su',
'_twig_escape_js_callback', $string);
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, $charset,
'UTF-8');
}
return $string;
case 'css':
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, 'UTF-8',
$charset);
}
if (!preg_match('//u', $string)) {
throw new RuntimeError('The string to escape is not a
valid UTF-8 string.');
}
$string = preg_replace_callback('#[^a-zA-Z0-9]#Su',
'_twig_escape_css_callback', $string);
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, $charset,
'UTF-8');
}
return $string;
case 'html_attr':
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, 'UTF-8',
$charset);
}
if (!preg_match('//u', $string)) {
throw new RuntimeError('The string to escape is not a
valid UTF-8 string.');
}
$string =
preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su',
'_twig_escape_html_attr_callback', $string);
if ('UTF-8' !== $charset) {
$string = twig_convert_encoding($string, $charset,
'UTF-8');
}
return $string;
case 'url':
return rawurlencode($string);
default:
static $escapers;
if (null === $escapers) {
$escapers =
$env->getExtension('\Twig\Extension\CoreExtension')->getEscapers();
}
if (isset($escapers[$strategy])) {
return \call_user_func($escapers[$strategy], $env, $string,
$charset);
}
$validStrategies = implode(', ',
array_merge(['html', 'js', 'url',
'css', 'html_attr'], array_keys($escapers)));
throw new RuntimeError(sprintf('Invalid escaping strategy
"%s" (valid ones: %s).', $strategy, $validStrategies));
}
}
/**
* @internal
*/
function twig_escape_filter_is_safe(Node $filterArgs)
{
foreach ($filterArgs as $arg) {
if ($arg instanceof ConstantExpression) {
return [$arg->getAttribute('value')];
}
return [];
}
return ['html'];
}
if (\function_exists('mb_convert_encoding')) {
function twig_convert_encoding($string, $to, $from)
{
return mb_convert_encoding($string, $to, $from);
}
} elseif (\function_exists('iconv')) {
function twig_convert_encoding($string, $to, $from)
{
return iconv($from, $to, $string);
}
} else {
function twig_convert_encoding($string, $to, $from)
{
throw new RuntimeError('No suitable convert encoding function
(use UTF-8 as your encoding or install the iconv or mbstring
extension).');
}
}
if (\function_exists('mb_ord')) {
function twig_ord($string)
{
return mb_ord($string, 'UTF-8');
}
} else {
function twig_ord($string)
{
$code = ($string = unpack('C*', substr($string, 0, 4))) ?
$string[1] : 0;
if (0xF0 <= $code) {
return (($code - 0xF0) << 18) + (($string[2] - 0x80)
<< 12) + (($string[3] - 0x80) << 6) + $string[4] - 0x80;
}
if (0xE0 <= $code) {
return (($code - 0xE0) << 12) + (($string[2] - 0x80)
<< 6) + $string[3] - 0x80;
}
if (0xC0 <= $code) {
return (($code - 0xC0) << 6) + $string[2] - 0x80;
}
return $code;
}
}
function _twig_escape_js_callback($matches)
{
$char = $matches[0];
/*
* A few characters have short escape sequences in JSON and JavaScript.
* Escape sequences supported only by JavaScript, not JSON, are
ommitted.
* \" is also supported but omitted, because the resulting string
is not HTML safe.
*/
static $shortMap = [
'\\' => '\\\\',
'/' => '\\/',
"\x08" => '\b',
"\x0C" => '\f',
"\x0A" => '\n',
"\x0D" => '\r',
"\x09" => '\t',
];
if (isset($shortMap[$char])) {
return $shortMap[$char];
}
// \uHHHH
$char = twig_convert_encoding($char, 'UTF-16BE',
'UTF-8');
$char = strtoupper(bin2hex($char));
if (4 >= \strlen($char)) {
return sprintf('\u%04s', $char);
}
return sprintf('\u%04s\u%04s', substr($char, 0, -4),
substr($char, -4));
}
function _twig_escape_css_callback($matches)
{
$char = $matches[0];
return sprintf('\\%X ', 1 === \strlen($char) ? \ord($char) :
twig_ord($char));
}
/**
* This function is adapted from code coming from Zend Framework.
*
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc.
(https://www.zend.com)
* @license https://framework.zend.com/license/new-bsd New BSD License
*/
function _twig_escape_html_attr_callback($matches)
{
$chr = $matches[0];
$ord = \ord($chr);
/*
* The following replaces characters undefined in HTML with the
* hex entity for the Unicode replacement character.
*/
if (($ord <= 0x1f && "\t" != $chr &&
"\n" != $chr && "\r" != $chr) || ($ord >=
0x7f && $ord <= 0x9f)) {
return '�';
}
/*
* Check if the current character to escape has a name entity we should
* replace it with while grabbing the hex value of the character.
*/
if (1 == \strlen($chr)) {
/*
* While HTML supports far more named entities, the lowest common
denominator
* has become HTML5's XML Serialisation which is restricted to
the those named
* entities that XML supports. Using HTML entities would result in
this error:
* XML Parsing Error: undefined entity
*/
static $entityMap = [
34 => '"', /* quotation mark */
38 => '&', /* ampersand */
60 => '<', /* less-than sign */
62 => '>', /* greater-than sign */
];
if (isset($entityMap[$ord])) {
return $entityMap[$ord];
}
return sprintf('&#x%02X;', $ord);
}
/*
* Per OWASP recommendations, we'll use hex entities for any other
* characters where a named entity does not exist.
*/
return sprintf('&#x%04X;', twig_ord($chr));
}
// add multibyte extensions if possible
if (\function_exists('mb_get_info')) {
/**
* Returns the length of a variable.
*
* @param mixed $thing A variable
*
* @return int The length of the value
*/
function twig_length_filter(Environment $env, $thing)
{
if (null === $thing) {
return 0;
}
if (is_scalar($thing)) {
return mb_strlen($thing, $env->getCharset());
}
if ($thing instanceof \Countable || \is_array($thing) || $thing
instanceof \SimpleXMLElement) {
return \count($thing);
}
if ($thing instanceof \Traversable) {
return iterator_count($thing);
}
if (\is_object($thing) && method_exists($thing,
'__toString')) {
return mb_strlen((string) $thing, $env->getCharset());
}
return 1;
}
/**
* Converts a string to uppercase.
*
* @param string $string A string
*
* @return string The uppercased string
*/
function twig_upper_filter(Environment $env, $string)
{
if (null !== $charset = $env->getCharset()) {
return mb_strtoupper($string, $charset);
}
return strtoupper($string);
}
/**
* Converts a string to lowercase.
*
* @param string $string A string
*
* @return string The lowercased string
*/
function twig_lower_filter(Environment $env, $string)
{
if (null !== $charset = $env->getCharset()) {
return mb_strtolower($string, $charset);
}
return strtolower($string);
}
/**
* Returns a titlecased string.
*
* @param string $string A string
*
* @return string The titlecased string
*/
function twig_title_string_filter(Environment $env, $string)
{
if (null !== $charset = $env->getCharset()) {
return mb_convert_case($string, MB_CASE_TITLE, $charset);
}
return ucwords(strtolower($string));
}
/**
* Returns a capitalized string.
*
* @param string $string A string
*
* @return string The capitalized string
*/
function twig_capitalize_string_filter(Environment $env, $string)
{
if (null !== $charset = $env->getCharset()) {
return mb_strtoupper(mb_substr($string, 0, 1, $charset),
$charset).mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset),
$charset), $charset);
}
return ucfirst(strtolower($string));
}
}
// and byte fallback
else {
/**
* Returns the length of a variable.
*
* @param mixed $thing A variable
*
* @return int The length of the value
*/
function twig_length_filter(Environment $env, $thing)
{
if (null === $thing) {
return 0;
}
if (is_scalar($thing)) {
return \strlen($thing);
}
if ($thing instanceof \SimpleXMLElement) {
return \count($thing);
}
if (\is_object($thing) && method_exists($thing,
'__toString') && !$thing instanceof \Countable) {
return \strlen((string) $thing);
}
if ($thing instanceof \Countable || \is_array($thing)) {
return \count($thing);
}
if ($thing instanceof \IteratorAggregate) {
return iterator_count($thing);
}
return 1;
}
/**
* Returns a titlecased string.
*
* @param string $string A string
*
* @return string The titlecased string
*/
function twig_title_string_filter(Environment $env, $string)
{
return ucwords(strtolower($string));
}
/**
* Returns a capitalized string.
*
* @param string $string A string
*
* @return string The capitalized string
*/
function twig_capitalize_string_filter(Environment $env, $string)
{
return ucfirst(strtolower($string));
}
}
/**
* @internal
*/
function twig_ensure_traversable($seq)
{
if ($seq instanceof \Traversable || \is_array($seq)) {
return $seq;
}
return [];
}
/**
* @internal
*/
function twig_to_array($seq, $preserveKeys = true)
{
if ($seq instanceof \Traversable) {
return iterator_to_array($seq, $preserveKeys);
}
if (!\is_array($seq)) {
return $seq;
}
return $preserveKeys ? $seq : array_values($seq);
}
/**
* Checks if a variable is empty.
*
* {# evaluates to true if the foo variable is null, false, or the empty
string #}
* {% if foo is empty %}
* {# ... #}
* {% endif %}
*
* @param mixed $value A variable
*
* @return bool true if the value is empty, false otherwise
*/
function twig_test_empty($value)
{
if ($value instanceof \Countable) {
return 0 == \count($value);
}
if ($value instanceof \Traversable) {
return !iterator_count($value);
}
if (\is_object($value) && method_exists($value,
'__toString')) {
return '' === (string) $value;
}
return '' === $value || false === $value || null === $value
|| [] === $value;
}
/**
* Checks if a variable is traversable.
*
* {# evaluates to true if the foo variable is an array or a traversable
object #}
* {% if foo is iterable %}
* {# ... #}
* {% endif %}
*
* @param mixed $value A variable
*
* @return bool true if the value is traversable
*/
function twig_test_iterable($value)
{
return $value instanceof \Traversable || \is_array($value);
}
/**
* Renders a template.
*
* @param array $context
* @param string|array $template The template to render or an array of
templates to try consecutively
* @param array $variables The variables to pass to the template
* @param bool $withContext
* @param bool $ignoreMissing Whether to ignore missing templates
or not
* @param bool $sandboxed Whether to sandbox the template or
not
*
* @return string The rendered template
*/
function twig_include(Environment $env, $context, $template, $variables =
[], $withContext = true, $ignoreMissing = false, $sandboxed = false)
{
$alreadySandboxed = false;
$sandbox = null;
if ($withContext) {
$variables = array_merge($context, $variables);
}
if ($isSandboxed = $sandboxed &&
$env->hasExtension('\Twig\Extension\SandboxExtension')) {
$sandbox =
$env->getExtension('\Twig\Extension\SandboxExtension');
if (!$alreadySandboxed = $sandbox->isSandboxed()) {
$sandbox->enableSandbox();
}
}
$loaded = null;
try {
$loaded = $env->resolveTemplate($template);
} catch (LoaderError $e) {
if (!$ignoreMissing) {
if ($isSandboxed && !$alreadySandboxed) {
$sandbox->disableSandbox();
}
throw $e;
}
} catch (\Throwable $e) {
if ($isSandboxed && !$alreadySandboxed) {
$sandbox->disableSandbox();
}
throw $e;
} catch (\Exception $e) {
if ($isSandboxed && !$alreadySandboxed) {
$sandbox->disableSandbox();
}
throw $e;
}
try {
$ret = $loaded ? $loaded->render($variables) : '';
} catch (\Exception $e) {
if ($isSandboxed && !$alreadySandboxed) {
$sandbox->disableSandbox();
}
throw $e;
}
if ($isSandboxed && !$alreadySandboxed) {
$sandbox->disableSandbox();
}
return $ret;
}
/**
* Returns a template content without rendering it.
*
* @param string $name The template name
* @param bool $ignoreMissing Whether to ignore missing templates or not
*
* @return string The template source
*/
function twig_source(Environment $env, $name, $ignoreMissing = false)
{
$loader = $env->getLoader();
try {
if (!$loader instanceof SourceContextLoaderInterface) {
return $loader->getSource($name);
} else {
return $loader->getSourceContext($name)->getCode();
}
} catch (LoaderError $e) {
if (!$ignoreMissing) {
throw $e;
}
}
}
/**
* Provides the ability to get constants from instances as well as
class/global constants.
*
* @param string $constant The name of the constant
* @param object|null $object The object to get the constant from
*
* @return string
*/
function twig_constant($constant, $object = null)
{
if (null !== $object) {
$constant = \get_class($object).'::'.$constant;
}
return \constant($constant);
}
/**
* Checks if a constant exists.
*
* @param string $constant The name of the constant
* @param object|null $object The object to get the constant from
*
* @return bool
*/
function twig_constant_is_defined($constant, $object = null)
{
if (null !== $object) {
$constant = \get_class($object).'::'.$constant;
}
return \defined($constant);
}
/**
* Batches item.
*
* @param array $items An array of items
* @param int $size The size of the batch
* @param mixed $fill A value used to fill missing items
*
* @return array
*/
function twig_array_batch($items, $size, $fill = null, $preserveKeys =
true)
{
if (!twig_test_iterable($items)) {
throw new RuntimeError(sprintf('The "batch" filter
expects an array or "Traversable", got "%s".',
\is_object($items) ? \get_class($items) : \gettype($items)));
}
$size = ceil($size);
$result = array_chunk(twig_to_array($items, $preserveKeys), $size,
$preserveKeys);
if (null !== $fill && $result) {
$last = \count($result) - 1;
if ($fillCount = $size - \count($result[$last])) {
for ($i = 0; $i < $fillCount; ++$i) {
$result[$last][] = $fill;
}
}
}
return $result;
}
function twig_array_filter($array, $arrow)
{
if (\is_array($array)) {
if (\PHP_VERSION_ID >= 50600) {
return array_filter($array, $arrow, \ARRAY_FILTER_USE_BOTH);
}
return array_filter($array, $arrow);
}
// the IteratorIterator wrapping is needed as some internal PHP classes
are \Traversable but do not implement \Iterator
return new \CallbackFilterIterator(new \IteratorIterator($array),
$arrow);
}
function twig_array_map($array, $arrow)
{
$r = [];
foreach ($array as $k => $v) {
$r[$k] = $arrow($v, $k);
}
return $r;
}
function twig_array_reduce($array, $arrow, $initial = null)
{
if (!\is_array($array)) {
$array = iterator_to_array($array);
}
return array_reduce($array, $arrow, $initial);
}
}
twig/src/Extension/DebugExtension.php000064400000003640151161070030013712
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\TwigFunction;
/**
* @final
*/
class DebugExtension extends AbstractExtension
{
public function getFunctions()
{
// dump is safe if var_dump is overridden by xdebug
$isDumpOutputHtmlSafe = \extension_loaded('xdebug')
// false means that it was not set (and the default is on) or
it explicitly enabled
&& (false ===
ini_get('xdebug.overload_var_dump') ||
ini_get('xdebug.overload_var_dump'))
// false means that it was not set (and the default is on) or
it explicitly enabled
// xdebug.overload_var_dump produces HTML only when html_errors
is also enabled
&& (false === ini_get('html_errors') ||
ini_get('html_errors'))
|| 'cli' === \PHP_SAPI
;
return [
new TwigFunction('dump', 'twig_var_dump',
['is_safe' => $isDumpOutputHtmlSafe ? ['html'] : [],
'needs_context' => true, 'needs_environment' =>
true, 'is_variadic' => true]),
];
}
public function getName()
{
return 'debug';
}
}
class_alias('Twig\Extension\DebugExtension',
'Twig_Extension_Debug');
}
namespace {
use Twig\Environment;
use Twig\Template;
use Twig\TemplateWrapper;
function twig_var_dump(Environment $env, $context, array $vars = [])
{
if (!$env->isDebug()) {
return;
}
ob_start();
if (!$vars) {
$vars = [];
foreach ($context as $key => $value) {
if (!$value instanceof Template && !$value instanceof
TemplateWrapper) {
$vars[$key] = $value;
}
}
var_dump($vars);
} else {
foreach ($vars as $var) {
var_dump($var);
}
}
return ob_get_clean();
}
}
twig/src/Extension/EscaperExtension.php000064400000005731151161070030014251
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\NodeVisitor\EscaperNodeVisitor;
use Twig\TokenParser\AutoEscapeTokenParser;
use Twig\TwigFilter;
/**
* @final
*/
class EscaperExtension extends AbstractExtension
{
protected $defaultStrategy;
/**
* @param string|false|callable $defaultStrategy An escaping strategy
*
* @see setDefaultStrategy()
*/
public function __construct($defaultStrategy = 'html')
{
$this->setDefaultStrategy($defaultStrategy);
}
public function getTokenParsers()
{
return [new AutoEscapeTokenParser()];
}
public function getNodeVisitors()
{
return [new EscaperNodeVisitor()];
}
public function getFilters()
{
return [
new TwigFilter('raw', 'twig_raw_filter',
['is_safe' => ['all']]),
];
}
/**
* Sets the default strategy to use when not defined by the user.
*
* The strategy can be a valid PHP callback that takes the template
* name as an argument and returns the strategy to use.
*
* @param string|false|callable $defaultStrategy An escaping strategy
*/
public function setDefaultStrategy($defaultStrategy)
{
// for BC
if (true === $defaultStrategy) {
@trigger_error('Using "true" as the default
strategy is deprecated since version 1.21. Use "html"
instead.', E_USER_DEPRECATED);
$defaultStrategy = 'html';
}
if ('filename' === $defaultStrategy) {
@trigger_error('Using "filename" as the default
strategy is deprecated since version 1.27. Use "name"
instead.', E_USER_DEPRECATED);
$defaultStrategy = 'name';
}
if ('name' === $defaultStrategy) {
$defaultStrategy =
['\Twig\FileExtensionEscapingStrategy', 'guess'];
}
$this->defaultStrategy = $defaultStrategy;
}
/**
* Gets the default strategy to use when not defined by the user.
*
* @param string $name The template name
*
* @return string|false The default strategy to use for the template
*/
public function getDefaultStrategy($name)
{
// disable string callables to avoid calling a function named html
or js,
// or any other upcoming escaping strategy
if (!\is_string($this->defaultStrategy) && false !==
$this->defaultStrategy) {
return \call_user_func($this->defaultStrategy, $name);
}
return $this->defaultStrategy;
}
public function getName()
{
return 'escaper';
}
}
class_alias('Twig\Extension\EscaperExtension',
'Twig_Extension_Escaper');
}
namespace {
/**
* Marks a variable as being safe.
*
* @param string $string A PHP variable
*
* @return string
*/
function twig_raw_filter($string)
{
return $string;
}
}
twig/src/Extension/ExtensionInterface.php000064400000005102151161070030014557
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\Environment;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\TokenParser\TokenParserInterface;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
/**
* Interface implemented by extension classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface ExtensionInterface
{
/**
* Initializes the runtime environment.
*
* This is where you can load some file that contains filter functions
for instance.
*
* @deprecated since 1.23 (to be removed in 2.0), implement
\Twig_Extension_InitRuntimeInterface instead
*/
public function initRuntime(Environment $environment);
/**
* Returns the token parser instances to add to the existing list.
*
* @return TokenParserInterface[]
*/
public function getTokenParsers();
/**
* Returns the node visitor instances to add to the existing list.
*
* @return NodeVisitorInterface[]
*/
public function getNodeVisitors();
/**
* Returns a list of filters to add to the existing list.
*
* @return TwigFilter[]
*/
public function getFilters();
/**
* Returns a list of tests to add to the existing list.
*
* @return TwigTest[]
*/
public function getTests();
/**
* Returns a list of functions to add to the existing list.
*
* @return TwigFunction[]
*/
public function getFunctions();
/**
* Returns a list of operators to add to the existing list.
*
* @return array<array> First array of unary operators, second
array of binary operators
*/
public function getOperators();
/**
* Returns a list of global variables to add to the existing list.
*
* @return array An array of global variables
*
* @deprecated since 1.23 (to be removed in 2.0), implement
\Twig_Extension_GlobalsInterface instead
*/
public function getGlobals();
/**
* Returns the name of the extension.
*
* @return string The extension name
*
* @deprecated since 1.26 (to be removed in 2.0), not used anymore
internally
*/
public function getName();
}
class_alias('Twig\Extension\ExtensionInterface',
'Twig_ExtensionInterface');
// Ensure that the aliased name is loaded to keep BC for classes
implementing the typehint with the old aliased name.
class_exists('Twig\Environment');
twig/src/Extension/GlobalsInterface.php000064400000001162151161070030014170
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
/**
* Enables usage of the deprecated
Twig\Extension\AbstractExtension::getGlobals() method.
*
* Explicitly implement this interface if you really need to implement the
* deprecated getGlobals() method in your extensions.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface GlobalsInterface
{
}
class_alias('Twig\Extension\GlobalsInterface',
'Twig_Extension_GlobalsInterface');
twig/src/Extension/InitRuntimeInterface.php000064400000001200151161070030015045
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
/**
* Enables usage of the deprecated
Twig\Extension\AbstractExtension::initRuntime() method.
*
* Explicitly implement this interface if you really need to implement the
* deprecated initRuntime() method in your extensions.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface InitRuntimeInterface
{
}
class_alias('Twig\Extension\InitRuntimeInterface',
'Twig_Extension_InitRuntimeInterface');
twig/src/Extension/OptimizerExtension.php000064400000001344151161070030014645
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\NodeVisitor\OptimizerNodeVisitor;
/**
* @final
*/
class OptimizerExtension extends AbstractExtension
{
protected $optimizers;
public function __construct($optimizers = -1)
{
$this->optimizers = $optimizers;
}
public function getNodeVisitors()
{
return [new OptimizerNodeVisitor($this->optimizers)];
}
public function getName()
{
return 'optimizer';
}
}
class_alias('Twig\Extension\OptimizerExtension',
'Twig_Extension_Optimizer');
twig/src/Extension/ProfilerExtension.php000064400000002137151161070030014446
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\Profiler\NodeVisitor\ProfilerNodeVisitor;
use Twig\Profiler\Profile;
class ProfilerExtension extends AbstractExtension
{
private $actives = [];
public function __construct(Profile $profile)
{
$this->actives[] = $profile;
}
public function enter(Profile $profile)
{
$this->actives[0]->addProfile($profile);
array_unshift($this->actives, $profile);
}
public function leave(Profile $profile)
{
$profile->leave();
array_shift($this->actives);
if (1 === \count($this->actives)) {
$this->actives[0]->leave();
}
}
public function getNodeVisitors()
{
return [new ProfilerNodeVisitor(\get_class($this))];
}
public function getName()
{
return 'profiler';
}
}
class_alias('Twig\Extension\ProfilerExtension',
'Twig_Extension_Profiler');
twig/src/Extension/RuntimeExtensionInterface.php000064400000000506151161070030016126
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
/**
* @author Grégoire Pineau <lyrixx@lyrixx.info>
*/
interface RuntimeExtensionInterface
{
}
twig/src/Extension/SandboxExtension.php000064400000004524151161070030014264
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\NodeVisitor\SandboxNodeVisitor;
use Twig\Sandbox\SecurityPolicyInterface;
use Twig\TokenParser\SandboxTokenParser;
/**
* @final
*/
class SandboxExtension extends AbstractExtension
{
protected $sandboxedGlobally;
protected $sandboxed;
protected $policy;
public function __construct(SecurityPolicyInterface $policy, $sandboxed
= false)
{
$this->policy = $policy;
$this->sandboxedGlobally = $sandboxed;
}
public function getTokenParsers()
{
return [new SandboxTokenParser()];
}
public function getNodeVisitors()
{
return [new SandboxNodeVisitor()];
}
public function enableSandbox()
{
$this->sandboxed = true;
}
public function disableSandbox()
{
$this->sandboxed = false;
}
public function isSandboxed()
{
return $this->sandboxedGlobally || $this->sandboxed;
}
public function isSandboxedGlobally()
{
return $this->sandboxedGlobally;
}
public function setSecurityPolicy(SecurityPolicyInterface $policy)
{
$this->policy = $policy;
}
public function getSecurityPolicy()
{
return $this->policy;
}
public function checkSecurity($tags, $filters, $functions)
{
if ($this->isSandboxed()) {
$this->policy->checkSecurity($tags, $filters,
$functions);
}
}
public function checkMethodAllowed($obj, $method)
{
if ($this->isSandboxed()) {
$this->policy->checkMethodAllowed($obj, $method);
}
}
public function checkPropertyAllowed($obj, $method)
{
if ($this->isSandboxed()) {
$this->policy->checkPropertyAllowed($obj, $method);
}
}
public function ensureToStringAllowed($obj)
{
if ($this->isSandboxed() && \is_object($obj) &&
method_exists($obj, '__toString')) {
$this->policy->checkMethodAllowed($obj,
'__toString');
}
return $obj;
}
public function getName()
{
return 'sandbox';
}
}
class_alias('Twig\Extension\SandboxExtension',
'Twig_Extension_Sandbox');
twig/src/Extension/StagingExtension.php000064400000005702151161070030014261
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\TokenParser\TokenParserInterface;
/**
* Internal class.
*
* This class is used by \Twig\Environment as a staging area and must not
be used directly.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @internal
*/
class StagingExtension extends AbstractExtension
{
protected $functions = [];
protected $filters = [];
protected $visitors = [];
protected $tokenParsers = [];
protected $globals = [];
protected $tests = [];
public function addFunction($name, $function)
{
if (isset($this->functions[$name])) {
@trigger_error(sprintf('Overriding function "%s"
that is already registered is deprecated since version 1.30 and won\'t
be possible anymore in 2.0.', $name), E_USER_DEPRECATED);
}
$this->functions[$name] = $function;
}
public function getFunctions()
{
return $this->functions;
}
public function addFilter($name, $filter)
{
if (isset($this->filters[$name])) {
@trigger_error(sprintf('Overriding filter "%s"
that is already registered is deprecated since version 1.30 and won\'t
be possible anymore in 2.0.', $name), E_USER_DEPRECATED);
}
$this->filters[$name] = $filter;
}
public function getFilters()
{
return $this->filters;
}
public function addNodeVisitor(NodeVisitorInterface $visitor)
{
$this->visitors[] = $visitor;
}
public function getNodeVisitors()
{
return $this->visitors;
}
public function addTokenParser(TokenParserInterface $parser)
{
if (isset($this->tokenParsers[$parser->getTag()])) {
@trigger_error(sprintf('Overriding tag "%s" that
is already registered is deprecated since version 1.30 and won\'t be
possible anymore in 2.0.', $parser->getTag()), E_USER_DEPRECATED);
}
$this->tokenParsers[$parser->getTag()] = $parser;
}
public function getTokenParsers()
{
return $this->tokenParsers;
}
public function addGlobal($name, $value)
{
$this->globals[$name] = $value;
}
public function getGlobals()
{
return $this->globals;
}
public function addTest($name, $test)
{
if (isset($this->tests[$name])) {
@trigger_error(sprintf('Overriding test "%s"
that is already registered is deprecated since version 1.30 and won\'t
be possible anymore in 2.0.', $name), E_USER_DEPRECATED);
}
$this->tests[$name] = $test;
}
public function getTests()
{
return $this->tests;
}
public function getName()
{
return 'staging';
}
}
class_alias('Twig\Extension\StagingExtension',
'Twig_Extension_Staging');
twig/src/Extension/StringLoaderExtension.php000064400000002263151161070030015261
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extension {
use Twig\TwigFunction;
/**
* @final
*/
class StringLoaderExtension extends AbstractExtension
{
public function getFunctions()
{
return [
new TwigFunction('template_from_string',
'twig_template_from_string', ['needs_environment' =>
true]),
];
}
public function getName()
{
return 'string_loader';
}
}
class_alias('Twig\Extension\StringLoaderExtension',
'Twig_Extension_StringLoader');
}
namespace {
use Twig\Environment;
use Twig\TemplateWrapper;
/**
* Loads a template from a string.
*
* {{ include(template_from_string("Hello {{ name }}")) }}
*
* @param string $template A template as a string or object implementing
__toString()
* @param string $name An optional name of the template to be used in
error messages
*
* @return TemplateWrapper
*/
function twig_template_from_string(Environment $env, $template, $name =
null)
{
return $env->createTemplate((string) $template, $name);
}
}
twig/src/FileExtensionEscapingStrategy.php000064400000002761151161070030014767
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Default autoescaping strategy based on file names.
*
* This strategy sets the HTML as the default autoescaping strategy,
* but changes it based on the template name.
*
* Note that there is no runtime performance impact as the
* default autoescaping strategy is set at compilation time.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Lexer.php000064400000050144151161070030010073 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
/**
* Lexes a template string.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Lexer implements \Twig_LexerInterface
{
protected $tokens;
protected $code;
protected $cursor;
protected $lineno;
protected $end;
protected $state;
protected $states;
protected $brackets;
protected $env;
// to be renamed to $name in 2.0 (where it is private)
protected $filename;
protected $options;
protected $regexes;
protected $position;
protected $positions;
protected $currentVarBlockLine;
private $source;
const STATE_DATA = 0;
const STATE_BLOCK = 1;
const STATE_VAR = 2;
const STATE_STRING = 3;
const STATE_INTERPOLATION = 4;
const REGEX_NAME =
'/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/A';
const REGEX_NUMBER =
'/[0-9]+(?:\.[0-9]+)?([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*'.
'(?:end%s)'. // endraw or endverbatim
'\s*'.
'(?:'.
preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1],
'#').'\s*'. // -%}
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1],
'#').'['.$this->options['whitespace_line_chars'].']*'.
// ~%}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_block'][1],
'#'). // %}
')
}sx',
'operator' => $this->getOperatorRegex(),
// #}
'lex_comment' => '{
(?:'.
preg_quote($this->options['whitespace_trim']).preg_quote($this->options['tag_comment'][1],
'#').'\s*\n?'. // -#}\s*\n?
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_comment'][1],
'#').'['.$this->options['whitespace_line_chars'].']*'.
// ~#}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_comment'][1],
'#').'\n?'. // #}\n?
')
}sx',
// verbatim %}
'lex_block_raw' => '{
\s*
(raw|verbatim)
\s*
(?:'.
preg_quote($this->options['whitespace_trim'].$this->options['tag_block'][1],
'#').'\s*'. // -%}\s*
'|'.
preg_quote($this->options['whitespace_line_trim'].$this->options['tag_block'][1],
'#').'['.$this->options['whitespace_line_chars'].']*'.
// ~%}[ \t\0\x0B]*
'|'.
preg_quote($this->options['tag_block'][1],
'#'). // %}
')
}Asx',
'lex_block_line' =>
'{\s*line\s+(\d+)\s*'.preg_quote($this->options['tag_block'][1],
'#').'}As',
// {{ or {% or {#
'lex_tokens_start' => '{
('.
preg_quote($this->options['tag_variable'][0], '#').
// {{
'|'.
preg_quote($this->options['tag_block'][0],
'#'). // {%
'|'.
preg_quote($this->options['tag_comment'][0], '#').
// {#
')('.
preg_quote($this->options['whitespace_trim'], '#').
// -
'|'.
preg_quote($this->options['whitespace_line_trim'],
'#'). // ~
')?
}sx',
'interpolation_start' =>
'{'.preg_quote($this->options['interpolation'][0],
'#').'\s*}A',
'interpolation_end' =>
'{\s*'.preg_quote($this->options['interpolation'][1],
'#').'}A',
];
}
public function tokenize($code, $name = null)
{
if (!$code instanceof Source) {
@trigger_error(sprintf('Passing a string as the $code
argument of %s() is deprecated since version 1.27 and will be removed in
2.0. Pass a \Twig\Source instance instead.', __METHOD__),
E_USER_DEPRECATED);
$this->source = new Source($code, $name);
} else {
$this->source = $code;
}
if (((int) ini_get('mbstring.func_overload')) & 2) {
@trigger_error('Support for having
"mbstring.func_overload" different from 0 is deprecated version
1.29 and will be removed in 2.0.', E_USER_DEPRECATED);
}
if (\function_exists('mb_internal_encoding') &&
((int) ini_get('mbstring.func_overload')) & 2) {
$mbEncoding = mb_internal_encoding();
mb_internal_encoding('ASCII');
} else {
$mbEncoding = null;
}
$this->code = str_replace(["\r\n", "\r"],
"\n", $this->source->getCode());
$this->filename = $this->source->getName();
$this->cursor = 0;
$this->lineno = 1;
$this->end = \strlen($this->code);
$this->tokens = [];
$this->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);
if (!empty($this->brackets)) {
list($expect, $lineno) = array_pop($this->brackets);
throw new SyntaxError(sprintf('Unclosed
"%s".', $expect), $lineno, $this->source);
}
if ($mbEncoding) {
mb_internal_encoding($mbEncoding);
}
return new TokenStream($this->tokens, $this->source);
}
protected function lexData()
{
// if no matches are left we return the rest of the template as
simple text token
if ($this->position == \count($this->positions[0]) - 1) {
$this->pushToken(Token::TEXT_TYPE, substr($this->code,
$this->cursor));
$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, $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($match[1]);
// {% 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);
$this->pushState(self::STATE_BLOCK);
$this->currentVarBlockLine = $this->lineno;
}
break;
case $this->options['tag_variable'][0]:
$this->pushToken(Token::VAR_START_TYPE);
$this->pushState(self::STATE_VAR);
$this->currentVarBlockLine = $this->lineno;
break;
}
}
protected function lexBlock()
{
if (empty($this->brackets) &&
preg_match($this->regexes['lex_block'], $this->code,
$match, 0, $this->cursor)) {
$this->pushToken(Token::BLOCK_END_TYPE);
$this->moveCursor($match[0]);
$this->popState();
} else {
$this->lexExpression();
}
}
protected function lexVar()
{
if (empty($this->brackets) &&
preg_match($this->regexes['lex_var'], $this->code, $match,
0, $this->cursor)) {
$this->pushToken(Token::VAR_END_TYPE);
$this->moveCursor($match[0]);
$this->popState();
} else {
$this->lexExpression();
}
}
protected function lexExpression()
{
// whitespace
if (preg_match('/\s+/A', $this->code, $match, 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,
preg_replace('/\s+/', ' ', $match[0]));
$this->moveCursor($match[0]);
}
// names
elseif (preg_match(self::REGEX_NAME, $this->code, $match, 0,
$this->cursor)) {
$this->pushToken(Token::NAME_TYPE, $match[0]);
$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, $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,
$this->code[$this->cursor]);
++$this->cursor;
}
// strings
elseif (preg_match(self::REGEX_STRING, $this->code, $match, 0,
$this->cursor)) {
$this->pushToken(Token::STRING_TYPE,
stripcslashes(substr($match[0], 1, -1)));
$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);
}
}
protected function lexRawData($tag)
{
if ('raw' === $tag) {
@trigger_error(sprintf('Twig Tag "raw" is
deprecated since version 1.21. Use "verbatim" instead in %s at
line %d.', $this->filename, $this->lineno), E_USER_DEPRECATED);
}
if (!preg_match(str_replace('%s', $tag,
$this->regexes['lex_raw_data']), $this->code, $match,
PREG_OFFSET_CAPTURE, $this->cursor)) {
throw new SyntaxError(sprintf('Unexpected end of file:
Unclosed "%s" block.', $tag), $this->lineno,
$this->source);
}
$text = substr($this->code, $this->cursor, $match[0][1] -
$this->cursor);
$this->moveCursor($text.$match[0][0]);
// trim?
if (isset($match[1][0])) {
if ($this->options['whitespace_trim'] ===
$match[1][0]) {
// whitespace_trim detected ({%-, {{- or {#-)
$text = rtrim($text);
} else {
// whitespace_line_trim detected ({%~, {{~ or {#~)
// don't trim \r and \n
$text = rtrim($text, " \t\0\x0B");
}
}
$this->pushToken(Token::TEXT_TYPE, $text);
}
protected function lexComment()
{
if (!preg_match($this->regexes['lex_comment'],
$this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
throw new SyntaxError('Unclosed comment.',
$this->lineno, $this->source);
}
$this->moveCursor(substr($this->code, $this->cursor,
$match[0][1] - $this->cursor).$match[0][0]);
}
protected function lexString()
{
if (preg_match($this->regexes['interpolation_start'],
$this->code, $match, 0, $this->cursor)) {
$this->brackets[] =
[$this->options['interpolation'][0], $this->lineno];
$this->pushToken(Token::INTERPOLATION_START_TYPE);
$this->moveCursor($match[0]);
$this->pushState(self::STATE_INTERPOLATION);
} elseif (preg_match(self::REGEX_DQ_STRING_PART, $this->code,
$match, 0, $this->cursor) && \strlen($match[0]) > 0) {
$this->pushToken(Token::STRING_TYPE,
stripcslashes($match[0]));
$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);
}
}
protected function lexInterpolation()
{
$bracket = end($this->brackets);
if ($this->options['interpolation'][0] === $bracket[0]
&& preg_match($this->regexes['interpolation_end'],
$this->code, $match, 0, $this->cursor)) {
array_pop($this->brackets);
$this->pushToken(Token::INTERPOLATION_END_TYPE);
$this->moveCursor($match[0]);
$this->popState();
} else {
$this->lexExpression();
}
}
protected function pushToken($type, $value = '')
{
// do not push empty text tokens
if (Token::TEXT_TYPE === $type && '' === $value)
{
return;
}
$this->tokens[] = new Token($type, $value, $this->lineno);
}
protected function moveCursor($text)
{
$this->cursor += \strlen($text);
$this->lineno += substr_count($text, "\n");
}
protected function getOperatorRegex()
{
$operators = array_merge(
['='],
array_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';
}
protected function pushState($state)
{
$this->states[] = $this->state;
$this->state = $state;
}
protected 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');
twig/src/Loader/ArrayLoader.php000064400000005373151161070030012433
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Loader;
use Twig\Error\LoaderError;
use Twig\Source;
/**
* Loads a template from an array.
*
* When using this 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.
*
* This loader should only be used for unit testing.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ArrayLoader implements LoaderInterface, ExistsLoaderInterface,
SourceContextLoaderInterface
{
protected $templates = [];
/**
* @param array $templates An array of templates (keys are the names,
and values are the source code)
*/
public function __construct(array $templates = [])
{
$this->templates = $templates;
}
/**
* Adds or overrides a template.
*
* @param string $name The template name
* @param string $template The template source
*/
public function setTemplate($name, $template)
{
$this->templates[(string) $name] = $template;
}
public function getSource($name)
{
@trigger_error(sprintf('Calling "getSource" on
"%s" is deprecated since 1.27. Use getSourceContext()
instead.', \get_class($this)), E_USER_DEPRECATED);
$name = (string) $name;
if (!isset($this->templates[$name])) {
throw new LoaderError(sprintf('Template "%s" is
not defined.', $name));
}
return $this->templates[$name];
}
public function getSourceContext($name)
{
$name = (string) $name;
if (!isset($this->templates[$name])) {
throw new LoaderError(sprintf('Template "%s" is
not defined.', $name));
}
return new Source($this->templates[$name], $name);
}
public function exists($name)
{
return isset($this->templates[(string) $name]);
}
public function getCacheKey($name)
{
$name = (string) $name;
if (!isset($this->templates[$name])) {
throw new LoaderError(sprintf('Template "%s" is
not defined.', $name));
}
return $name.':'.$this->templates[$name];
}
public function isFresh($name, $time)
{
$name = (string) $name;
if (!isset($this->templates[$name])) {
throw new LoaderError(sprintf('Template "%s" is
not defined.', $name));
}
return true;
}
}
class_alias('Twig\Loader\ArrayLoader',
'Twig_Loader_Array');
twig/src/Loader/ChainLoader.php000064400000011051151161070030012365
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Loader;
use Twig\Error\LoaderError;
use Twig\Source;
/**
* Loads templates from other loaders.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ChainLoader implements LoaderInterface, ExistsLoaderInterface,
SourceContextLoaderInterface
{
private $hasSourceCache = [];
protected $loaders = [];
/**
* @param LoaderInterface[] $loaders
*/
public function __construct(array $loaders = [])
{
foreach ($loaders as $loader) {
$this->addLoader($loader);
}
}
public function addLoader(LoaderInterface $loader)
{
$this->loaders[] = $loader;
$this->hasSourceCache = [];
}
/**
* @return LoaderInterface[]
*/
public function getLoaders()
{
return $this->loaders;
}
public function getSource($name)
{
@trigger_error(sprintf('Calling "getSource" on
"%s" is deprecated since 1.27. Use getSourceContext()
instead.', \get_class($this)), E_USER_DEPRECATED);
$exceptions = [];
foreach ($this->loaders as $loader) {
if ($loader instanceof ExistsLoaderInterface &&
!$loader->exists($name)) {
continue;
}
try {
return $loader->getSource($name);
} catch (LoaderError $e) {
$exceptions[] = $e->getMessage();
}
}
throw new LoaderError(sprintf('Template "%s" is not
defined%s.', $name, $exceptions ? ' ('.implode(',
', $exceptions).')' : ''));
}
public function getSourceContext($name)
{
$exceptions = [];
foreach ($this->loaders as $loader) {
if ($loader instanceof ExistsLoaderInterface &&
!$loader->exists($name)) {
continue;
}
try {
if ($loader instanceof SourceContextLoaderInterface) {
return $loader->getSourceContext($name);
}
return new Source($loader->getSource($name), $name);
} catch (LoaderError $e) {
$exceptions[] = $e->getMessage();
}
}
throw new LoaderError(sprintf('Template "%s" is not
defined%s.', $name, $exceptions ? ' ('.implode(',
', $exceptions).')' : ''));
}
public function exists($name)
{
$name = (string) $name;
if (isset($this->hasSourceCache[$name])) {
return $this->hasSourceCache[$name];
}
foreach ($this->loaders as $loader) {
if ($loader instanceof ExistsLoaderInterface) {
if ($loader->exists($name)) {
return $this->hasSourceCache[$name] = true;
}
continue;
}
try {
if ($loader instanceof SourceContextLoaderInterface) {
$loader->getSourceContext($name);
} else {
$loader->getSource($name);
}
return $this->hasSourceCache[$name] = true;
} catch (LoaderError $e) {
}
}
return $this->hasSourceCache[$name] = false;
}
public function getCacheKey($name)
{
$exceptions = [];
foreach ($this->loaders as $loader) {
if ($loader instanceof ExistsLoaderInterface &&
!$loader->exists($name)) {
continue;
}
try {
return $loader->getCacheKey($name);
} catch (LoaderError $e) {
$exceptions[] = \get_class($loader).':
'.$e->getMessage();
}
}
throw new LoaderError(sprintf('Template "%s" is not
defined%s.', $name, $exceptions ? ' ('.implode(',
', $exceptions).')' : ''));
}
public function isFresh($name, $time)
{
$exceptions = [];
foreach ($this->loaders as $loader) {
if ($loader instanceof ExistsLoaderInterface &&
!$loader->exists($name)) {
continue;
}
try {
return $loader->isFresh($name, $time);
} catch (LoaderError $e) {
$exceptions[] = \get_class($loader).':
'.$e->getMessage();
}
}
throw new LoaderError(sprintf('Template "%s" is not
defined%s.', $name, $exceptions ? ' ('.implode(',
', $exceptions).')' : ''));
}
}
class_alias('Twig\Loader\ChainLoader',
'Twig_Loader_Chain');
twig/src/Loader/ExistsLoaderInterface.php000064400000001423151161070030014445
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Loader;
/**
* Adds an exists() method for loaders.
*
* @author Florin Patan <florinpatan@gmail.com>
*
* @deprecated since 1.12 (to be removed in 3.0)
*/
interface ExistsLoaderInterface
{
/**
* Check if we have the source code of a template, given its name.
*
* @param string $name The name of the template to check if we can load
*
* @return bool If the template source code is handled by this loader
or not
*/
public function exists($name);
}
class_alias('Twig\Loader\ExistsLoaderInterface',
'Twig_ExistsLoaderInterface');
twig/src/Loader/FilesystemLoader.php000064400000022263151161070030013476
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Loader;
use Twig\Error\LoaderError;
use Twig\Source;
/**
* Loads template from the filesystem.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FilesystemLoader implements LoaderInterface, ExistsLoaderInterface,
SourceContextLoaderInterface
{
/** Identifier of the main namespace. */
const MAIN_NAMESPACE = '__main__';
protected $paths = [];
protected $cache = [];
protected $errorCache = [];
private $rootPath;
/**
* @param string|array $paths A path or an array of paths where to
look for templates
* @param string|null $rootPath The root path common to all relative
paths (null for getcwd())
*/
public function __construct($paths = [], $rootPath = null)
{
$this->rootPath = (null === $rootPath ? getcwd() :
$rootPath).\DIRECTORY_SEPARATOR;
if (false !== $realPath = realpath($rootPath)) {
$this->rootPath = $realPath.\DIRECTORY_SEPARATOR;
}
if ($paths) {
$this->setPaths($paths);
}
}
/**
* Returns the paths to the templates.
*
* @param string $namespace A path namespace
*
* @return array The array of paths where to look for templates
*/
public function getPaths($namespace = self::MAIN_NAMESPACE)
{
return isset($this->paths[$namespace]) ?
$this->paths[$namespace] : [];
}
/**
* Returns the path namespaces.
*
* The main namespace is always defined.
*
* @return array The array of defined namespaces
*/
public function getNamespaces()
{
return array_keys($this->paths);
}
/**
* Sets the paths where templates are stored.
*
* @param string|array $paths A path or an array of paths where to
look for templates
* @param string $namespace A path namespace
*/
public function setPaths($paths, $namespace = self::MAIN_NAMESPACE)
{
if (!\is_array($paths)) {
$paths = [$paths];
}
$this->paths[$namespace] = [];
foreach ($paths as $path) {
$this->addPath($path, $namespace);
}
}
/**
* Adds a path where templates are stored.
*
* @param string $path A path where to look for templates
* @param string $namespace A path namespace
*
* @throws LoaderError
*/
public function addPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = [];
$checkPath = $this->isAbsolutePath($path) ? $path :
$this->rootPath.$path;
if (!is_dir($checkPath)) {
throw new LoaderError(sprintf('The "%s"
directory does not exist ("%s").', $path, $checkPath));
}
$this->paths[$namespace][] = rtrim($path, '/\\');
}
/**
* Prepends a path where templates are stored.
*
* @param string $path A path where to look for templates
* @param string $namespace A path namespace
*
* @throws LoaderError
*/
public function prependPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = [];
$checkPath = $this->isAbsolutePath($path) ? $path :
$this->rootPath.$path;
if (!is_dir($checkPath)) {
throw new LoaderError(sprintf('The "%s"
directory does not exist ("%s").', $path, $checkPath));
}
$path = rtrim($path, '/\\');
if (!isset($this->paths[$namespace])) {
$this->paths[$namespace][] = $path;
} else {
array_unshift($this->paths[$namespace], $path);
}
}
public function getSource($name)
{
@trigger_error(sprintf('Calling "getSource" on
"%s" is deprecated since 1.27. Use getSourceContext()
instead.', \get_class($this)), E_USER_DEPRECATED);
if (null === ($path = $this->findTemplate($name)) || false ===
$path) {
return '';
}
return file_get_contents($path);
}
public function getSourceContext($name)
{
if (null === ($path = $this->findTemplate($name)) || false ===
$path) {
return new Source('', $name, '');
}
return new Source(file_get_contents($path), $name, $path);
}
public function getCacheKey($name)
{
if (null === ($path = $this->findTemplate($name)) || false ===
$path) {
return '';
}
$len = \strlen($this->rootPath);
if (0 === strncmp($this->rootPath, $path, $len)) {
return substr($path, $len);
}
return $path;
}
public function exists($name)
{
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return true;
}
try {
return null !== ($path = $this->findTemplate($name, false))
&& false !== $path;
} catch (LoaderError $e) {
@trigger_error(sprintf('In %s::findTemplate(), you must
accept a second argument that when set to "false" returns
"false" instead of throwing an exception. Not supporting this
argument is deprecated since version 1.27.', \get_class($this)),
E_USER_DEPRECATED);
return false;
}
}
public function isFresh($name, $time)
{
// false support to be removed in 3.0
if (null === ($path = $this->findTemplate($name)) || false ===
$path) {
return false;
}
return filemtime($path) < $time;
}
/**
* Checks if the template can be found.
*
* @param string $name The template name
*
* @return string|false|null The template name or false/null
*/
protected function findTemplate($name)
{
$throw = \func_num_args() > 1 ? func_get_arg(1) : true;
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return $this->cache[$name];
}
if (isset($this->errorCache[$name])) {
if (!$throw) {
return false;
}
throw new LoaderError($this->errorCache[$name]);
}
try {
$this->validateName($name);
list($namespace, $shortname) = $this->parseName($name);
} catch (LoaderError $e) {
if (!$throw) {
return false;
}
throw $e;
}
if (!isset($this->paths[$namespace])) {
$this->errorCache[$name] = sprintf('There are no
registered paths for namespace "%s".', $namespace);
if (!$throw) {
return false;
}
throw new LoaderError($this->errorCache[$name]);
}
foreach ($this->paths[$namespace] as $path) {
if (!$this->isAbsolutePath($path)) {
$path = $this->rootPath.$path;
}
if (is_file($path.'/'.$shortname)) {
if (false !== $realpath =
realpath($path.'/'.$shortname)) {
return $this->cache[$name] = $realpath;
}
return $this->cache[$name] =
$path.'/'.$shortname;
}
}
$this->errorCache[$name] = sprintf('Unable to find template
"%s" (looked into: %s).', $name, implode(', ',
$this->paths[$namespace]));
if (!$throw) {
return false;
}
throw new LoaderError($this->errorCache[$name]);
}
protected function parseName($name, $default = self::MAIN_NAMESPACE)
{
if (isset($name[0]) && '@' == $name[0]) {
if (false === $pos = strpos($name, '/')) {
throw new LoaderError(sprintf('Malformed namespaced
template name "%s" (expecting
"@namespace/template_name").', $name));
}
$namespace = substr($name, 1, $pos - 1);
$shortname = substr($name, $pos + 1);
return [$namespace, $shortname];
}
return [$default, $name];
}
protected function normalizeName($name)
{
return preg_replace('#/{2,}#', '/',
str_replace('\\', '/', (string) $name));
}
protected function validateName($name)
{
if (false !== strpos($name, "\0")) {
throw new LoaderError('A template name cannot contain NUL
bytes.');
}
$name = ltrim($name, '/');
$parts = explode('/', $name);
$level = 0;
foreach ($parts as $part) {
if ('..' === $part) {
--$level;
} elseif ('.' !== $part) {
++$level;
}
if ($level < 0) {
throw new LoaderError(sprintf('Looks like you try to
load a template outside configured directories (%s).', $name));
}
}
}
private function isAbsolutePath($file)
{
return strspn($file, '/\\', 0, 1)
|| (\strlen($file) > 3 && ctype_alpha($file[0])
&& ':' === substr($file, 1, 1)
&& strspn($file, '/\\', 2, 1)
)
|| null !== parse_url($file, PHP_URL_SCHEME)
;
}
}
class_alias('Twig\Loader\FilesystemLoader',
'Twig_Loader_Filesystem');
twig/src/Loader/LoaderInterface.php000064400000003043151161070030013245
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Loader;
use Twig\Error\LoaderError;
/**
* Interface all loaders must implement.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface LoaderInterface
{
/**
* Gets the source code of a template, given its name.
*
* @param string $name The name of the template to load
*
* @return string The template source code
*
* @throws LoaderError When $name is not found
*
* @deprecated since 1.27 (to be removed in 2.0), implement
Twig\Loader\SourceContextLoaderInterface
*/
public function getSource($name);
/**
* Gets the cache key to use for the cache for a given template name.
*
* @param string $name The name of the template to load
*
* @return string The cache key
*
* @throws LoaderError When $name is not found
*/
public function getCacheKey($name);
/**
* Returns true if the template is still fresh.
*
* @param string $name The template name
* @param int $time Timestamp of the last modification time of the
* cached template
*
* @return bool true if the template is fresh, false otherwise
*
* @throws LoaderError When $name is not found
*/
public function isFresh($name, $time);
}
class_alias('Twig\Loader\LoaderInterface',
'Twig_LoaderInterface');
twig/src/Loader/SourceContextLoaderInterface.php000064400000001520151161070030015771
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Loader;
use Twig\Error\LoaderError;
use Twig\Source;
/**
* Adds a getSourceContext() method for loaders.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @deprecated since 1.27 (to be removed in 3.0)
*/
interface SourceContextLoaderInterface
{
/**
* Returns the source context for a given template logical name.
*
* @param string $name The template logical name
*
* @return Source
*
* @throws LoaderError When $name is not found
*/
public function getSourceContext($name);
}
class_alias('Twig\Loader\SourceContextLoaderInterface',
'Twig_SourceContextLoaderInterface');
twig/src/Markup.php000064400000001462151161070030010252 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Marks a content as safe.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Markup implements \Countable
{
protected $content;
protected $charset;
public function __construct($content, $charset)
{
$this->content = (string) $content;
$this->charset = $charset;
}
public function __toString()
{
return $this->content;
}
public function count()
{
return \function_exists('mb_get_info') ?
mb_strlen($this->content, $this->charset) :
\strlen($this->content);
}
}
class_alias('Twig\Markup', 'Twig_Markup');
twig/src/Node/AutoEscapeNode.php000064400000001627151161070030012542
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents an autoescape node.
*
* The value is the escaping strategy (can be html, js, ...)
*
* The true value is equivalent to html.
*
* If autoescaping is disabled, then the value is false.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AutoEscapeNode extends Node
{
public function __construct($value, \Twig_NodeInterface $body, $lineno,
$tag = 'autoescape')
{
parent::__construct(['body' => $body],
['value' => $value], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler->subcompile($this->getNode('body'));
}
}
class_alias('Twig\Node\AutoEscapeNode',
'Twig_Node_AutoEscape');
twig/src/Node/BlockNode.php000064400000002005151161070030011532
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents a block node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class BlockNode extends Node
{
public function __construct($name, \Twig_NodeInterface $body, $lineno,
$tag = null)
{
parent::__construct(['body' => $body],
['name' => $name], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write(sprintf("public function block_%s(\$context,
array \$blocks = [])\n", $this->getAttribute('name')),
"{\n")
->indent()
;
$compiler
->subcompile($this->getNode('body'))
->outdent()
->write("}\n\n")
;
}
}
class_alias('Twig\Node\BlockNode', 'Twig_Node_Block');
twig/src/Node/BlockReferenceNode.php000064400000001561151161070030013357
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents a block call node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class BlockReferenceNode extends Node implements NodeOutputInterface
{
public function __construct($name, $lineno, $tag = null)
{
parent::__construct([], ['name' => $name], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write(sprintf("\$this->displayBlock('%s', \$context,
\$blocks);\n", $this->getAttribute('name')))
;
}
}
class_alias('Twig\Node\BlockReferenceNode',
'Twig_Node_BlockReference');
twig/src/Node/BodyNode.php000064400000000615151161070030011402
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
/**
* Represents a body node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class BodyNode extends Node
{
}
class_alias('Twig\Node\BodyNode', 'Twig_Node_Body');
twig/src/Node/CheckSecurityNode.php000064400000006025151161070030013253
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class CheckSecurityNode extends Node
{
protected $usedFilters;
protected $usedTags;
protected $usedFunctions;
public function __construct(array $usedFilters, array $usedTags, array
$usedFunctions)
{
$this->usedFilters = $usedFilters;
$this->usedTags = $usedTags;
$this->usedFunctions = $usedFunctions;
parent::__construct();
}
public function compile(Compiler $compiler)
{
$tags = $filters = $functions = [];
foreach (['tags', 'filters',
'functions'] as $type) {
foreach ($this->{'used'.ucfirst($type)} as $name
=> $node) {
if ($node instanceof Node) {
${$type}[$name] = $node->getTemplateLine();
} else {
${$type}[$node] = null;
}
}
}
$compiler
->write("\$this->sandbox =
\$this->env->getExtension('\Twig\Extension\SandboxExtension');\n")
->write('$tags =
')->repr(array_filter($tags))->raw(";\n")
->write('$filters =
')->repr(array_filter($filters))->raw(";\n")
->write('$functions =
')->repr(array_filter($functions))->raw(";\n\n")
->write("try {\n")
->indent()
->write("\$this->sandbox->checkSecurity(\n")
->indent()
->write(!$tags ? "[],\n" :
"['".implode("', '",
array_keys($tags))."'],\n")
->write(!$filters ? "[],\n" :
"['".implode("', '",
array_keys($filters))."'],\n")
->write(!$functions ? "[]\n" :
"['".implode("', '",
array_keys($functions))."']\n")
->outdent()
->write(");\n")
->outdent()
->write("} catch (SecurityError \$e) {\n")
->indent()
->write("\$e->setSourceContext(\$this->getSourceContext());\n\n")
->write("if (\$e instanceof SecurityNotAllowedTagError
&& isset(\$tags[\$e->getTagName()])) {\n")
->indent()
->write("\$e->setTemplateLine(\$tags[\$e->getTagName()]);\n")
->outdent()
->write("} elseif (\$e instanceof
SecurityNotAllowedFilterError &&
isset(\$filters[\$e->getFilterName()])) {\n")
->indent()
->write("\$e->setTemplateLine(\$filters[\$e->getFilterName()]);\n")
->outdent()
->write("} elseif (\$e instanceof
SecurityNotAllowedFunctionError &&
isset(\$functions[\$e->getFunctionName()])) {\n")
->indent()
->write("\$e->setTemplateLine(\$functions[\$e->getFunctionName()]);\n")
->outdent()
->write("}\n\n")
->write("throw \$e;\n")
->outdent()
->write("}\n\n")
;
}
}
class_alias('Twig\Node\CheckSecurityNode',
'Twig_Node_CheckSecurity');
twig/src/Node/CheckToStringNode.php000064400000002163151161070030013214
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
/**
* Checks if casting an expression to __toString() is allowed by the
sandbox.
*
* For instance, when there is a simple Print statement, like {{ article
}},
* and if the sandbox is enabled, we need to check that the __toString()
* method is allowed if 'article' is an object. The same goes for
{{ article|upper }}
* or {{ random(article) }}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class CheckToStringNode extends AbstractExpression
{
public function __construct(AbstractExpression $expr)
{
parent::__construct(['expr' => $expr], [],
$expr->getTemplateLine(), $expr->getNodeTag());
}
public function compile(Compiler $compiler)
{
$compiler
->raw('$this->sandbox->ensureToStringAllowed(')
->subcompile($this->getNode('expr'))
->raw(')')
;
}
}
twig/src/Node/DeprecatedNode.php000064400000002632151161070030012546
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\ConstantExpression;
/**
* Represents a deprecated node.
*
* @author Yonel Ceruto <yonelceruto@gmail.com>
*/
class DeprecatedNode extends Node
{
public function __construct(AbstractExpression $expr, $lineno, $tag =
null)
{
parent::__construct(['expr' => $expr], [], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
$compiler->addDebugInfo($this);
$expr = $this->getNode('expr');
if ($expr instanceof ConstantExpression) {
$compiler->write('@trigger_error(')
->subcompile($expr);
} else {
$varName = $compiler->getVarName();
$compiler->write(sprintf('$%s = ', $varName))
->subcompile($expr)
->raw(";\n")
->write(sprintf('@trigger_error($%s',
$varName));
}
$compiler
->raw('.')
->string(sprintf(' ("%s" at line %d).',
$this->getTemplateName(), $this->getTemplateLine()))
->raw(", E_USER_DEPRECATED);\n")
;
}
}
class_alias('Twig\Node\DeprecatedNode',
'Twig_Node_Deprecated');
twig/src/Node/DoNode.php000064400000001502151161070030011043
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
/**
* Represents a do node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DoNode extends Node
{
public function __construct(AbstractExpression $expr, $lineno, $tag =
null)
{
parent::__construct(['expr' => $expr], [], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('')
->subcompile($this->getNode('expr'))
->raw(";\n")
;
}
}
class_alias('Twig\Node\DoNode', 'Twig_Node_Do');
twig/src/Node/EmbedNode.php000064400000003015151161070030011516
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\ConstantExpression;
/**
* Represents an embed node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class EmbedNode extends IncludeNode
{
// we don't inject the module to avoid node visitors to traverse
it twice (as it will be already visited in the main module)
public function __construct($name, $index, AbstractExpression
$variables = null, $only = false, $ignoreMissing = false, $lineno, $tag =
null)
{
parent::__construct(new ConstantExpression('not_used',
$lineno), $variables, $only, $ignoreMissing, $lineno, $tag);
$this->setAttribute('name', $name);
// to be removed in 2.0, used name instead
$this->setAttribute('filename', $name);
$this->setAttribute('index', $index);
}
protected function addGetTemplate(Compiler $compiler)
{
$compiler
->write('$this->loadTemplate(')
->string($this->getAttribute('name'))
->raw(', ')
->repr($this->getTemplateName())
->raw(', ')
->repr($this->getTemplateLine())
->raw(', ')
->string($this->getAttribute('index'))
->raw(')')
;
}
}
class_alias('Twig\Node\EmbedNode', 'Twig_Node_Embed');
twig/src/Node/Expression/AbstractExpression.php000064400000001025151161070030015655
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Node\Node;
/**
* Abstract class for all nodes that represents an expression.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class AbstractExpression extends Node
{
}
class_alias('Twig\Node\Expression\AbstractExpression',
'Twig_Node_Expression');
twig/src/Node/Expression/ArrayExpression.php000064400000004415151161070030015176
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
class ArrayExpression extends AbstractExpression
{
protected $index;
public function __construct(array $elements, $lineno)
{
parent::__construct($elements, [], $lineno);
$this->index = -1;
foreach ($this->getKeyValuePairs() as $pair) {
if ($pair['key'] instanceof ConstantExpression
&& ctype_digit((string)
$pair['key']->getAttribute('value')) &&
$pair['key']->getAttribute('value') >
$this->index) {
$this->index =
$pair['key']->getAttribute('value');
}
}
}
public function getKeyValuePairs()
{
$pairs = [];
foreach (array_chunk($this->nodes, 2) as $pair) {
$pairs[] = [
'key' => $pair[0],
'value' => $pair[1],
];
}
return $pairs;
}
public function hasElement(AbstractExpression $key)
{
foreach ($this->getKeyValuePairs() as $pair) {
// we compare the string representation of the keys
// to avoid comparing the line numbers which are not relevant
here.
if ((string) $key === (string) $pair['key']) {
return true;
}
}
return false;
}
public function addElement(AbstractExpression $value,
AbstractExpression $key = null)
{
if (null === $key) {
$key = new ConstantExpression(++$this->index,
$value->getTemplateLine());
}
array_push($this->nodes, $key, $value);
}
public function compile(Compiler $compiler)
{
$compiler->raw('[');
$first = true;
foreach ($this->getKeyValuePairs() as $pair) {
if (!$first) {
$compiler->raw(', ');
}
$first = false;
$compiler
->subcompile($pair['key'])
->raw(' => ')
->subcompile($pair['value'])
;
}
$compiler->raw(']');
}
}
class_alias('Twig\Node\Expression\ArrayExpression',
'Twig_Node_Expression_Array');
twig/src/Node/Expression/ArrowFunctionExpression.php000064400000003034151161070030016714
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\Node\Node;
/**
* Represents an arrow function.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ArrowFunctionExpression extends AbstractExpression
{
public function __construct(AbstractExpression $expr, Node $names,
$lineno, $tag = null)
{
parent::__construct(['expr' => $expr,
'names' => $names], [], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->raw('function (')
;
foreach ($this->getNode('names') as $i => $name) {
if ($i) {
$compiler->raw(', ');
}
$compiler
->raw('$__')
->raw($name->getAttribute('name'))
->raw('__')
;
}
$compiler
->raw(') use ($context) { ')
;
foreach ($this->getNode('names') as $name) {
$compiler
->raw('$context["')
->raw($name->getAttribute('name'))
->raw('"] = $__')
->raw($name->getAttribute('name'))
->raw('__; ')
;
}
$compiler
->raw('return ')
->subcompile($this->getNode('expr'))
->raw('; }')
;
}
}
twig/src/Node/Expression/AssignNameExpression.php000064400000001151151161070030016137
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
class AssignNameExpression extends NameExpression
{
public function compile(Compiler $compiler)
{
$compiler
->raw('$context[')
->string($this->getAttribute('name'))
->raw(']')
;
}
}
class_alias('Twig\Node\Expression\AssignNameExpression',
'Twig_Node_Expression_AssignName');
twig/src/Node/Expression/Binary/AbstractBinary.php000064400000002061151161070030016167
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
abstract class AbstractBinary extends AbstractExpression
{
public function __construct(\Twig_NodeInterface $left,
\Twig_NodeInterface $right, $lineno)
{
parent::__construct(['left' => $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');
twig/src/Node/Expression/Binary/AddBinary.php000064400000001002151161070030015106
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class AddBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('+');
}
}
class_alias('Twig\Node\Expression\Binary\AddBinary',
'Twig_Node_Expression_Binary_Add');
twig/src/Node/Expression/Binary/AndBinary.php000064400000001003151161070030015121
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class AndBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('&&');
}
}
class_alias('Twig\Node\Expression\Binary\AndBinary',
'Twig_Node_Expression_Binary_And');
twig/src/Node/Expression/Binary/BitwiseAndBinary.php000064400000001027151161070030016456
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class BitwiseAndBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('&');
}
}
class_alias('Twig\Node\Expression\Binary\BitwiseAndBinary',
'Twig_Node_Expression_Binary_BitwiseAnd');
twig/src/Node/Expression/Binary/BitwiseOrBinary.php000064400000001024151161070030016331
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class BitwiseOrBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('|');
}
}
class_alias('Twig\Node\Expression\Binary\BitwiseOrBinary',
'Twig_Node_Expression_Binary_BitwiseOr');
twig/src/Node/Expression/Binary/BitwiseXorBinary.php000064400000001027151161070030016524
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class BitwiseXorBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('^');
}
}
class_alias('Twig\Node\Expression\Binary\BitwiseXorBinary',
'Twig_Node_Expression_Binary_BitwiseXor');
twig/src/Node/Expression/Binary/ConcatBinary.php000064400000001013151161070030015627
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class ConcatBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('.');
}
}
class_alias('Twig\Node\Expression\Binary\ConcatBinary',
'Twig_Node_Expression_Binary_Concat');
twig/src/Node/Expression/Binary/DivBinary.php000064400000001002151161070030015140
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class DivBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('/');
}
}
class_alias('Twig\Node\Expression\Binary\DivBinary',
'Twig_Node_Expression_Binary_Div');
twig/src/Node/Expression/Binary/EndsWithBinary.php000064400000001753151161070030016160
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class EndsWithBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
$left = $compiler->getVarName();
$right = $compiler->getVarName();
$compiler
->raw(sprintf('(is_string($%s = ', $left))
->subcompile($this->getNode('left'))
->raw(sprintf(') && is_string($%s = ',
$right))
->subcompile($this->getNode('right'))
->raw(sprintf(') && (\'\' === $%2$s
|| $%2$s === substr($%1$s, -strlen($%2$s))))', $left, $right))
;
}
public function operator(Compiler $compiler)
{
return $compiler->raw('');
}
}
class_alias('Twig\Node\Expression\Binary\EndsWithBinary',
'Twig_Node_Expression_Binary_EndsWith');
twig/src/Node/Expression/Binary/EqualBinary.php000064400000000763151161070030015502
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class EqualBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('==');
}
}
class_alias('Twig\Node\Expression\Binary\EqualBinary',
'Twig_Node_Expression_Binary_Equal');
twig/src/Node/Expression/Binary/FloorDivBinary.php000064400000001241151161070030016147
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class FloorDivBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
$compiler->raw('(int) floor(');
parent::compile($compiler);
$compiler->raw(')');
}
public function operator(Compiler $compiler)
{
return $compiler->raw('/');
}
}
class_alias('Twig\Node\Expression\Binary\FloorDivBinary',
'Twig_Node_Expression_Binary_FloorDiv');
twig/src/Node/Expression/Binary/GreaterBinary.php000064400000000770151161070030016022
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class GreaterBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('>');
}
}
class_alias('Twig\Node\Expression\Binary\GreaterBinary',
'Twig_Node_Expression_Binary_Greater');
twig/src/Node/Expression/Binary/GreaterEqualBinary.php000064400000001010151161070030016776
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class GreaterEqualBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('>=');
}
}
class_alias('Twig\Node\Expression\Binary\GreaterEqualBinary',
'Twig_Node_Expression_Binary_GreaterEqual');
twig/src/Node/Expression/Binary/InBinary.php000064400000001372151161070030014776
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class InBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
$compiler
->raw('twig_in_filter(')
->subcompile($this->getNode('left'))
->raw(', ')
->subcompile($this->getNode('right'))
->raw(')')
;
}
public function operator(Compiler $compiler)
{
return $compiler->raw('in');
}
}
class_alias('Twig\Node\Expression\Binary\InBinary',
'Twig_Node_Expression_Binary_In');
twig/src/Node/Expression/Binary/LessBinary.php000064400000000757151161070030015344
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class LessBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('<');
}
}
class_alias('Twig\Node\Expression\Binary\LessBinary',
'Twig_Node_Expression_Binary_Less');
twig/src/Node/Expression/Binary/LessEqualBinary.php000064400000000777151161070030016336
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class LessEqualBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('<=');
}
}
class_alias('Twig\Node\Expression\Binary\LessEqualBinary',
'Twig_Node_Expression_Binary_LessEqual');
twig/src/Node/Expression/Binary/MatchesBinary.php000064400000001403151161070030016007
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class MatchesBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
$compiler
->raw('preg_match(')
->subcompile($this->getNode('right'))
->raw(', ')
->subcompile($this->getNode('left'))
->raw(')')
;
}
public function operator(Compiler $compiler)
{
return $compiler->raw('');
}
}
class_alias('Twig\Node\Expression\Binary\MatchesBinary',
'Twig_Node_Expression_Binary_Matches');
twig/src/Node/Expression/Binary/ModBinary.php000064400000001002151161070030015135
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class ModBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('%');
}
}
class_alias('Twig\Node\Expression\Binary\ModBinary',
'Twig_Node_Expression_Binary_Mod');
twig/src/Node/Expression/Binary/MulBinary.php000064400000001002151161070030015153
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class MulBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('*');
}
}
class_alias('Twig\Node\Expression\Binary\MulBinary',
'Twig_Node_Expression_Binary_Mul');
twig/src/Node/Expression/Binary/NotEqualBinary.php000064400000000774151161070030016165
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class NotEqualBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('!=');
}
}
class_alias('Twig\Node\Expression\Binary\NotEqualBinary',
'Twig_Node_Expression_Binary_NotEqual');
twig/src/Node/Expression/Binary/NotInBinary.php000064400000001410151161070030015450
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class NotInBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
$compiler
->raw('!twig_in_filter(')
->subcompile($this->getNode('left'))
->raw(', ')
->subcompile($this->getNode('right'))
->raw(')')
;
}
public function operator(Compiler $compiler)
{
return $compiler->raw('not in');
}
}
class_alias('Twig\Node\Expression\Binary\NotInBinary',
'Twig_Node_Expression_Binary_NotIn');
twig/src/Node/Expression/Binary/OrBinary.php000064400000001000151161070030014774
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class OrBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('||');
}
}
class_alias('Twig\Node\Expression\Binary\OrBinary',
'Twig_Node_Expression_Binary_Or');
twig/src/Node/Expression/Binary/PowerBinary.php000064400000001532151161070030015522
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class PowerBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
if (\PHP_VERSION_ID >= 50600) {
return parent::compile($compiler);
}
$compiler
->raw('pow(')
->subcompile($this->getNode('left'))
->raw(', ')
->subcompile($this->getNode('right'))
->raw(')')
;
}
public function operator(Compiler $compiler)
{
return $compiler->raw('**');
}
}
class_alias('Twig\Node\Expression\Binary\PowerBinary',
'Twig_Node_Expression_Binary_Power');
twig/src/Node/Expression/Binary/RangeBinary.php000064400000001372151161070030015464
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class RangeBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
$compiler
->raw('range(')
->subcompile($this->getNode('left'))
->raw(', ')
->subcompile($this->getNode('right'))
->raw(')')
;
}
public function operator(Compiler $compiler)
{
return $compiler->raw('..');
}
}
class_alias('Twig\Node\Expression\Binary\RangeBinary',
'Twig_Node_Expression_Binary_Range');
twig/src/Node/Expression/Binary/StartsWithBinary.php000064400000001744151161070030016547
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class StartsWithBinary extends AbstractBinary
{
public function compile(Compiler $compiler)
{
$left = $compiler->getVarName();
$right = $compiler->getVarName();
$compiler
->raw(sprintf('(is_string($%s = ', $left))
->subcompile($this->getNode('left'))
->raw(sprintf(') && is_string($%s = ',
$right))
->subcompile($this->getNode('right'))
->raw(sprintf(') && (\'\' === $%2$s
|| 0 === strpos($%1$s, $%2$s)))', $left, $right))
;
}
public function operator(Compiler $compiler)
{
return $compiler->raw('');
}
}
class_alias('Twig\Node\Expression\Binary\StartsWithBinary',
'Twig_Node_Expression_Binary_StartsWith');
twig/src/Node/Expression/Binary/SubBinary.php000064400000001002151161070030015147
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Binary;
use Twig\Compiler;
class SubBinary extends AbstractBinary
{
public function operator(Compiler $compiler)
{
return $compiler->raw('-');
}
}
class_alias('Twig\Node\Expression\Binary\SubBinary',
'Twig_Node_Expression_Binary_Sub');
twig/src/Node/Expression/BlockReferenceExpression.php000064400000005202151161070030016764
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\Node\Node;
/**
* Represents a block call node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class BlockReferenceExpression extends AbstractExpression
{
/**
* @param Node|null $template
*/
public function __construct(\Twig_NodeInterface $name, $template =
null, $lineno, $tag = null)
{
if (\is_bool($template)) {
@trigger_error(sprintf('The %s method
"$asString" argument is deprecated since version 1.28 and will be
removed in 2.0.', __METHOD__), E_USER_DEPRECATED);
$template = null;
}
$nodes = ['name' => $name];
if (null !== $template) {
$nodes['template'] = $template;
}
parent::__construct($nodes, ['is_defined_test' =>
false, 'output' => false], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
if ($this->getAttribute('is_defined_test')) {
$this->compileTemplateCall($compiler, 'hasBlock');
} else {
if ($this->getAttribute('output')) {
$compiler->addDebugInfo($this);
$this
->compileTemplateCall($compiler,
'displayBlock')
->raw(";\n");
} else {
$this->compileTemplateCall($compiler,
'renderBlock');
}
}
}
private function compileTemplateCall(Compiler $compiler, $method)
{
if (!$this->hasNode('template')) {
$compiler->write('$this');
} else {
$compiler
->write('$this->loadTemplate(')
->subcompile($this->getNode('template'))
->raw(', ')
->repr($this->getTemplateName())
->raw(', ')
->repr($this->getTemplateLine())
->raw(')')
;
}
$compiler->raw(sprintf('->%s', $method));
$this->compileBlockArguments($compiler);
return $compiler;
}
private function compileBlockArguments(Compiler $compiler)
{
$compiler
->raw('(')
->subcompile($this->getNode('name'))
->raw(', $context');
if (!$this->hasNode('template')) {
$compiler->raw(', $blocks');
}
return $compiler->raw(')');
}
}
class_alias('Twig\Node\Expression\BlockReferenceExpression',
'Twig_Node_Expression_BlockReference');
twig/src/Node/Expression/CallExpression.php000064400000026750151161070030015001
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\Error\SyntaxError;
use Twig\Extension\ExtensionInterface;
use Twig\Node\Node;
abstract class CallExpression extends AbstractExpression
{
private $reflector;
protected function compileCallable(Compiler $compiler)
{
$closingParenthesis = false;
$isArray = false;
if ($this->hasAttribute('callable') &&
$callable = $this->getAttribute('callable')) {
if (\is_string($callable) && false ===
strpos($callable, '::')) {
$compiler->raw($callable);
} else {
list($r, $callable) = $this->reflectCallable($callable);
if ($r instanceof \ReflectionMethod &&
\is_string($callable[0])) {
if ($r->isStatic()) {
$compiler->raw(sprintf('%s::%s',
$callable[0], $callable[1]));
} else {
$compiler->raw(sprintf('$this->env->getRuntime(\'%s\')->%s',
$callable[0], $callable[1]));
}
} elseif ($r instanceof \ReflectionMethod &&
$callable[0] instanceof ExtensionInterface) {
$compiler->raw(sprintf('$this->env->getExtension(\'%s\')->%s',
\get_class($callable[0]), $callable[1]));
} else {
$type =
ucfirst($this->getAttribute('type'));
$compiler->raw(sprintf('call_user_func_array($this->env->get%s(\'%s\')->getCallable(),
', $type, $this->getAttribute('name')));
$closingParenthesis = true;
$isArray = true;
}
}
} else {
$compiler->raw($this->getAttribute('thing')->compile());
}
$this->compileArguments($compiler, $isArray);
if ($closingParenthesis) {
$compiler->raw(')');
}
}
protected function compileArguments(Compiler $compiler, $isArray =
false)
{
$compiler->raw($isArray ? '[' : '(');
$first = true;
if ($this->hasAttribute('needs_environment')
&& $this->getAttribute('needs_environment')) {
$compiler->raw('$this->env');
$first = false;
}
if ($this->hasAttribute('needs_context') &&
$this->getAttribute('needs_context')) {
if (!$first) {
$compiler->raw(', ');
}
$compiler->raw('$context');
$first = false;
}
if ($this->hasAttribute('arguments')) {
foreach ($this->getAttribute('arguments') as
$argument) {
if (!$first) {
$compiler->raw(', ');
}
$compiler->string($argument);
$first = false;
}
}
if ($this->hasNode('node')) {
if (!$first) {
$compiler->raw(', ');
}
$compiler->subcompile($this->getNode('node'));
$first = false;
}
if ($this->hasNode('arguments')) {
$callable = $this->hasAttribute('callable') ?
$this->getAttribute('callable') : null;
$arguments = $this->getArguments($callable,
$this->getNode('arguments'));
foreach ($arguments as $node) {
if (!$first) {
$compiler->raw(', ');
}
$compiler->subcompile($node);
$first = false;
}
}
$compiler->raw($isArray ? ']' : ')');
}
protected function getArguments($callable, $arguments)
{
$callType = $this->getAttribute('type');
$callName = $this->getAttribute('name');
$parameters = [];
$named = false;
foreach ($arguments as $name => $node) {
if (!\is_int($name)) {
$named = true;
$name = $this->normalizeName($name);
} elseif ($named) {
throw new SyntaxError(sprintf('Positional arguments
cannot be used after named arguments for %s "%s".',
$callType, $callName), $this->getTemplateLine(),
$this->getSourceContext());
}
$parameters[$name] = $node;
}
$isVariadic = $this->hasAttribute('is_variadic')
&& $this->getAttribute('is_variadic');
if (!$named && !$isVariadic) {
return $parameters;
}
if (!$callable) {
if ($named) {
$message = sprintf('Named arguments are not supported
for %s "%s".', $callType, $callName);
} else {
$message = sprintf('Arbitrary positional arguments are
not supported for %s "%s".', $callType, $callName);
}
throw new \LogicException($message);
}
$callableParameters = $this->getCallableParameters($callable,
$isVariadic);
$arguments = [];
$names = [];
$missingArguments = [];
$optionalArguments = [];
$pos = 0;
foreach ($callableParameters as $callableParameter) {
$names[] = $name =
$this->normalizeName($callableParameter->name);
if (\array_key_exists($name, $parameters)) {
if (\array_key_exists($pos, $parameters)) {
throw new SyntaxError(sprintf('Argument
"%s" is defined twice for %s "%s".', $name,
$callType, $callName), $this->getTemplateLine(),
$this->getSourceContext());
}
if (\count($missingArguments)) {
throw new SyntaxError(sprintf(
'Argument "%s" could not be assigned
for %s "%s(%s)" because it is mapped to an internal PHP function
which cannot determine default value for optional argument%s
"%s".',
$name, $callType, $callName, implode(',
', $names), \count($missingArguments) > 1 ? 's' :
'', implode('", "', $missingArguments)
), $this->getTemplateLine(),
$this->getSourceContext());
}
$arguments = array_merge($arguments, $optionalArguments);
$arguments[] = $parameters[$name];
unset($parameters[$name]);
$optionalArguments = [];
} elseif (\array_key_exists($pos, $parameters)) {
$arguments = array_merge($arguments, $optionalArguments);
$arguments[] = $parameters[$pos];
unset($parameters[$pos]);
$optionalArguments = [];
++$pos;
} elseif ($callableParameter->isDefaultValueAvailable()) {
$optionalArguments[] = new
ConstantExpression($callableParameter->getDefaultValue(), -1);
} elseif ($callableParameter->isOptional()) {
if (empty($parameters)) {
break;
} else {
$missingArguments[] = $name;
}
} else {
throw new SyntaxError(sprintf('Value for argument
"%s" is required for %s "%s".', $name, $callType,
$callName), $this->getTemplateLine(), $this->getSourceContext());
}
}
if ($isVariadic) {
$arbitraryArguments = new ArrayExpression([], -1);
foreach ($parameters as $key => $value) {
if (\is_int($key)) {
$arbitraryArguments->addElement($value);
} else {
$arbitraryArguments->addElement($value, new
ConstantExpression($key, -1));
}
unset($parameters[$key]);
}
if ($arbitraryArguments->count()) {
$arguments = array_merge($arguments, $optionalArguments);
$arguments[] = $arbitraryArguments;
}
}
if (!empty($parameters)) {
$unknownParameter = null;
foreach ($parameters as $parameter) {
if ($parameter instanceof Node) {
$unknownParameter = $parameter;
break;
}
}
throw new SyntaxError(
sprintf(
'Unknown argument%s "%s" for %s
"%s(%s)".',
\count($parameters) > 1 ? 's' :
'', implode('", "', array_keys($parameters)),
$callType, $callName, implode(', ', $names)
),
$unknownParameter ? $unknownParameter->getTemplateLine()
: $this->getTemplateLine(),
$unknownParameter ?
$unknownParameter->getSourceContext() : $this->getSourceContext()
);
}
return $arguments;
}
protected function normalizeName($name)
{
return strtolower(preg_replace(['/([A-Z]+)([A-Z][a-z])/',
'/([a-z\d])([A-Z])/'], ['\\1_\\2',
'\\1_\\2'], $name));
}
private function getCallableParameters($callable, $isVariadic)
{
list($r) = $this->reflectCallable($callable);
if (null === $r) {
return [];
}
$parameters = $r->getParameters();
if ($this->hasNode('node')) {
array_shift($parameters);
}
if ($this->hasAttribute('needs_environment')
&& $this->getAttribute('needs_environment')) {
array_shift($parameters);
}
if ($this->hasAttribute('needs_context') &&
$this->getAttribute('needs_context')) {
array_shift($parameters);
}
if ($this->hasAttribute('arguments') && null
!== $this->getAttribute('arguments')) {
foreach ($this->getAttribute('arguments') as
$argument) {
array_shift($parameters);
}
}
if ($isVariadic) {
$argument = end($parameters);
if ($argument && $argument->isArray() &&
$argument->isDefaultValueAvailable() && [] ===
$argument->getDefaultValue()) {
array_pop($parameters);
} else {
$callableName = $r->name;
if ($r instanceof \ReflectionMethod) {
$callableName =
$r->getDeclaringClass()->name.'::'.$callableName;
}
throw new \LogicException(sprintf('The last parameter
of "%s" for %s "%s" must be an array with default
value, eg. "array $arg = []".', $callableName,
$this->getAttribute('type'),
$this->getAttribute('name')));
}
}
return $parameters;
}
private function reflectCallable($callable)
{
if (null !== $this->reflector) {
return $this->reflector;
}
if (\is_array($callable)) {
if (!method_exists($callable[0], $callable[1])) {
// __call()
return [null, []];
}
$r = new \ReflectionMethod($callable[0], $callable[1]);
} elseif (\is_object($callable) && !$callable instanceof
\Closure) {
$r = new \ReflectionObject($callable);
$r = $r->getMethod('__invoke');
$callable = [$callable, '__invoke'];
} elseif (\is_string($callable) && false !== $pos =
strpos($callable, '::')) {
$class = substr($callable, 0, $pos);
$method = substr($callable, $pos + 2);
if (!method_exists($class, $method)) {
// __staticCall()
return [null, []];
}
$r = new \ReflectionMethod($callable);
$callable = [$class, $method];
} else {
$r = new \ReflectionFunction($callable);
}
return $this->reflector = [$r, $callable];
}
}
class_alias('Twig\Node\Expression\CallExpression',
'Twig_Node_Expression_Call');
twig/src/Node/Expression/ConditionalExpression.php000064400000001760151161070030016363
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
class ConditionalExpression extends AbstractExpression
{
public function __construct(AbstractExpression $expr1,
AbstractExpression $expr2, AbstractExpression $expr3, $lineno)
{
parent::__construct(['expr1' => $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');
twig/src/Node/Expression/ConstantExpression.php000064400000001227151161070030015707
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
class ConstantExpression extends AbstractExpression
{
public function __construct($value, $lineno)
{
parent::__construct([], ['value' => $value], $lineno);
}
public function compile(Compiler $compiler)
{
$compiler->repr($this->getAttribute('value'));
}
}
class_alias('Twig\Node\Expression\ConstantExpression',
'Twig_Node_Expression_Constant');
twig/src/Node/Expression/Filter/DefaultFilter.php000064400000003556151161070030016024
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Filter;
use Twig\Compiler;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\Test\DefinedTest;
use Twig\Node\Node;
/**
* Returns the value or the default value when it is undefined or empty.
*
* {{ var.foo|default('foo item on var is not defined') }}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DefaultFilter extends FilterExpression
{
public function __construct(\Twig_NodeInterface $node,
ConstantExpression $filterName, \Twig_NodeInterface $arguments, $lineno,
$tag = null)
{
$default = new FilterExpression($node, new
ConstantExpression('default', $node->getTemplateLine()),
$arguments, $node->getTemplateLine());
if ('default' ===
$filterName->getAttribute('value') && ($node
instanceof NameExpression || $node instanceof GetAttrExpression)) {
$test = new DefinedTest(clone $node, 'defined', new
Node(), $node->getTemplateLine());
$false = \count($arguments) ? $arguments->getNode(0) : new
ConstantExpression('', $node->getTemplateLine());
$node = new ConditionalExpression($test, $default, $false,
$node->getTemplateLine());
} else {
$node = $default;
}
parent::__construct($node, $filterName, $arguments, $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler->subcompile($this->getNode('node'));
}
}
class_alias('Twig\Node\Expression\Filter\DefaultFilter',
'Twig_Node_Expression_Filter_Default');
twig/src/Node/Expression/FilterExpression.php000064400000003103151161070030015336
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\TwigFilter;
class FilterExpression extends CallExpression
{
public function __construct(\Twig_NodeInterface $node,
ConstantExpression $filterName, \Twig_NodeInterface $arguments, $lineno,
$tag = null)
{
parent::__construct(['node' => $node,
'filter' => $filterName, 'arguments' =>
$arguments], [], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$name =
$this->getNode('filter')->getAttribute('value');
$filter = $compiler->getEnvironment()->getFilter($name);
$this->setAttribute('name', $name);
$this->setAttribute('type', 'filter');
$this->setAttribute('thing', $filter);
$this->setAttribute('needs_environment',
$filter->needsEnvironment());
$this->setAttribute('needs_context',
$filter->needsContext());
$this->setAttribute('arguments',
$filter->getArguments());
if ($filter instanceof \Twig_FilterCallableInterface || $filter
instanceof TwigFilter) {
$this->setAttribute('callable',
$filter->getCallable());
}
if ($filter instanceof TwigFilter) {
$this->setAttribute('is_variadic',
$filter->isVariadic());
}
$this->compileCallable($compiler);
}
}
class_alias('Twig\Node\Expression\FilterExpression',
'Twig_Node_Expression_Filter');
twig/src/Node/Expression/FunctionExpression.php000064400000003265151161070030015707
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\TwigFunction;
class FunctionExpression extends CallExpression
{
public function __construct($name, \Twig_NodeInterface $arguments,
$lineno)
{
parent::__construct(['arguments' => $arguments],
['name' => $name, 'is_defined_test' => false],
$lineno);
}
public function compile(Compiler $compiler)
{
$name = $this->getAttribute('name');
$function = $compiler->getEnvironment()->getFunction($name);
$this->setAttribute('name', $name);
$this->setAttribute('type', 'function');
$this->setAttribute('thing', $function);
$this->setAttribute('needs_environment',
$function->needsEnvironment());
$this->setAttribute('needs_context',
$function->needsContext());
$this->setAttribute('arguments',
$function->getArguments());
if ($function instanceof \Twig_FunctionCallableInterface ||
$function instanceof TwigFunction) {
$callable = $function->getCallable();
if ('constant' === $name &&
$this->getAttribute('is_defined_test')) {
$callable = 'twig_constant_is_defined';
}
$this->setAttribute('callable', $callable);
}
if ($function instanceof TwigFunction) {
$this->setAttribute('is_variadic',
$function->isVariadic());
}
$this->compileCallable($compiler);
}
}
class_alias('Twig\Node\Expression\FunctionExpression',
'Twig_Node_Expression_Function');
twig/src/Node/Expression/GetAttrExpression.php000064400000005252151161070030015472
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\Template;
class GetAttrExpression extends AbstractExpression
{
public function __construct(AbstractExpression $node,
AbstractExpression $attribute, AbstractExpression $arguments = null, $type,
$lineno)
{
$nodes = ['node' => $node, 'attribute' =>
$attribute];
if (null !== $arguments) {
$nodes['arguments'] = $arguments;
}
parent::__construct($nodes, ['type' => $type,
'is_defined_test' => false, 'ignore_strict_check'
=> false, 'disable_c_ext' => false], $lineno);
}
public function compile(Compiler $compiler)
{
if ($this->getAttribute('disable_c_ext')) {
@trigger_error(sprintf('Using the
"disable_c_ext" attribute on %s is deprecated since version 1.30
and will be removed in 2.0.', __CLASS__), E_USER_DEPRECATED);
}
if (\function_exists('twig_template_get_attributes')
&& !$this->getAttribute('disable_c_ext')) {
$compiler->raw('twig_template_get_attributes($this,
');
} else {
$compiler->raw('$this->getAttribute(');
}
if ($this->getAttribute('ignore_strict_check')) {
$this->getNode('node')->setAttribute('ignore_strict_check',
true);
}
$compiler->subcompile($this->getNode('node'));
$compiler->raw(',
')->subcompile($this->getNode('attribute'));
// only generate optional arguments when needed (to make generated
code more readable)
$needFourth =
$this->getAttribute('ignore_strict_check');
$needThird = $needFourth ||
$this->getAttribute('is_defined_test');
$needSecond = $needThird || Template::ANY_CALL !==
$this->getAttribute('type');
$needFirst = $needSecond ||
$this->hasNode('arguments');
if ($needFirst) {
if ($this->hasNode('arguments')) {
$compiler->raw(',
')->subcompile($this->getNode('arguments'));
} else {
$compiler->raw(', []');
}
}
if ($needSecond) {
$compiler->raw(',
')->repr($this->getAttribute('type'));
}
if ($needThird) {
$compiler->raw(',
')->repr($this->getAttribute('is_defined_test'));
}
if ($needFourth) {
$compiler->raw(',
')->repr($this->getAttribute('ignore_strict_check'));
}
$compiler->raw(')');
}
}
class_alias('Twig\Node\Expression\GetAttrExpression',
'Twig_Node_Expression_GetAttr');
twig/src/Node/Expression/InlinePrint.php000064400000001233151161070030014266
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\Node\Node;
/**
* @internal
*/
final class InlinePrint extends AbstractExpression
{
public function __construct(Node $node, $lineno)
{
parent::__construct(['node' => $node], [], $lineno);
}
public function compile(Compiler $compiler)
{
$compiler
->raw('print (')
->subcompile($this->getNode('node'))
->raw(')')
;
}
}
twig/src/Node/Expression/MethodCallExpression.php000064400000002416151161070030016133
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
class MethodCallExpression extends AbstractExpression
{
public function __construct(AbstractExpression $node, $method,
ArrayExpression $arguments, $lineno)
{
parent::__construct(['node' => $node,
'arguments' => $arguments], ['method' => $method,
'safe' => false], $lineno);
if ($node instanceof NameExpression) {
$node->setAttribute('always_defined', true);
}
}
public function compile(Compiler $compiler)
{
$compiler
->subcompile($this->getNode('node'))
->raw('->')
->raw($this->getAttribute('method'))
->raw('(')
;
$first = true;
foreach
($this->getNode('arguments')->getKeyValuePairs() as $pair)
{
if (!$first) {
$compiler->raw(', ');
}
$first = false;
$compiler->subcompile($pair['value']);
}
$compiler->raw(')');
}
}
class_alias('Twig\Node\Expression\MethodCallExpression',
'Twig_Node_Expression_MethodCall');
twig/src/Node/Expression/NameExpression.php000064400000007173151161070030015004
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
class NameExpression extends AbstractExpression
{
protected $specialVars = [
'_self' => '$this',
'_context' => '$context',
'_charset' =>
'$this->env->getCharset()',
];
public function __construct($name, $lineno)
{
parent::__construct([], ['name' => $name,
'is_defined_test' => false, 'ignore_strict_check'
=> false, 'always_defined' => false], $lineno);
}
public function compile(Compiler $compiler)
{
$name = $this->getAttribute('name');
$compiler->addDebugInfo($this);
if ($this->getAttribute('is_defined_test')) {
if ($this->isSpecial()) {
$compiler->repr(true);
} elseif (\PHP_VERSION_ID >= 700400) {
$compiler
->raw('array_key_exists(')
->string($name)
->raw(', $context)')
;
} else {
$compiler
->raw('(isset($context[')
->string($name)
->raw(']) || array_key_exists(')
->string($name)
->raw(', $context))')
;
}
} elseif ($this->isSpecial()) {
$compiler->raw($this->specialVars[$name]);
} elseif ($this->getAttribute('always_defined')) {
$compiler
->raw('$context[')
->string($name)
->raw(']')
;
} else {
if (\PHP_VERSION_ID >= 70000) {
// use PHP 7 null coalescing operator
$compiler
->raw('($context[')
->string($name)
->raw('] ?? ')
;
if ($this->getAttribute('ignore_strict_check')
|| !$compiler->getEnvironment()->isStrictVariables()) {
$compiler->raw('null)');
} else {
$compiler->raw('$this->getContext($context,
')->string($name)->raw('))');
}
} elseif (\PHP_VERSION_ID >= 50400) {
// PHP 5.4 ternary operator performance was optimized
$compiler
->raw('(isset($context[')
->string($name)
->raw(']) ? $context[')
->string($name)
->raw('] : ')
;
if ($this->getAttribute('ignore_strict_check')
|| !$compiler->getEnvironment()->isStrictVariables()) {
$compiler->raw('null)');
} else {
$compiler->raw('$this->getContext($context,
')->string($name)->raw('))');
}
} else {
$compiler
->raw('$this->getContext($context, ')
->string($name)
;
if
($this->getAttribute('ignore_strict_check')) {
$compiler->raw(', true');
}
$compiler
->raw(')')
;
}
}
}
public function isSpecial()
{
return
isset($this->specialVars[$this->getAttribute('name')]);
}
public function isSimple()
{
return !$this->isSpecial() &&
!$this->getAttribute('is_defined_test');
}
}
class_alias('Twig\Node\Expression\NameExpression',
'Twig_Node_Expression_Name');
twig/src/Node/Expression/NullCoalesceExpression.php000064400000004310151161070030016463
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\Node\Expression\Binary\AndBinary;
use Twig\Node\Expression\Test\DefinedTest;
use Twig\Node\Expression\Test\NullTest;
use Twig\Node\Expression\Unary\NotUnary;
use Twig\Node\Node;
class NullCoalesceExpression extends ConditionalExpression
{
public function __construct(\Twig_NodeInterface $left,
\Twig_NodeInterface $right, $lineno)
{
$test = new DefinedTest(clone $left, 'defined', new
Node(), $left->getTemplateLine());
// for "block()", we don't need the null test as the
return value is always a string
if (!$left instanceof BlockReferenceExpression) {
$test = new AndBinary(
$test,
new NotUnary(new NullTest($left, 'null', new
Node(), $left->getTemplateLine()), $left->getTemplateLine()),
$left->getTemplateLine()
);
}
parent::__construct($test, $left, $right, $lineno);
}
public function compile(Compiler $compiler)
{
/*
* This optimizes only one case. PHP 7 also supports more complex
expressions
* that can return null. So, for instance, if log is defined,
log("foo") ?? "..." works,
* but log($a["foo"]) ?? "..." does not if
$a["foo"] is not defined. More advanced
* cases might be implemented as an optimizer node visitor, but has
not been done
* as benefits are probably not worth the added complexity.
*/
if (\PHP_VERSION_ID >= 70000 &&
$this->getNode('expr2') instanceof NameExpression) {
$this->getNode('expr2')->setAttribute('always_defined',
true);
$compiler
->raw('((')
->subcompile($this->getNode('expr2'))
->raw(') ?? (')
->subcompile($this->getNode('expr3'))
->raw('))')
;
} else {
parent::compile($compiler);
}
}
}
class_alias('Twig\Node\Expression\NullCoalesceExpression',
'Twig_Node_Expression_NullCoalesce');
twig/src/Node/Expression/ParentExpression.php000064400000002302151161070030015342
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
/**
* Represents a parent node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ParentExpression extends AbstractExpression
{
public function __construct($name, $lineno, $tag = null)
{
parent::__construct([], ['output' => false,
'name' => $name], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
if ($this->getAttribute('output')) {
$compiler
->addDebugInfo($this)
->write('$this->displayParentBlock(')
->string($this->getAttribute('name'))
->raw(", \$context, \$blocks);\n")
;
} else {
$compiler
->raw('$this->renderParentBlock(')
->string($this->getAttribute('name'))
->raw(', $context, $blocks)')
;
}
}
}
class_alias('Twig\Node\Expression\ParentExpression',
'Twig_Node_Expression_Parent');
twig/src/Node/Expression/TempNameExpression.php000064400000001301151161070030015615
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
class TempNameExpression extends AbstractExpression
{
public function __construct($name, $lineno)
{
parent::__construct([], ['name' => $name], $lineno);
}
public function compile(Compiler $compiler)
{
$compiler
->raw('$_')
->raw($this->getAttribute('name'))
->raw('_')
;
}
}
class_alias('Twig\Node\Expression\TempNameExpression',
'Twig_Node_Expression_TempName');
twig/src/Node/Expression/Test/ConstantTest.php000064400000002363151161070030015410
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a variable is the exact same value as a constant.
*
* {% if post.status is constant('Post::PUBLISHED') %}
* the status attribute is exactly the same as Post::PUBLISHED
* {% endif %}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Node/Expression/Test/DefinedTest.php000064400000004606151161070030015157
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Error\SyntaxError;
use Twig\Node\Expression\ArrayExpression;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a variable is defined in the current context.
*
* {# defined works with variable names and variable attributes #}
* {% if foo is defined %}
* {# ... #}
* {% endif %}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DefinedTest extends TestExpression
{
public function __construct(\Twig_NodeInterface $node, $name,
\Twig_NodeInterface $arguments = null, $lineno)
{
if ($node instanceof NameExpression) {
$node->setAttribute('is_defined_test', true);
} elseif ($node instanceof GetAttrExpression) {
$node->setAttribute('is_defined_test', true);
$this->changeIgnoreStrictCheck($node);
} elseif ($node instanceof BlockReferenceExpression) {
$node->setAttribute('is_defined_test', true);
} elseif ($node instanceof FunctionExpression &&
'constant' === $node->getAttribute('name')) {
$node->setAttribute('is_defined_test', true);
} elseif ($node instanceof ConstantExpression || $node instanceof
ArrayExpression) {
$node = new ConstantExpression(true,
$node->getTemplateLine());
} else {
throw new SyntaxError('The "defined" test only
works with simple variables.', $lineno);
}
parent::__construct($node, $name, $arguments, $lineno);
}
protected function changeIgnoreStrictCheck(GetAttrExpression $node)
{
$node->setAttribute('ignore_strict_check', true);
if ($node->getNode('node') instanceof
GetAttrExpression) {
$this->changeIgnoreStrictCheck($node->getNode('node'));
}
}
public function compile(Compiler $compiler)
{
$compiler->subcompile($this->getNode('node'));
}
}
class_alias('Twig\Node\Expression\Test\DefinedTest',
'Twig_Node_Expression_Test_Defined');
twig/src/Node/Expression/Test/DivisiblebyTest.php000064400000001565151161070030016067
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a variable is divisible by a number.
*
* {% if loop.index is divisible by(3) %}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Node/Expression/Test/EvenTest.php000064400000001367151161070030014517
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a number is even.
*
* {{ var is even }}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Node/Expression/Test/NullTest.php000064400000001345151161070030014530
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks that a variable is null.
*
* {{ var is none }}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Node/Expression/Test/OddTest.php000064400000001362151161070030014323
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a number is odd.
*
* {{ var is odd }}
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Node/Expression/Test/SameasTest.php000064400000001504151161070030015024
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Test;
use Twig\Compiler;
use Twig\Node\Expression\TestExpression;
/**
* Checks if a variable is the same as another one (=== in PHP).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Node/Expression/TestExpression.php000064400000002703151161070030015035
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression;
use Twig\Compiler;
use Twig\TwigTest;
class TestExpression extends CallExpression
{
public function __construct(\Twig_NodeInterface $node, $name,
\Twig_NodeInterface $arguments = null, $lineno)
{
$nodes = ['node' => $node];
if (null !== $arguments) {
$nodes['arguments'] = $arguments;
}
parent::__construct($nodes, ['name' => $name],
$lineno);
}
public function compile(Compiler $compiler)
{
$name = $this->getAttribute('name');
$test = $compiler->getEnvironment()->getTest($name);
$this->setAttribute('name', $name);
$this->setAttribute('type', 'test');
$this->setAttribute('thing', $test);
if ($test instanceof TwigTest) {
$this->setAttribute('arguments',
$test->getArguments());
}
if ($test instanceof \Twig_TestCallableInterface || $test
instanceof TwigTest) {
$this->setAttribute('callable',
$test->getCallable());
}
if ($test instanceof TwigTest) {
$this->setAttribute('is_variadic',
$test->isVariadic());
}
$this->compileCallable($compiler);
}
}
class_alias('Twig\Node\Expression\TestExpression',
'Twig_Node_Expression_Test');
twig/src/Node/Expression/Unary/AbstractUnary.php000064400000001532151161070030015715
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
abstract class AbstractUnary extends AbstractExpression
{
public function __construct(\Twig_NodeInterface $node, $lineno)
{
parent::__construct(['node' => $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');
twig/src/Node/Expression/Unary/NegUnary.php000064400000000765151161070030014672
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
class NegUnary extends AbstractUnary
{
public function operator(Compiler $compiler)
{
$compiler->raw('-');
}
}
class_alias('Twig\Node\Expression\Unary\NegUnary',
'Twig_Node_Expression_Unary_Neg');
twig/src/Node/Expression/Unary/NotUnary.php000064400000000765151161070030014721
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
class NotUnary extends AbstractUnary
{
public function operator(Compiler $compiler)
{
$compiler->raw('!');
}
}
class_alias('Twig\Node\Expression\Unary\NotUnary',
'Twig_Node_Expression_Unary_Not');
twig/src/Node/Expression/Unary/PosUnary.php000064400000000765151161070030014722
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node\Expression\Unary;
use Twig\Compiler;
class PosUnary extends AbstractUnary
{
public function operator(Compiler $compiler)
{
$compiler->raw('+');
}
}
class_alias('Twig\Node\Expression\Unary\PosUnary',
'Twig_Node_Expression_Unary_Pos');
twig/src/Node/FlushNode.php000064400000001261151161070030011564
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents a flush node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FlushNode extends Node
{
public function __construct($lineno, $tag)
{
parent::__construct([], [], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write("flush();\n")
;
}
}
class_alias('Twig\Node\FlushNode', 'Twig_Node_Flush');
twig/src/Node/ForLoopNode.php000064400000003061151161070030012063
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Internal node used by the for node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ForLoopNode extends Node
{
public function __construct($lineno, $tag = null)
{
parent::__construct([], ['with_loop' => false,
'ifexpr' => false, 'else' => false], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
if ($this->getAttribute('else')) {
$compiler->write("\$context['_iterated'] =
true;\n");
}
if ($this->getAttribute('with_loop')) {
$compiler
->write("++\$context['loop']['index0'];\n")
->write("++\$context['loop']['index'];\n")
->write("\$context['loop']['first'] =
false;\n")
;
if (!$this->getAttribute('ifexpr')) {
$compiler
->write("if
(isset(\$context['loop']['length'])) {\n")
->indent()
->write("--\$context['loop']['revindex0'];\n")
->write("--\$context['loop']['revindex'];\n")
->write("\$context['loop']['last'] = 0 ===
\$context['loop']['revindex0'];\n")
->outdent()
->write("}\n")
;
}
}
}
}
class_alias('Twig\Node\ForLoopNode',
'Twig_Node_ForLoop');
twig/src/Node/ForNode.php000064400000010365151161070030011236
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\AssignNameExpression;
/**
* Represents a for node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ForNode extends Node
{
protected $loop;
public function __construct(AssignNameExpression $keyTarget,
AssignNameExpression $valueTarget, AbstractExpression $seq,
AbstractExpression $ifexpr = null, \Twig_NodeInterface $body,
\Twig_NodeInterface $else = null, $lineno, $tag = null)
{
$body = new Node([$body, $this->loop = new ForLoopNode($lineno,
$tag)]);
if (null !== $ifexpr) {
$body = new IfNode(new Node([$ifexpr, $body]), null, $lineno,
$tag);
}
$nodes = ['key_target' => $keyTarget,
'value_target' => $valueTarget, 'seq' => $seq,
'body' => $body];
if (null !== $else) {
$nodes['else'] = $else;
}
parent::__construct($nodes, ['with_loop' => true,
'ifexpr' => null !== $ifexpr], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write("\$context['_parent'] =
\$context;\n")
->write("\$context['_seq'] =
twig_ensure_traversable(")
->subcompile($this->getNode('seq'))
->raw(");\n")
;
if ($this->hasNode('else')) {
$compiler->write("\$context['_iterated'] =
false;\n");
}
if ($this->getAttribute('with_loop')) {
$compiler
->write("\$context['loop'] = [\n")
->write(" 'parent' =>
\$context['_parent'],\n")
->write(" 'index0' => 0,\n")
->write(" 'index' => 1,\n")
->write(" 'first' => true,\n")
->write("];\n")
;
if (!$this->getAttribute('ifexpr')) {
$compiler
->write("if
(is_array(\$context['_seq']) ||
(is_object(\$context['_seq']) &&
\$context['_seq'] instanceof \Countable)) {\n")
->indent()
->write("\$length =
count(\$context['_seq']);\n")
->write("\$context['loop']['revindex0'] =
\$length - 1;\n")
->write("\$context['loop']['revindex'] =
\$length;\n")
->write("\$context['loop']['length'] =
\$length;\n")
->write("\$context['loop']['last'] = 1 ===
\$length;\n")
->outdent()
->write("}\n")
;
}
}
$this->loop->setAttribute('else',
$this->hasNode('else'));
$this->loop->setAttribute('with_loop',
$this->getAttribute('with_loop'));
$this->loop->setAttribute('ifexpr',
$this->getAttribute('ifexpr'));
$compiler
->write("foreach (\$context['_seq'] as
")
->subcompile($this->getNode('key_target'))
->raw(' => ')
->subcompile($this->getNode('value_target'))
->raw(") {\n")
->indent()
->subcompile($this->getNode('body'))
->outdent()
->write("}\n")
;
if ($this->hasNode('else')) {
$compiler
->write("if (!\$context['_iterated'])
{\n")
->indent()
->subcompile($this->getNode('else'))
->outdent()
->write("}\n")
;
}
$compiler->write("\$_parent =
\$context['_parent'];\n");
// remove some "private" loop variables (needed for
nested loops)
$compiler->write('unset($context[\'_seq\'],
$context[\'_iterated\'],
$context[\''.$this->getNode('key_target')->getAttribute('name').'\'],
$context[\''.$this->getNode('value_target')->getAttribute('name').'\'],
$context[\'_parent\'],
$context[\'loop\']);'."\n");
// keep the values set in the inner context for variables defined
in the outer context
$compiler->write("\$context =
array_intersect_key(\$context, \$_parent) + \$_parent;\n");
}
}
class_alias('Twig\Node\ForNode', 'Twig_Node_For');
twig/src/Node/IfNode.php000064400000003273151161070030011046
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents an if node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class IfNode extends Node
{
public function __construct(\Twig_NodeInterface $tests,
\Twig_NodeInterface $else = null, $lineno, $tag = null)
{
$nodes = ['tests' => $tests];
if (null !== $else) {
$nodes['else'] = $else;
}
parent::__construct($nodes, [], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler->addDebugInfo($this);
for ($i = 0, $count = \count($this->getNode('tests'));
$i < $count; $i += 2) {
if ($i > 0) {
$compiler
->outdent()
->write('} elseif (')
;
} else {
$compiler
->write('if (')
;
}
$compiler
->subcompile($this->getNode('tests')->getNode($i))
->raw(") {\n")
->indent()
->subcompile($this->getNode('tests')->getNode($i + 1))
;
}
if ($this->hasNode('else')) {
$compiler
->outdent()
->write("} else {\n")
->indent()
->subcompile($this->getNode('else'))
;
}
$compiler
->outdent()
->write("}\n");
}
}
class_alias('Twig\Node\IfNode', 'Twig_Node_If');
twig/src/Node/ImportNode.php000064400000002706151161070030011762
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\NameExpression;
/**
* Represents an import node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ImportNode extends Node
{
public function __construct(AbstractExpression $expr,
AbstractExpression $var, $lineno, $tag = null)
{
parent::__construct(['expr' => $expr, 'var'
=> $var], [], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('')
->subcompile($this->getNode('var'))
->raw(' = ')
;
if ($this->getNode('expr') instanceof NameExpression
&& '_self' ===
$this->getNode('expr')->getAttribute('name')) {
$compiler->raw('$this');
} else {
$compiler
->raw('$this->loadTemplate(')
->subcompile($this->getNode('expr'))
->raw(', ')
->repr($this->getTemplateName())
->raw(', ')
->repr($this->getTemplateLine())
->raw(')->unwrap()')
;
}
$compiler->raw(";\n");
}
}
class_alias('Twig\Node\ImportNode',
'Twig_Node_Import');
twig/src/Node/IncludeNode.php000064400000006174151161070030012076
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
/**
* Represents an include node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class IncludeNode extends Node implements NodeOutputInterface
{
public function __construct(AbstractExpression $expr,
AbstractExpression $variables = null, $only = false, $ignoreMissing =
false, $lineno, $tag = null)
{
$nodes = ['expr' => $expr];
if (null !== $variables) {
$nodes['variables'] = $variables;
}
parent::__construct($nodes, ['only' => (bool) $only,
'ignore_missing' => (bool) $ignoreMissing], $lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler->addDebugInfo($this);
if ($this->getAttribute('ignore_missing')) {
$template = $compiler->getVarName();
$compiler
->write(sprintf("$%s = null;\n", $template))
->write("try {\n")
->indent()
->write(sprintf('$%s = ', $template))
;
$this->addGetTemplate($compiler);
$compiler
->raw(";\n")
->outdent()
->write("} catch (LoaderError \$e) {\n")
->indent()
->write("// ignore missing template\n")
->outdent()
->write("}\n")
->write(sprintf("if ($%s) {\n", $template))
->indent()
->write(sprintf('$%s->display(',
$template))
;
$this->addTemplateArguments($compiler);
$compiler
->raw(");\n")
->outdent()
->write("}\n")
;
} else {
$this->addGetTemplate($compiler);
$compiler->raw('->display(');
$this->addTemplateArguments($compiler);
$compiler->raw(");\n");
}
}
protected function addGetTemplate(Compiler $compiler)
{
$compiler
->write('$this->loadTemplate(')
->subcompile($this->getNode('expr'))
->raw(', ')
->repr($this->getTemplateName())
->raw(', ')
->repr($this->getTemplateLine())
->raw(')')
;
}
protected function addTemplateArguments(Compiler $compiler)
{
if (!$this->hasNode('variables')) {
$compiler->raw(false ===
$this->getAttribute('only') ? '$context' :
'[]');
} elseif (false === $this->getAttribute('only')) {
$compiler
->raw('twig_array_merge($context, ')
->subcompile($this->getNode('variables'))
->raw(')')
;
} else {
$compiler->raw('twig_to_array(');
$compiler->subcompile($this->getNode('variables'));
$compiler->raw(')');
}
}
}
class_alias('Twig\Node\IncludeNode',
'Twig_Node_Include');
twig/src/Node/MacroNode.php000064400000007425151161070030011554
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Error\SyntaxError;
/**
* Represents a macro node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class MacroNode extends Node
{
const VARARGS_NAME = 'varargs';
public function __construct($name, \Twig_NodeInterface $body,
\Twig_NodeInterface $arguments, $lineno, $tag = null)
{
foreach ($arguments as $argumentName => $argument) {
if (self::VARARGS_NAME === $argumentName) {
throw new SyntaxError(sprintf('The argument
"%s" in macro "%s" cannot be defined because the
variable "%s" is reserved for arbitrary arguments.',
self::VARARGS_NAME, $name, self::VARARGS_NAME),
$argument->getTemplateLine(), $argument->getSourceContext());
}
}
parent::__construct(['body' => $body,
'arguments' => $arguments], ['name' => $name],
$lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write(sprintf('public function get%s(',
$this->getAttribute('name')))
;
$count = \count($this->getNode('arguments'));
$pos = 0;
foreach ($this->getNode('arguments') as $name =>
$default) {
$compiler
->raw('$__'.$name.'__ = ')
->subcompile($default)
;
if (++$pos < $count) {
$compiler->raw(', ');
}
}
if (\PHP_VERSION_ID >= 50600) {
if ($count) {
$compiler->raw(', ');
}
$compiler->raw('...$__varargs__');
}
$compiler
->raw(")\n")
->write("{\n")
->indent()
;
$compiler
->write("\$context =
\$this->env->mergeGlobals([\n")
->indent()
;
foreach ($this->getNode('arguments') as $name =>
$default) {
$compiler
->write('')
->string($name)
->raw(' => $__'.$name.'__')
->raw(",\n")
;
}
$compiler
->write('')
->string(self::VARARGS_NAME)
->raw(' => ')
;
if (\PHP_VERSION_ID >= 50600) {
$compiler->raw("\$__varargs__,\n");
} else {
$compiler
->raw('func_num_args() > ')
->repr($count)
->raw(' ? array_slice(func_get_args(), ')
->repr($count)
->raw(") : [],\n")
;
}
$compiler
->outdent()
->write("]);\n\n")
->write("\$blocks = [];\n\n")
;
if ($compiler->getEnvironment()->isDebug()) {
$compiler->write("ob_start();\n");
} else {
$compiler->write("ob_start(function () { return
''; });\n");
}
$compiler
->write("try {\n")
->indent()
->subcompile($this->getNode('body'))
->outdent()
->write("} catch (\Exception \$e) {\n")
->indent()
->write("ob_end_clean();\n\n")
->write("throw \$e;\n")
->outdent()
->write("} catch (\Throwable \$e) {\n")
->indent()
->write("ob_end_clean();\n\n")
->write("throw \$e;\n")
->outdent()
->write("}\n\n")
->write("return ('' === \$tmp =
ob_get_clean()) ? '' : new Markup(\$tmp,
\$this->env->getCharset());\n")
->outdent()
->write("}\n\n")
;
}
}
class_alias('Twig\Node\MacroNode', 'Twig_Node_Macro');
twig/src/Node/ModuleNode.php000064400000037414151161070030011741
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Source;
/**
* Represents a module node.
*
* Consider this class as being final. If you need to customize the
behavior of
* the generated class, consider adding nodes to the following nodes:
display_start,
* display_end, constructor_start, constructor_end, and class_end.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ModuleNode extends Node
{
public function __construct(\Twig_NodeInterface $body,
AbstractExpression $parent = null, \Twig_NodeInterface $blocks,
\Twig_NodeInterface $macros, \Twig_NodeInterface $traits,
$embeddedTemplates, $name, $source = '')
{
if (!$name instanceof Source) {
@trigger_error(sprintf('Passing a string as the $name
argument of %s() is deprecated since version 1.27. Pass a \Twig\Source
instance instead.', __METHOD__), E_USER_DEPRECATED);
$source = new Source($source, $name);
} else {
$source = $name;
}
$nodes = [
'body' => $body,
'blocks' => $blocks,
'macros' => $macros,
'traits' => $traits,
'display_start' => new Node(),
'display_end' => new Node(),
'constructor_start' => new Node(),
'constructor_end' => new Node(),
'class_end' => new Node(),
];
if (null !== $parent) {
$nodes['parent'] = $parent;
}
// embedded templates are set as attributes so that they are only
visited once by the visitors
parent::__construct($nodes, [
// source to be remove in 2.0
'source' => $source->getCode(),
// filename to be remove in 2.0 (use getTemplateName() instead)
'filename' => $source->getName(),
'index' => null,
'embedded_templates' => $embeddedTemplates,
], 1);
// populate the template name of all node children
$this->setTemplateName($source->getName());
$this->setSourceContext($source);
}
public function setIndex($index)
{
$this->setAttribute('index', $index);
}
public function compile(Compiler $compiler)
{
$this->compileTemplate($compiler);
foreach ($this->getAttribute('embedded_templates') as
$template) {
$compiler->subcompile($template);
}
}
protected function compileTemplate(Compiler $compiler)
{
if (!$this->getAttribute('index')) {
$compiler->write('<?php');
}
$this->compileClassHeader($compiler);
if (
\count($this->getNode('blocks'))
|| \count($this->getNode('traits'))
|| !$this->hasNode('parent')
|| $this->getNode('parent') instanceof
ConstantExpression
|| \count($this->getNode('constructor_start'))
|| \count($this->getNode('constructor_end'))
) {
$this->compileConstructor($compiler);
}
$this->compileGetParent($compiler);
$this->compileDisplay($compiler);
$compiler->subcompile($this->getNode('blocks'));
$this->compileMacros($compiler);
$this->compileGetTemplateName($compiler);
$this->compileIsTraitable($compiler);
$this->compileDebugInfo($compiler);
$this->compileGetSource($compiler);
$this->compileGetSourceContext($compiler);
$this->compileClassFooter($compiler);
}
protected function compileGetParent(Compiler $compiler)
{
if (!$this->hasNode('parent')) {
return;
}
$parent = $this->getNode('parent');
$compiler
->write("protected function doGetParent(array
\$context)\n", "{\n")
->indent()
->addDebugInfo($parent)
->write('return ')
;
if ($parent instanceof ConstantExpression) {
$compiler->subcompile($parent);
} else {
$compiler
->raw('$this->loadTemplate(')
->subcompile($parent)
->raw(', ')
->repr($this->getSourceContext()->getName())
->raw(', ')
->repr($parent->getTemplateLine())
->raw(')')
;
}
$compiler
->raw(";\n")
->outdent()
->write("}\n\n")
;
}
protected function compileClassHeader(Compiler $compiler)
{
$compiler
->write("\n\n")
;
if (!$this->getAttribute('index')) {
$compiler
->write("use Twig\Environment;\n")
->write("use Twig\Error\LoaderError;\n")
->write("use Twig\Error\RuntimeError;\n")
->write("use Twig\Markup;\n")
->write("use Twig\Sandbox\SecurityError;\n")
->write("use
Twig\Sandbox\SecurityNotAllowedTagError;\n")
->write("use
Twig\Sandbox\SecurityNotAllowedFilterError;\n")
->write("use
Twig\Sandbox\SecurityNotAllowedFunctionError;\n")
->write("use Twig\Source;\n")
->write("use Twig\Template;\n\n")
;
}
$compiler
// if the template name contains */, add a blank to avoid a PHP
parse error
->write('/* '.str_replace('*/', '*
/', $this->getSourceContext()->getName())." */\n")
->write('class
'.$compiler->getEnvironment()->getTemplateClass($this->getSourceContext()->getName(),
$this->getAttribute('index')))
->raw(sprintf(" extends %s\n",
$compiler->getEnvironment()->getBaseTemplateClass()))
->write("{\n")
->indent()
;
}
protected function compileConstructor(Compiler $compiler)
{
$compiler
->write("public function __construct(Environment
\$env)\n", "{\n")
->indent()
->subcompile($this->getNode('constructor_start'))
->write("parent::__construct(\$env);\n\n")
;
// parent
if (!$this->hasNode('parent')) {
$compiler->write("\$this->parent =
false;\n\n");
}
$countTraits = \count($this->getNode('traits'));
if ($countTraits) {
// traits
foreach ($this->getNode('traits') as $i =>
$trait) {
$this->compileLoadTemplate($compiler,
$trait->getNode('template'), sprintf('$_trait_%s',
$i));
$node = $trait->getNode('template');
$compiler
->addDebugInfo($node)
->write(sprintf("if
(!\$_trait_%s->isTraitable()) {\n", $i))
->indent()
->write("throw new RuntimeError('Template
\"'.")
->subcompile($trait->getNode('template'))
->raw(".'\" cannot be used as a
trait.', ")
->repr($node->getTemplateLine())
->raw(",
\$this->getSourceContext());\n")
->outdent()
->write("}\n")
->write(sprintf("\$_trait_%s_blocks =
\$_trait_%s->getBlocks();\n\n", $i, $i))
;
foreach ($trait->getNode('targets') as $key
=> $value) {
$compiler
->write(sprintf('if
(!isset($_trait_%s_blocks[', $i))
->string($key)
->raw("])) {\n")
->indent()
->write("throw new
RuntimeError(sprintf('Block ")
->string($key)
->raw(' is not defined in trait ')
->subcompile($trait->getNode('template'))
->raw(".'), ")
->repr($node->getTemplateLine())
->raw(",
\$this->getSourceContext());\n")
->outdent()
->write("}\n\n")
->write(sprintf('$_trait_%s_blocks[',
$i))
->subcompile($value)
->raw(sprintf('] =
$_trait_%s_blocks[', $i))
->string($key)
->raw(sprintf('];
unset($_trait_%s_blocks[', $i))
->string($key)
->raw("]);\n\n")
;
}
}
if ($countTraits > 1) {
$compiler
->write("\$this->traits =
array_merge(\n")
->indent()
;
for ($i = 0; $i < $countTraits; ++$i) {
$compiler
->write(sprintf('$_trait_%s_blocks'.($i == $countTraits - 1 ?
'' : ',')."\n", $i))
;
}
$compiler
->outdent()
->write(");\n\n")
;
} else {
$compiler
->write("\$this->traits =
\$_trait_0_blocks;\n\n")
;
}
$compiler
->write("\$this->blocks = array_merge(\n")
->indent()
->write("\$this->traits,\n")
->write("[\n")
;
} else {
$compiler
->write("\$this->blocks = [\n")
;
}
// blocks
$compiler
->indent()
;
foreach ($this->getNode('blocks') as $name =>
$node) {
$compiler
->write(sprintf("'%s' => [\$this,
'block_%s'],\n", $name, $name))
;
}
if ($countTraits) {
$compiler
->outdent()
->write("]\n")
->outdent()
->write(");\n")
;
} else {
$compiler
->outdent()
->write("];\n")
;
}
$compiler
->subcompile($this->getNode('constructor_end'))
->outdent()
->write("}\n\n")
;
}
protected function compileDisplay(Compiler $compiler)
{
$compiler
->write("protected function doDisplay(array \$context,
array \$blocks = [])\n", "{\n")
->indent()
->subcompile($this->getNode('display_start'))
->subcompile($this->getNode('body'))
;
if ($this->hasNode('parent')) {
$parent = $this->getNode('parent');
$compiler->addDebugInfo($parent);
if ($parent instanceof ConstantExpression) {
$compiler
->write('$this->parent =
$this->loadTemplate(')
->subcompile($parent)
->raw(', ')
->repr($this->getSourceContext()->getName())
->raw(', ')
->repr($parent->getTemplateLine())
->raw(");\n")
;
$compiler->write('$this->parent');
} else {
$compiler->write('$this->getParent($context)');
}
$compiler->raw("->display(\$context,
array_merge(\$this->blocks, \$blocks));\n");
}
$compiler
->subcompile($this->getNode('display_end'))
->outdent()
->write("}\n\n")
;
}
protected function compileClassFooter(Compiler $compiler)
{
$compiler
->subcompile($this->getNode('class_end'))
->outdent()
->write("}\n")
;
}
protected function compileMacros(Compiler $compiler)
{
$compiler->subcompile($this->getNode('macros'));
}
protected function compileGetTemplateName(Compiler $compiler)
{
$compiler
->write("public function getTemplateName()\n",
"{\n")
->indent()
->write('return ')
->repr($this->getSourceContext()->getName())
->raw(";\n")
->outdent()
->write("}\n\n")
;
}
protected function compileIsTraitable(Compiler $compiler)
{
// A template can be used as a trait if:
// * it has no parent
// * it has no macros
// * it has no body
//
// Put another way, a template can be used as a trait if it
// only contains blocks and use statements.
$traitable = !$this->hasNode('parent') && 0
=== \count($this->getNode('macros'));
if ($traitable) {
if ($this->getNode('body') instanceof BodyNode) {
$nodes =
$this->getNode('body')->getNode(0);
} else {
$nodes = $this->getNode('body');
}
if (!\count($nodes)) {
$nodes = new Node([$nodes]);
}
foreach ($nodes as $node) {
if (!\count($node)) {
continue;
}
if ($node instanceof TextNode &&
ctype_space($node->getAttribute('data'))) {
continue;
}
if ($node instanceof BlockReferenceNode) {
continue;
}
$traitable = false;
break;
}
}
if ($traitable) {
return;
}
$compiler
->write("public function isTraitable()\n",
"{\n")
->indent()
->write(sprintf("return %s;\n", $traitable ?
'true' : 'false'))
->outdent()
->write("}\n\n")
;
}
protected function compileDebugInfo(Compiler $compiler)
{
$compiler
->write("public function getDebugInfo()\n",
"{\n")
->indent()
->write(sprintf("return %s;\n",
str_replace("\n", '',
var_export(array_reverse($compiler->getDebugInfo(), true), true))))
->outdent()
->write("}\n\n")
;
}
protected function compileGetSource(Compiler $compiler)
{
$compiler
->write("/** @deprecated since 1.27 (to be removed in
2.0). Use getSourceContext() instead */\n")
->write("public function getSource()\n",
"{\n")
->indent()
->write("@trigger_error('The
'.__METHOD__.' method is deprecated since version 1.27 and will
be removed in 2.0. Use getSourceContext() instead.',
E_USER_DEPRECATED);\n\n")
->write('return
$this->getSourceContext()->getCode();')
->raw("\n")
->outdent()
->write("}\n\n")
;
}
protected function compileGetSourceContext(Compiler $compiler)
{
$compiler
->write("public function getSourceContext()\n",
"{\n")
->indent()
->write('return new Source(')
->string($compiler->getEnvironment()->isDebug() ?
$this->getSourceContext()->getCode() : '')
->raw(', ')
->string($this->getSourceContext()->getName())
->raw(', ')
->string($this->getSourceContext()->getPath())
->raw(");\n")
->outdent()
->write("}\n")
;
}
protected function compileLoadTemplate(Compiler $compiler, $node, $var)
{
if ($node instanceof ConstantExpression) {
$compiler
->write(sprintf('%s =
$this->loadTemplate(', $var))
->subcompile($node)
->raw(', ')
->repr($node->getTemplateName())
->raw(', ')
->repr($node->getTemplateLine())
->raw(");\n")
;
} else {
throw new \LogicException('Trait templates can only be
constant nodes.');
}
}
}
class_alias('Twig\Node\ModuleNode',
'Twig_Node_Module');
twig/src/Node/Node.php000064400000016545151161070030010575 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Source;
/**
* Represents a node in the AST.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Node implements \Twig_NodeInterface
{
protected $nodes;
protected $attributes;
protected $lineno;
protected $tag;
private $name;
private $sourceContext;
/**
* @param array $nodes An array of named nodes
* @param array $attributes An array of attributes (should not be
nodes)
* @param int $lineno The line number
* @param string $tag The tag name associated with the Node
*/
public function __construct(array $nodes = [], array $attributes = [],
$lineno = 0, $tag = null)
{
foreach ($nodes as $name => $node) {
if (!$node instanceof \Twig_NodeInterface) {
@trigger_error(sprintf('Using "%s" for the
value of node "%s" of "%s" is deprecated since version
1.25 and will be removed in 2.0.', \is_object($node) ?
\get_class($node) : (null === $node ? 'null' : \gettype($node)),
$name, \get_class($this)), E_USER_DEPRECATED);
}
}
$this->nodes = $nodes;
$this->attributes = $attributes;
$this->lineno = $lineno;
$this->tag = $tag;
}
public function __toString()
{
$attributes = [];
foreach ($this->attributes as $name => $value) {
$attributes[] = sprintf('%s: %s', $name,
str_replace("\n", '', var_export($value, true)));
}
$repr = [\get_class($this).'('.implode(', ',
$attributes)];
if (\count($this->nodes)) {
foreach ($this->nodes as $name => $node) {
$len = \strlen($name) + 4;
$noderepr = [];
foreach (explode("\n", (string) $node) as $line)
{
$noderepr[] = str_repeat(' ', $len).$line;
}
$repr[] = sprintf(' %s: %s', $name,
ltrim(implode("\n", $noderepr)));
}
$repr[] = ')';
} else {
$repr[0] .= ')';
}
return implode("\n", $repr);
}
/**
* @deprecated since 1.16.1 (to be removed in 2.0)
*/
public function toXml($asDom = false)
{
@trigger_error(sprintf('%s is deprecated since version 1.16.1
and will be removed in 2.0.', __METHOD__), E_USER_DEPRECATED);
$dom = new \DOMDocument('1.0', 'UTF-8');
$dom->formatOutput = true;
$dom->appendChild($xml =
$dom->createElement('twig'));
$xml->appendChild($node =
$dom->createElement('node'));
$node->setAttribute('class', \get_class($this));
foreach ($this->attributes as $name => $value) {
$node->appendChild($attribute =
$dom->createElement('attribute'));
$attribute->setAttribute('name', $name);
$attribute->appendChild($dom->createTextNode($value));
}
foreach ($this->nodes as $name => $n) {
if (null === $n) {
continue;
}
$child =
$n->toXml(true)->getElementsByTagName('node')->item(0);
$child = $dom->importNode($child, true);
$child->setAttribute('name', $name);
$node->appendChild($child);
}
return $asDom ? $dom : $dom->saveXML();
}
public function compile(Compiler $compiler)
{
foreach ($this->nodes as $node) {
$node->compile($compiler);
}
}
public function getTemplateLine()
{
return $this->lineno;
}
/**
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function getLine()
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0. Use
getTemplateLine() instead.', E_USER_DEPRECATED);
return $this->lineno;
}
public function getNodeTag()
{
return $this->tag;
}
/**
* @return bool
*/
public function hasAttribute($name)
{
return \array_key_exists($name, $this->attributes);
}
/**
* @return mixed
*/
public function getAttribute($name)
{
if (!\array_key_exists($name, $this->attributes)) {
throw new \LogicException(sprintf('Attribute
"%s" does not exist for Node "%s".', $name,
\get_class($this)));
}
return $this->attributes[$name];
}
/**
* @param string $name
* @param mixed $value
*/
public function setAttribute($name, $value)
{
$this->attributes[$name] = $value;
}
public function removeAttribute($name)
{
unset($this->attributes[$name]);
}
/**
* @return bool
*/
public function hasNode($name)
{
return \array_key_exists($name, $this->nodes);
}
/**
* @return Node
*/
public function getNode($name)
{
if (!\array_key_exists($name, $this->nodes)) {
throw new \LogicException(sprintf('Node "%s"
does not exist for Node "%s".', $name, \get_class($this)));
}
return $this->nodes[$name];
}
public function setNode($name, $node = null)
{
if (!$node instanceof \Twig_NodeInterface) {
@trigger_error(sprintf('Using "%s" for the value
of node "%s" of "%s" is deprecated since version 1.25
and will be removed in 2.0.', \is_object($node) ? \get_class($node) :
(null === $node ? 'null' : \gettype($node)), $name,
\get_class($this)), E_USER_DEPRECATED);
}
$this->nodes[$name] = $node;
}
public function removeNode($name)
{
unset($this->nodes[$name]);
}
public function count()
{
return \count($this->nodes);
}
public function getIterator()
{
return new \ArrayIterator($this->nodes);
}
public function setTemplateName($name)
{
$this->name = $name;
foreach ($this->nodes as $node) {
if (null !== $node) {
$node->setTemplateName($name);
}
}
}
public function getTemplateName()
{
return $this->name;
}
public function setSourceContext(Source $source)
{
$this->sourceContext = $source;
foreach ($this->nodes as $node) {
if ($node instanceof Node) {
$node->setSourceContext($source);
}
}
}
public function getSourceContext()
{
return $this->sourceContext;
}
/**
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function setFilename($name)
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0. Use
setTemplateName() instead.', E_USER_DEPRECATED);
$this->setTemplateName($name);
}
/**
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function getFilename()
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0. Use
getTemplateName() instead.', E_USER_DEPRECATED);
return $this->name;
}
}
class_alias('Twig\Node\Node', 'Twig_Node');
// Ensure that the aliased name is loaded to keep BC for classes
implementing the typehint with the old aliased name.
class_exists('Twig\Compiler');
twig/src/Node/NodeCaptureInterface.php000064400000000715151161070030013732
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
/**
* Represents a node that captures any nested displayable nodes.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface NodeCaptureInterface
{
}
class_alias('Twig\Node\NodeCaptureInterface',
'Twig_NodeCaptureInterface');
twig/src/Node/NodeOutputInterface.php000064400000000666151161070030013634
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
/**
* Represents a displayable node in the AST.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface NodeOutputInterface
{
}
class_alias('Twig\Node\NodeOutputInterface',
'Twig_NodeOutputInterface');
twig/src/Node/PrintNode.php000064400000001635151161070030011604
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\AbstractExpression;
/**
* Represents a node that outputs an expression.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class PrintNode extends Node implements NodeOutputInterface
{
public function __construct(AbstractExpression $expr, $lineno, $tag =
null)
{
parent::__construct(['expr' => $expr], [], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('echo ')
->subcompile($this->getNode('expr'))
->raw(";\n")
;
}
}
class_alias('Twig\Node\PrintNode', 'Twig_Node_Print');
twig/src/Node/SandboxedPrintNode.php000064400000003457151161070030013440
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
/**
* Adds a check for the __toString() method when the variable is an object
and the sandbox is activated.
*
* When there is a simple Print statement, like {{ article }},
* and if the sandbox is enabled, we need to check that the __toString()
* method is allowed if 'article' is an object.
*
* Not used anymore, to be deprecated in 2.x and removed in 3.0
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SandboxedPrintNode extends PrintNode
{
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('echo ')
;
$expr = $this->getNode('expr');
if ($expr instanceof ConstantExpression) {
$compiler
->subcompile($expr)
->raw(";\n")
;
} else {
$compiler
->write('$this->env->getExtension(\'\Twig\Extension\SandboxExtension\')->ensureToStringAllowed(')
->subcompile($expr)
->raw(");\n")
;
}
}
/**
* Removes node filters.
*
* This is mostly needed when another visitor adds filters (like the
escaper one).
*
* @return Node
*/
protected function removeNodeFilter(Node $node)
{
if ($node instanceof FilterExpression) {
return
$this->removeNodeFilter($node->getNode('node'));
}
return $node;
}
}
class_alias('Twig\Node\SandboxedPrintNode',
'Twig_Node_SandboxedPrint');
twig/src/Node/SandboxNode.php000064400000002215151161070030012101
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents a sandbox node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SandboxNode extends Node
{
public function __construct(\Twig_NodeInterface $body, $lineno, $tag =
null)
{
parent::__construct(['body' => $body], [], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write("if (!\$alreadySandboxed =
\$this->sandbox->isSandboxed()) {\n")
->indent()
->write("\$this->sandbox->enableSandbox();\n")
->outdent()
->write("}\n")
->subcompile($this->getNode('body'))
->write("if (!\$alreadySandboxed) {\n")
->indent()
->write("\$this->sandbox->disableSandbox();\n")
->outdent()
->write("}\n")
;
}
}
class_alias('Twig\Node\SandboxNode',
'Twig_Node_Sandbox');
twig/src/Node/SetNode.php000064400000006547151161070030011252
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
use Twig\Node\Expression\ConstantExpression;
/**
* Represents a set node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SetNode extends Node implements NodeCaptureInterface
{
public function __construct($capture, \Twig_NodeInterface $names,
\Twig_NodeInterface $values, $lineno, $tag = null)
{
parent::__construct(['names' => $names,
'values' => $values], ['capture' => $capture,
'safe' => false], $lineno, $tag);
/*
* Optimizes the node when capture is used for a large block of
text.
*
* {% set foo %}foo{% endset %} is compiled to
$context['foo'] = new Twig\Markup("foo");
*/
if ($this->getAttribute('capture')) {
$this->setAttribute('safe', true);
$values = $this->getNode('values');
if ($values instanceof TextNode) {
$this->setNode('values', new
ConstantExpression($values->getAttribute('data'),
$values->getTemplateLine()));
$this->setAttribute('capture', false);
}
}
}
public function compile(Compiler $compiler)
{
$compiler->addDebugInfo($this);
if (\count($this->getNode('names')) > 1) {
$compiler->write('list(');
foreach ($this->getNode('names') as $idx =>
$node) {
if ($idx) {
$compiler->raw(', ');
}
$compiler->subcompile($node);
}
$compiler->raw(')');
} else {
if ($this->getAttribute('capture')) {
if ($compiler->getEnvironment()->isDebug()) {
$compiler->write("ob_start();\n");
} else {
$compiler->write("ob_start(function () { return
''; });\n");
}
$compiler
->subcompile($this->getNode('values'))
;
}
$compiler->subcompile($this->getNode('names'),
false);
if ($this->getAttribute('capture')) {
$compiler->raw(" = ('' === \$tmp =
ob_get_clean()) ? '' : new Markup(\$tmp,
\$this->env->getCharset())");
}
}
if (!$this->getAttribute('capture')) {
$compiler->raw(' = ');
if (\count($this->getNode('names')) > 1) {
$compiler->write('[');
foreach ($this->getNode('values') as $idx
=> $value) {
if ($idx) {
$compiler->raw(', ');
}
$compiler->subcompile($value);
}
$compiler->raw(']');
} else {
if ($this->getAttribute('safe')) {
$compiler
->raw("('' === \$tmp = ")
->subcompile($this->getNode('values'))
->raw(") ? '' : new Markup(\$tmp,
\$this->env->getCharset())")
;
} else {
$compiler->subcompile($this->getNode('values'));
}
}
}
$compiler->raw(";\n");
}
}
class_alias('Twig\Node\SetNode', 'Twig_Node_Set');
twig/src/Node/SetTempNode.php000064400000001644151161070030012071
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* @internal
*/
class SetTempNode extends Node
{
public function __construct($name, $lineno)
{
parent::__construct([], ['name' => $name], $lineno);
}
public function compile(Compiler $compiler)
{
$name = $this->getAttribute('name');
$compiler
->addDebugInfo($this)
->write('if (isset($context[')
->string($name)
->raw('])) { $_')
->raw($name)
->raw('_ = $context[')
->repr($name)
->raw(']; } else { $_')
->raw($name)
->raw("_ = null; }\n")
;
}
}
class_alias('Twig\Node\SetTempNode',
'Twig_Node_SetTemp');
twig/src/Node/SpacelessNode.php000064400000002153151161070030012426
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents a spaceless node.
*
* It removes spaces between HTML tags.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SpacelessNode extends Node
{
public function __construct(\Twig_NodeInterface $body, $lineno, $tag =
'spaceless')
{
parent::__construct(['body' => $body], [], $lineno,
$tag);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
;
if ($compiler->getEnvironment()->isDebug()) {
$compiler->write("ob_start();\n");
} else {
$compiler->write("ob_start(function () { return
''; });\n");
}
$compiler
->subcompile($this->getNode('body'))
->write("echo
trim(preg_replace('/>\s+</', '><',
ob_get_clean()));\n")
;
}
}
class_alias('Twig\Node\SpacelessNode',
'Twig_Node_Spaceless');
twig/src/Node/TextNode.php000064400000001462151161070030011432
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents a text node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TextNode extends Node implements NodeOutputInterface
{
public function __construct($data, $lineno)
{
parent::__construct([], ['data' => $data], $lineno);
}
public function compile(Compiler $compiler)
{
$compiler
->addDebugInfo($this)
->write('echo ')
->string($this->getAttribute('data'))
->raw(";\n")
;
}
}
class_alias('Twig\Node\TextNode', 'Twig_Node_Text');
twig/src/Node/WithNode.php000064400000004241151161070030011417
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Node;
use Twig\Compiler;
/**
* Represents a nested "with" scope.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class WithNode extends Node
{
public function __construct(Node $body, Node $variables = null, $only =
false, $lineno, $tag = null)
{
$nodes = ['body' => $body];
if (null !== $variables) {
$nodes['variables'] = $variables;
}
parent::__construct($nodes, ['only' => (bool) $only],
$lineno, $tag);
}
public function compile(Compiler $compiler)
{
$compiler->addDebugInfo($this);
if ($this->hasNode('variables')) {
$node = $this->getNode('variables');
$varsName = $compiler->getVarName();
$compiler
->write(sprintf('$%s = ', $varsName))
->subcompile($node)
->raw(";\n")
->write(sprintf("if (!twig_test_iterable(\$%s))
{\n", $varsName))
->indent()
->write("throw new RuntimeError('Variables
passed to the \"with\" tag must be a hash.', ")
->repr($node->getTemplateLine())
->raw(", \$this->getSourceContext());\n")
->outdent()
->write("}\n")
->write(sprintf("\$%s =
twig_to_array(\$%s);\n", $varsName, $varsName))
;
if ($this->getAttribute('only')) {
$compiler->write("\$context = ['_parent'
=> \$context];\n");
} else {
$compiler->write("\$context['_parent'] =
\$context;\n");
}
$compiler->write(sprintf("\$context =
\$this->env->mergeGlobals(array_merge(\$context, \$%s));\n",
$varsName));
} else {
$compiler->write("\$context['_parent'] =
\$context;\n");
}
$compiler
->subcompile($this->getNode('body'))
->write("\$context =
\$context['_parent'];\n")
;
}
}
class_alias('Twig\Node\WithNode', 'Twig_Node_With');
twig/src/NodeTraverser.php000064400000004040151161070030011571
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\NodeVisitor\NodeVisitorInterface;
/**
* A node traverser.
*
* It visits all nodes and their children and calls the given visitor for
each.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class NodeTraverser
{
protected $env;
protected $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.
*
* @return \Twig_NodeInterface
*/
public function traverse(\Twig_NodeInterface $node)
{
ksort($this->visitors);
foreach ($this->visitors as $visitors) {
foreach ($visitors as $visitor) {
$node = $this->traverseForVisitor($visitor, $node);
}
}
return $node;
}
protected function traverseForVisitor(NodeVisitorInterface $visitor,
\Twig_NodeInterface $node = null)
{
if (null === $node) {
return;
}
$node = $visitor->enterNode($node, $this->env);
foreach ($node as $k => $n) {
if (null === $n) {
continue;
}
if (false !== ($m = $this->traverseForVisitor($visitor, $n))
&& null !== $m) {
if ($m !== $n) {
$node->setNode($k, $m);
}
} else {
$node->removeNode($k);
}
}
return $visitor->leaveNode($node, $this->env);
}
}
class_alias('Twig\NodeTraverser',
'Twig_NodeTraverser');
twig/src/NodeVisitor/AbstractNodeVisitor.php000064400000003061151161070030015206
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\Node;
/**
* Used to make node visitors compatible with Twig 1.x and 2.x.
*
* To be removed in Twig 3.1.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class AbstractNodeVisitor implements NodeVisitorInterface
{
final public function enterNode(\Twig_NodeInterface $node, Environment
$env)
{
if (!$node instanceof Node) {
throw new \LogicException(sprintf('%s only supports
\Twig\Node\Node instances.', __CLASS__));
}
return $this->doEnterNode($node, $env);
}
final public function leaveNode(\Twig_NodeInterface $node, Environment
$env)
{
if (!$node instanceof Node) {
throw new \LogicException(sprintf('%s only supports
\Twig\Node\Node instances.', __CLASS__));
}
return $this->doLeaveNode($node, $env);
}
/**
* Called before child nodes are visited.
*
* @return Node The modified node
*/
abstract protected function doEnterNode(Node $node, Environment $env);
/**
* Called after child nodes are visited.
*
* @return Node|false|null The modified node or null if the node must
be removed
*/
abstract protected function doLeaveNode(Node $node, Environment $env);
}
class_alias('Twig\NodeVisitor\AbstractNodeVisitor',
'Twig_BaseNodeVisitor');
twig/src/NodeVisitor/EscaperNodeVisitor.php000064400000016054151161070030015033
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\AutoEscapeNode;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
use Twig\Node\DoNode;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\InlinePrint;
use Twig\Node\ImportNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\NodeTraverser;
/**
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class EscaperNodeVisitor extends AbstractNodeVisitor
{
protected $statusStack = [];
protected $blocks = [];
protected $safeAnalysis;
protected $traverser;
protected $defaultStrategy = false;
protected $safeVars = [];
public function __construct()
{
$this->safeAnalysis = new SafeAnalysisNodeVisitor();
}
protected function doEnterNode(Node $node, Environment $env)
{
if ($node instanceof ModuleNode) {
if
($env->hasExtension('\Twig\Extension\EscaperExtension')
&& $defaultStrategy =
$env->getExtension('\Twig\Extension\EscaperExtension')->getDefaultStrategy($node->getTemplateName()))
{
$this->defaultStrategy = $defaultStrategy;
}
$this->safeVars = [];
$this->blocks = [];
} elseif ($node instanceof AutoEscapeNode) {
$this->statusStack[] =
$node->getAttribute('value');
} elseif ($node instanceof BlockNode) {
$this->statusStack[] =
isset($this->blocks[$node->getAttribute('name')]) ?
$this->blocks[$node->getAttribute('name')] :
$this->needEscaping($env);
} elseif ($node instanceof ImportNode) {
$this->safeVars[] =
$node->getNode('var')->getAttribute('name');
}
return $node;
}
protected function doLeaveNode(Node $node, Environment $env)
{
if ($node instanceof ModuleNode) {
$this->defaultStrategy = false;
$this->safeVars = [];
$this->blocks = [];
} elseif ($node instanceof FilterExpression) {
return $this->preEscapeFilterNode($node, $env);
} elseif ($node instanceof PrintNode && false !== $type =
$this->needEscaping($env)) {
$expression = $node->getNode('expr');
if ($expression instanceof ConditionalExpression &&
$this->shouldUnwrapConditional($expression, $env, $type)) {
return new DoNode($this->unwrapConditional($expression,
$env, $type), $expression->getTemplateLine());
}
return $this->escapePrintNode($node, $env, $type);
}
if ($node instanceof AutoEscapeNode || $node instanceof BlockNode)
{
array_pop($this->statusStack);
} elseif ($node instanceof BlockReferenceNode) {
$this->blocks[$node->getAttribute('name')] =
$this->needEscaping($env);
}
return $node;
}
private function shouldUnwrapConditional(ConditionalExpression
$expression, Environment $env, $type)
{
$expr2Safe = $this->isSafeFor($type,
$expression->getNode('expr2'), $env);
$expr3Safe = $this->isSafeFor($type,
$expression->getNode('expr3'), $env);
return $expr2Safe !== $expr3Safe;
}
private function unwrapConditional(ConditionalExpression $expression,
Environment $env, $type)
{
// convert "echo a ? b : c" to "a ? echo b : echo
c" recursively
$expr2 = $expression->getNode('expr2');
if ($expr2 instanceof ConditionalExpression &&
$this->shouldUnwrapConditional($expr2, $env, $type)) {
$expr2 = $this->unwrapConditional($expr2, $env, $type);
} else {
$expr2 = $this->escapeInlinePrintNode(new
InlinePrint($expr2, $expr2->getTemplateLine()), $env, $type);
}
$expr3 = $expression->getNode('expr3');
if ($expr3 instanceof ConditionalExpression &&
$this->shouldUnwrapConditional($expr3, $env, $type)) {
$expr3 = $this->unwrapConditional($expr3, $env, $type);
} else {
$expr3 = $this->escapeInlinePrintNode(new
InlinePrint($expr3, $expr3->getTemplateLine()), $env, $type);
}
return new
ConditionalExpression($expression->getNode('expr1'), $expr2,
$expr3, $expression->getTemplateLine());
}
private function escapeInlinePrintNode(InlinePrint $node, Environment
$env, $type)
{
$expression = $node->getNode('node');
if ($this->isSafeFor($type, $expression, $env)) {
return $node;
}
return new InlinePrint($this->getEscaperFilter($type,
$expression), $node->getTemplateLine());
}
protected function escapePrintNode(PrintNode $node, Environment $env,
$type)
{
if (false === $type) {
return $node;
}
$expression = $node->getNode('expr');
if ($this->isSafeFor($type, $expression, $env)) {
return $node;
}
$class = \get_class($node);
return new $class($this->getEscaperFilter($type, $expression),
$node->getTemplateLine());
}
protected function preEscapeFilterNode(FilterExpression $filter,
Environment $env)
{
$name =
$filter->getNode('filter')->getAttribute('value');
$type = $env->getFilter($name)->getPreEscape();
if (null === $type) {
return $filter;
}
$node = $filter->getNode('node');
if ($this->isSafeFor($type, $node, $env)) {
return $filter;
}
$filter->setNode('node',
$this->getEscaperFilter($type, $node));
return $filter;
}
protected function isSafeFor($type, \Twig_NodeInterface $expression,
$env)
{
$safe = $this->safeAnalysis->getSafe($expression);
if (null === $safe) {
if (null === $this->traverser) {
$this->traverser = new NodeTraverser($env,
[$this->safeAnalysis]);
}
$this->safeAnalysis->setSafeVars($this->safeVars);
$this->traverser->traverse($expression);
$safe = $this->safeAnalysis->getSafe($expression);
}
return \in_array($type, $safe) || \in_array('all',
$safe);
}
protected function needEscaping(Environment $env)
{
if (\count($this->statusStack)) {
return $this->statusStack[\count($this->statusStack) -
1];
}
return $this->defaultStrategy ? $this->defaultStrategy :
false;
}
protected function getEscaperFilter($type, \Twig_NodeInterface $node)
{
$line = $node->getTemplateLine();
$name = new ConstantExpression('escape', $line);
$args = new Node([new ConstantExpression((string) $type, $line),
new ConstantExpression(null, $line), new ConstantExpression(true, $line)]);
return new FilterExpression($node, $name, $args, $line);
}
public function getPriority()
{
return 0;
}
}
class_alias('Twig\NodeVisitor\EscaperNodeVisitor',
'Twig_NodeVisitor_Escaper');
twig/src/NodeVisitor/NodeVisitorInterface.php000064400000002403151161070030015342
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
/**
* Interface for node visitor classes.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface NodeVisitorInterface
{
/**
* Called before child nodes are visited.
*
* @return \Twig_NodeInterface The modified node
*/
public function enterNode(\Twig_NodeInterface $node, Environment $env);
/**
* Called after child nodes are visited.
*
* @return \Twig_NodeInterface|false|null The modified node or null if
the node must be removed
*/
public function leaveNode(\Twig_NodeInterface $node, Environment $env);
/**
* Returns the priority for this visitor.
*
* Priority should be between -10 and 10 (0 is the default).
*
* @return int The priority level
*/
public function getPriority();
}
class_alias('Twig\NodeVisitor\NodeVisitorInterface',
'Twig_NodeVisitorInterface');
// Ensure that the aliased name is loaded to keep BC for classes
implementing the typehint with the old aliased name.
class_exists('Twig\Environment');
twig/src/NodeVisitor/OptimizerNodeVisitor.php000064400000021370151161070030015430
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\BlockReferenceNode;
use Twig\Node\BodyNode;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\ParentExpression;
use Twig\Node\Expression\TempNameExpression;
use Twig\Node\ForNode;
use Twig\Node\IncludeNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Node\SetTempNode;
/**
* Tries to optimize the AST.
*
* This visitor is always the last registered one.
*
* You can configure which optimizations you want to activate via the
* optimizer mode.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class OptimizerNodeVisitor extends AbstractNodeVisitor
{
const OPTIMIZE_ALL = -1;
const OPTIMIZE_NONE = 0;
const OPTIMIZE_FOR = 2;
const OPTIMIZE_RAW_FILTER = 4;
const OPTIMIZE_VAR_ACCESS = 8;
protected $loops = [];
protected $loopsTargets = [];
protected $optimizers;
protected $prependedNodes = [];
protected $inABody = false;
/**
* @param int $optimizers The optimizer mode
*/
public function __construct($optimizers = -1)
{
if (!\is_int($optimizers) || $optimizers > (self::OPTIMIZE_FOR |
self::OPTIMIZE_RAW_FILTER | self::OPTIMIZE_VAR_ACCESS)) {
throw new \InvalidArgumentException(sprintf('Optimizer
mode "%s" is not valid.', $optimizers));
}
$this->optimizers = $optimizers;
}
protected function doEnterNode(Node $node, Environment $env)
{
if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR &
$this->optimizers)) {
$this->enterOptimizeFor($node, $env);
}
if (\PHP_VERSION_ID < 50400 && self::OPTIMIZE_VAR_ACCESS
=== (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) &&
!$env->isStrictVariables() &&
!$env->hasExtension('\Twig\Extension\SandboxExtension')) {
if ($this->inABody) {
if (!$node instanceof AbstractExpression) {
if ('Twig_Node' !== \get_class($node)) {
array_unshift($this->prependedNodes, []);
}
} else {
$node = $this->optimizeVariables($node, $env);
}
} elseif ($node instanceof BodyNode) {
$this->inABody = true;
}
}
return $node;
}
protected function doLeaveNode(Node $node, Environment $env)
{
$expression = $node instanceof AbstractExpression;
if (self::OPTIMIZE_FOR === (self::OPTIMIZE_FOR &
$this->optimizers)) {
$this->leaveOptimizeFor($node, $env);
}
if (self::OPTIMIZE_RAW_FILTER === (self::OPTIMIZE_RAW_FILTER &
$this->optimizers)) {
$node = $this->optimizeRawFilter($node, $env);
}
$node = $this->optimizePrintNode($node, $env);
if (self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS &
$this->optimizers) && !$env->isStrictVariables() &&
!$env->hasExtension('\Twig\Extension\SandboxExtension')) {
if ($node instanceof BodyNode) {
$this->inABody = false;
} elseif ($this->inABody) {
if (!$expression && 'Twig_Node' !==
\get_class($node) && $prependedNodes =
array_shift($this->prependedNodes)) {
$nodes = [];
foreach (array_unique($prependedNodes) as $name) {
$nodes[] = new SetTempNode($name,
$node->getTemplateLine());
}
$nodes[] = $node;
$node = new Node($nodes);
}
}
}
return $node;
}
protected function optimizeVariables(\Twig_NodeInterface $node,
Environment $env)
{
if ('Twig_Node_Expression_Name' === \get_class($node)
&& $node->isSimple()) {
$this->prependedNodes[0][] =
$node->getAttribute('name');
return new
TempNameExpression($node->getAttribute('name'),
$node->getTemplateLine());
}
return $node;
}
/**
* Optimizes print nodes.
*
* It replaces:
*
* * "echo $this->render(Parent)Block()" with
"$this->display(Parent)Block()"
*
* @return \Twig_NodeInterface
*/
protected function optimizePrintNode(\Twig_NodeInterface $node,
Environment $env)
{
if (!$node instanceof PrintNode) {
return $node;
}
$exprNode = $node->getNode('expr');
if (
$exprNode instanceof BlockReferenceExpression ||
$exprNode instanceof ParentExpression
) {
$exprNode->setAttribute('output', true);
return $exprNode;
}
return $node;
}
/**
* Removes "raw" filters.
*
* @return \Twig_NodeInterface
*/
protected function optimizeRawFilter(\Twig_NodeInterface $node,
Environment $env)
{
if ($node instanceof FilterExpression && 'raw' ==
$node->getNode('filter')->getAttribute('value'))
{
return $node->getNode('node');
}
return $node;
}
/**
* Optimizes "for" tag by removing the "loop"
variable creation whenever possible.
*/
protected function enterOptimizeFor(\Twig_NodeInterface $node,
Environment $env)
{
if ($node instanceof ForNode) {
// disable the loop variable by default
$node->setAttribute('with_loop', false);
array_unshift($this->loops, $node);
array_unshift($this->loopsTargets,
$node->getNode('value_target')->getAttribute('name'));
array_unshift($this->loopsTargets,
$node->getNode('key_target')->getAttribute('name'));
} elseif (!$this->loops) {
// we are outside a loop
return;
}
// when do we need to add the loop variable back?
// the loop variable is referenced for the current loop
elseif ($node instanceof NameExpression && 'loop'
=== $node->getAttribute('name')) {
$node->setAttribute('always_defined', true);
$this->addLoopToCurrent();
}
// optimize access to loop targets
elseif ($node instanceof NameExpression &&
\in_array($node->getAttribute('name'),
$this->loopsTargets)) {
$node->setAttribute('always_defined', true);
}
// block reference
elseif ($node instanceof BlockReferenceNode || $node instanceof
BlockReferenceExpression) {
$this->addLoopToCurrent();
}
// include without the only attribute
elseif ($node instanceof IncludeNode &&
!$node->getAttribute('only')) {
$this->addLoopToAll();
}
// include function without the with_context=false parameter
elseif ($node instanceof FunctionExpression
&& 'include' ===
$node->getAttribute('name')
&&
(!$node->getNode('arguments')->hasNode('with_context')
|| false !==
$node->getNode('arguments')->getNode('with_context')->getAttribute('value')
)
) {
$this->addLoopToAll();
}
// the loop variable is referenced via an attribute
elseif ($node instanceof GetAttrExpression
&& (!$node->getNode('attribute')
instanceof ConstantExpression
|| 'parent' ===
$node->getNode('attribute')->getAttribute('value')
)
&& (true ===
$this->loops[0]->getAttribute('with_loop')
|| ($node->getNode('node') instanceof
NameExpression
&& 'loop' ===
$node->getNode('node')->getAttribute('name')
)
)
) {
$this->addLoopToAll();
}
}
/**
* Optimizes "for" tag by removing the "loop"
variable creation whenever possible.
*/
protected function leaveOptimizeFor(\Twig_NodeInterface $node,
Environment $env)
{
if ($node instanceof ForNode) {
array_shift($this->loops);
array_shift($this->loopsTargets);
array_shift($this->loopsTargets);
}
}
protected function addLoopToCurrent()
{
$this->loops[0]->setAttribute('with_loop', true);
}
protected function addLoopToAll()
{
foreach ($this->loops as $loop) {
$loop->setAttribute('with_loop', true);
}
}
public function getPriority()
{
return 255;
}
}
class_alias('Twig\NodeVisitor\OptimizerNodeVisitor',
'Twig_NodeVisitor_Optimizer');
twig/src/NodeVisitor/SafeAnalysisNodeVisitor.php000064400000012016151161070030016025
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConditionalExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\MethodCallExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\Expression\ParentExpression;
use Twig\Node\Node;
/**
* @final
*/
class SafeAnalysisNodeVisitor extends AbstractNodeVisitor
{
protected $data = [];
protected $safeVars = [];
public function setSafeVars($safeVars)
{
$this->safeVars = $safeVars;
}
public function getSafe(\Twig_NodeInterface $node)
{
$hash = spl_object_hash($node);
if (!isset($this->data[$hash])) {
return;
}
foreach ($this->data[$hash] as $bucket) {
if ($bucket['key'] !== $node) {
continue;
}
if (\in_array('html_attr',
$bucket['value'])) {
$bucket['value'][] = 'html';
}
return $bucket['value'];
}
}
protected function setSafe(\Twig_NodeInterface $node, array $safe)
{
$hash = spl_object_hash($node);
if (isset($this->data[$hash])) {
foreach ($this->data[$hash] as &$bucket) {
if ($bucket['key'] === $node) {
$bucket['value'] = $safe;
return;
}
}
}
$this->data[$hash][] = [
'key' => $node,
'value' => $safe,
];
}
protected function doEnterNode(Node $node, Environment $env)
{
return $node;
}
protected function doLeaveNode(Node $node, Environment $env)
{
if ($node instanceof ConstantExpression) {
// constants are marked safe for all
$this->setSafe($node, ['all']);
} elseif ($node instanceof BlockReferenceExpression) {
// blocks are safe by definition
$this->setSafe($node, ['all']);
} elseif ($node instanceof ParentExpression) {
// parent block is safe by definition
$this->setSafe($node, ['all']);
} elseif ($node instanceof ConditionalExpression) {
// intersect safeness of both operands
$safe =
$this->intersectSafe($this->getSafe($node->getNode('expr2')),
$this->getSafe($node->getNode('expr3')));
$this->setSafe($node, $safe);
} elseif ($node instanceof FilterExpression) {
// filter expression is safe when the filter is safe
$name =
$node->getNode('filter')->getAttribute('value');
$args = $node->getNode('arguments');
if (false !== $filter = $env->getFilter($name)) {
$safe = $filter->getSafe($args);
if (null === $safe) {
$safe =
$this->intersectSafe($this->getSafe($node->getNode('node')),
$filter->getPreservesSafety());
}
$this->setSafe($node, $safe);
} else {
$this->setSafe($node, []);
}
} elseif ($node instanceof FunctionExpression) {
// function expression is safe when the function is safe
$name = $node->getAttribute('name');
$args = $node->getNode('arguments');
$function = $env->getFunction($name);
if (false !== $function) {
$this->setSafe($node, $function->getSafe($args));
} else {
$this->setSafe($node, []);
}
} elseif ($node instanceof MethodCallExpression) {
if ($node->getAttribute('safe')) {
$this->setSafe($node, ['all']);
} else {
$this->setSafe($node, []);
}
} elseif ($node instanceof GetAttrExpression &&
$node->getNode('node') instanceof NameExpression) {
$name =
$node->getNode('node')->getAttribute('name');
// attributes on template instances are safe
if ('_self' == $name || \in_array($name,
$this->safeVars)) {
$this->setSafe($node, ['all']);
} else {
$this->setSafe($node, []);
}
} else {
$this->setSafe($node, []);
}
return $node;
}
protected function intersectSafe(array $a = null, array $b = null)
{
if (null === $a || null === $b) {
return [];
}
if (\in_array('all', $a)) {
return $b;
}
if (\in_array('all', $b)) {
return $a;
}
return array_intersect($a, $b);
}
public function getPriority()
{
return 0;
}
}
class_alias('Twig\NodeVisitor\SafeAnalysisNodeVisitor',
'Twig_NodeVisitor_SafeAnalysis');
twig/src/NodeVisitor/SandboxNodeVisitor.php000064400000010321151161070030015036
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\NodeVisitor;
use Twig\Environment;
use Twig\Node\CheckSecurityNode;
use Twig\Node\CheckToStringNode;
use Twig\Node\Expression\Binary\ConcatBinary;
use Twig\Node\Expression\Binary\RangeBinary;
use Twig\Node\Expression\FilterExpression;
use Twig\Node\Expression\FunctionExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Node\SetNode;
/**
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SandboxNodeVisitor extends AbstractNodeVisitor
{
protected $inAModule = false;
protected $tags;
protected $filters;
protected $functions;
private $needsToStringWrap = false;
protected function doEnterNode(Node $node, Environment $env)
{
if ($node instanceof ModuleNode) {
$this->inAModule = true;
$this->tags = [];
$this->filters = [];
$this->functions = [];
return $node;
} elseif ($this->inAModule) {
// look for tags
if ($node->getNodeTag() &&
!isset($this->tags[$node->getNodeTag()])) {
$this->tags[$node->getNodeTag()] = $node;
}
// look for filters
if ($node instanceof FilterExpression &&
!isset($this->filters[$node->getNode('filter')->getAttribute('value')]))
{
$this->filters[$node->getNode('filter')->getAttribute('value')]
= $node;
}
// look for functions
if ($node instanceof FunctionExpression &&
!isset($this->functions[$node->getAttribute('name')])) {
$this->functions[$node->getAttribute('name')] = $node;
}
// the .. operator is equivalent to the range() function
if ($node instanceof RangeBinary &&
!isset($this->functions['range'])) {
$this->functions['range'] = $node;
}
if ($node instanceof PrintNode) {
$this->needsToStringWrap = true;
$this->wrapNode($node, 'expr');
}
if ($node instanceof SetNode &&
!$node->getAttribute('capture')) {
$this->needsToStringWrap = true;
}
// wrap outer nodes that can implicitly call __toString()
if ($this->needsToStringWrap) {
if ($node instanceof ConcatBinary) {
$this->wrapNode($node, 'left');
$this->wrapNode($node, 'right');
}
if ($node instanceof FilterExpression) {
$this->wrapNode($node, 'node');
$this->wrapArrayNode($node, 'arguments');
}
if ($node instanceof FunctionExpression) {
$this->wrapArrayNode($node, 'arguments');
}
}
}
return $node;
}
protected function doLeaveNode(Node $node, Environment $env)
{
if ($node instanceof ModuleNode) {
$this->inAModule = false;
$node->getNode('constructor_end')->setNode('_security_check',
new Node([new CheckSecurityNode($this->filters, $this->tags,
$this->functions), $node->getNode('display_start')]));
} elseif ($this->inAModule) {
if ($node instanceof PrintNode || $node instanceof SetNode) {
$this->needsToStringWrap = false;
}
}
return $node;
}
private function wrapNode(Node $node, $name)
{
$expr = $node->getNode($name);
if ($expr instanceof NameExpression || $expr instanceof
GetAttrExpression) {
$node->setNode($name, new CheckToStringNode($expr));
}
}
private function wrapArrayNode(Node $node, $name)
{
$args = $node->getNode($name);
foreach ($args as $name => $_) {
$this->wrapNode($args, $name);
}
}
public function getPriority()
{
return 0;
}
}
class_alias('Twig\NodeVisitor\SandboxNodeVisitor',
'Twig_NodeVisitor_Sandbox');
twig/src/Parser.php000064400000032630151161070030010250 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
use Twig\Node\BodyNode;
use Twig\Node\Expression\AbstractExpression;
use Twig\Node\MacroNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\Node\NodeCaptureInterface;
use Twig\Node\NodeOutputInterface;
use Twig\Node\PrintNode;
use Twig\Node\TextNode;
use Twig\NodeVisitor\NodeVisitorInterface;
use Twig\TokenParser\TokenParserInterface;
/**
* Default parser implementation.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Parser implements \Twig_ParserInterface
{
protected $stack = [];
protected $stream;
protected $parent;
protected $handlers;
protected $visitors;
protected $expressionParser;
protected $blocks;
protected $blockStack;
protected $macros;
protected $env;
protected $reservedMacroNames;
protected $importedSymbols;
protected $traits;
protected $embeddedTemplates = [];
private $varNameSalt = 0;
public function __construct(Environment $env)
{
$this->env = $env;
}
/**
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function getEnvironment()
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0.',
E_USER_DEPRECATED);
return $this->env;
}
public function getVarName()
{
return sprintf('__internal_%s', hash('sha256',
__METHOD__.$this->stream->getSourceContext()->getCode().$this->varNameSalt++));
}
/**
* @deprecated since 1.27 (to be removed in 2.0). Use
$parser->getStream()->getSourceContext()->getPath() instead.
*/
public function getFilename()
{
@trigger_error(sprintf('The "%s" method is
deprecated since version 1.27 and will be removed in 2.0. Use
$parser->getStream()->getSourceContext()->getPath()
instead.', __METHOD__), E_USER_DEPRECATED);
return $this->stream->getSourceContext()->getName();
}
public function parse(TokenStream $stream, $test = null, $dropNeedle =
false)
{
// push all variables into the stack to keep the current state of
the parser
// using get_object_vars() instead of foreach would lead to
https://bugs.php.net/71336
// This hack can be removed when min version if PHP 7.0
$vars = [];
foreach ($this as $k => $v) {
$vars[$k] = $v;
}
unset($vars['stack'], $vars['env'],
$vars['handlers'], $vars['visitors'],
$vars['expressionParser'],
$vars['reservedMacroNames']);
$this->stack[] = $vars;
// tag handlers
if (null === $this->handlers) {
$this->handlers = $this->env->getTokenParsers();
$this->handlers->setParser($this);
}
// node visitors
if (null === $this->visitors) {
$this->visitors = $this->env->getNodeVisitors();
}
if (null === $this->expressionParser) {
$this->expressionParser = new 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:
$token = $this->stream->next();
$rv[] = new TextNode($token->getValue(),
$token->getLine());
break;
case Token::VAR_START_TYPE:
$token = $this->stream->next();
$expr =
$this->expressionParser->parseExpression();
$this->stream->expect(Token::VAR_END_TYPE);
$rv[] = new PrintNode($expr, $token->getLine());
break;
case Token::BLOCK_START_TYPE:
$this->stream->next();
$token = $this->getCurrentToken();
if (Token::NAME_TYPE !== $token->getType()) {
throw new SyntaxError('A block must start with
a tag name.', $token->getLine(),
$this->stream->getSourceContext());
}
if (null !== $test && \call_user_func($test,
$token)) {
if ($dropNeedle) {
$this->stream->next();
}
if (1 === \count($rv)) {
return $rv[0];
}
return new Node($rv, [], $lineno);
}
$subparser =
$this->handlers->getTokenParser($token->getValue());
if (null === $subparser) {
if (null !== $test) {
$e = new SyntaxError(sprintf('Unexpected
"%s" tag', $token->getValue()), $token->getLine(),
$this->stream->getSourceContext());
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();
$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);
}
/**
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function addHandler($name, $class)
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0.',
E_USER_DEPRECATED);
$this->handlers[$name] = $class;
}
/**
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function addNodeVisitor(NodeVisitorInterface $visitor)
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0.',
E_USER_DEPRECATED);
$this->visitors[] = $visitor;
}
public function getBlockStack()
{
return $this->blockStack;
}
public function peekBlockStack()
{
return 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)
{
if ($this->isReservedMacroName($name)) {
throw new SyntaxError(sprintf('"%s" cannot be
used as a macro name as it is a reserved keyword.', $name),
$node->getTemplateLine(), $this->stream->getSourceContext());
}
$this->macros[$name] = $node;
}
public function isReservedMacroName($name)
{
if (null === $this->reservedMacroNames) {
$this->reservedMacroNames = [];
$r = new
\ReflectionClass($this->env->getBaseTemplateClass());
foreach ($r->getMethods() as $method) {
$methodName = strtr($method->getName(),
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz');
if ('get' === substr($methodName, 0, 3)
&& isset($methodName[3])) {
$this->reservedMacroNames[] = substr($methodName,
3);
}
}
}
return \in_array(strtr($name,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz'), $this->reservedMacroNames);
}
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 (null !== $this->peekBlockStack()) {
foreach ($this->importedSymbols as $functions) {
if (isset($functions[$type][$alias])) {
if (\count($this->blockStack) > 1) {
return null;
}
return $functions[$type][$alias];
}
}
} else {
return isset($this->importedSymbols[0][$type][$alias]) ?
$this->importedSymbols[0][$type][$alias] : null;
}
}
public function isMainScope()
{
return 1 === \count($this->importedSymbols);
}
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();
}
protected function filterBodyNodes(\Twig_NodeInterface $node)
{
// check that the body does not contain non-empty output nodes
if (
($node instanceof TextNode &&
!ctype_space($node->getAttribute('data')))
||
(!$node instanceof TextNode && !$node instanceof
BlockReferenceNode && $node instanceof NodeOutputInterface)
) {
if (false !== strpos((string) $node,
\chr(0xEF).\chr(0xBB).\chr(0xBF))) {
$t = substr($node->getAttribute('data'), 3);
if ('' === $t || ctype_space($t)) {
// bypass empty nodes starting with a BOM
return;
}
}
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 will "capture" the output
if ($node instanceof NodeCaptureInterface) {
return $node;
}
if ($node instanceof NodeOutputInterface) {
return;
}
foreach ($node as $k => $n) {
if (null !== $n && null ===
$this->filterBodyNodes($n)) {
$node->removeNode($k);
}
}
return $node;
}
}
class_alias('Twig\Parser', 'Twig_Parser');
twig/src/Profiler/Dumper/BaseDumper.php000064400000003346151161070030014063
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler\Dumper;
use Twig\Profiler\Profile;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class BaseDumper
{
private $root;
public function dump(Profile $profile)
{
return $this->dumpProfile($profile);
}
abstract protected function formatTemplate(Profile $profile, $prefix);
abstract protected function formatNonTemplate(Profile $profile,
$prefix);
abstract protected function formatTime(Profile $profile, $percent);
private function dumpProfile(Profile $profile, $prefix = '',
$sibling = false)
{
if ($profile->isRoot()) {
$this->root = $profile->getDuration();
$start = $profile->getName();
} else {
if ($profile->isTemplate()) {
$start = $this->formatTemplate($profile, $prefix);
} else {
$start = $this->formatNonTemplate($profile, $prefix);
}
$prefix .= $sibling ? '│ ' : ' ';
}
$percent = $this->root ? $profile->getDuration() /
$this->root * 100 : 0;
if ($profile->getDuration() * 1000 < 1) {
$str = $start."\n";
} else {
$str = sprintf("%s %s\n", $start,
$this->formatTime($profile, $percent));
}
$nCount = \count($profile->getProfiles());
foreach ($profile as $i => $p) {
$str .= $this->dumpProfile($p, $prefix, $i + 1 !== $nCount);
}
return $str;
}
}
class_alias('Twig\Profiler\Dumper\BaseDumper',
'Twig_Profiler_Dumper_Base');
twig/src/Profiler/Dumper/BlackfireDumper.php000064400000004016151161070030015066
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler\Dumper;
use Twig\Profiler\Profile;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @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 = <<<EOF
file-format: BlackfireProbe
cost-dimensions: wt mu pmu
request-start: {$start}
EOF;
foreach ($data as $name => $values) {
$str .= "{$name}//{$values['ct']}
{$values['wt']} {$values['mu']}
{$values['pmu']}\n";
}
return $str;
}
private function dumpChildren($parent, Profile $profile, &$data)
{
foreach ($profile as $p) {
if ($p->isTemplate()) {
$name = $p->getTemplate();
} else {
$name = sprintf('%s::%s(%s)',
$p->getTemplate(), $p->getType(), $p->getName());
}
$this->dumpProfile(sprintf('%s==>%s', $parent,
$name), $p, $data);
$this->dumpChildren($name, $p, $data);
}
}
private function dumpProfile($edge, Profile $profile, &$data)
{
if (isset($data[$edge])) {
++$data[$edge]['ct'];
$data[$edge]['wt'] +=
floor($profile->getDuration() * 1000000);
$data[$edge]['mu'] += $profile->getMemoryUsage();
$data[$edge]['pmu'] +=
$profile->getPeakMemoryUsage();
} else {
$data[$edge] = [
'ct' => 1,
'wt' => floor($profile->getDuration() *
1000000),
'mu' => $profile->getMemoryUsage(),
'pmu' => $profile->getPeakMemoryUsage(),
];
}
}
}
class_alias('Twig\Profiler\Dumper\BlackfireDumper',
'Twig_Profiler_Dumper_Blackfire');
twig/src/Profiler/Dumper/HtmlDumper.php000064400000002727151161070030014117
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler\Dumper;
use Twig\Profiler\Profile;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class HtmlDumper extends BaseDumper
{
private static $colors = [
'block' => '#dfd',
'macro' => '#ddf',
'template' => '#ffd',
'big' => '#d44',
];
public function dump(Profile $profile)
{
return
'<pre>'.parent::dump($profile).'</pre>';
}
protected function formatTemplate(Profile $profile, $prefix)
{
return sprintf('%sâ”” <span style="background-color:
%s">%s</span>', $prefix,
self::$colors['template'], $profile->getTemplate());
}
protected function formatNonTemplate(Profile $profile, $prefix)
{
return sprintf('%sâ”” %s::%s(<span
style="background-color: %s">%s</span>)', $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('<span style="color:
%s">%.2fms/%.0f%%</span>', $percent > 20 ?
self::$colors['big'] : 'auto',
$profile->getDuration() * 1000, $percent);
}
}
class_alias('Twig\Profiler\Dumper\HtmlDumper',
'Twig_Profiler_Dumper_Html');
twig/src/Profiler/Dumper/TextDumper.php000064400000001675151161070030014140
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler\Dumper;
use Twig\Profiler\Profile;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @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');
twig/src/Profiler/Node/EnterProfileNode.php000064400000002432151161070030014664
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler\Node;
use Twig\Compiler;
use Twig\Node\Node;
/**
* Represents a profile enter node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class EnterProfileNode extends Node
{
public function __construct($extensionName, $type, $name, $varName)
{
parent::__construct([], ['extension_name' =>
$extensionName, 'name' => $name, 'type' => $type,
'var_name' => $varName]);
}
public function compile(Compiler $compiler)
{
$compiler
->write(sprintf('$%s =
$this->env->getExtension(',
$this->getAttribute('var_name')))
->repr($this->getAttribute('extension_name'))
->raw(");\n")
->write(sprintf('$%s->enter($%s = new
\Twig\Profiler\Profile($this->getTemplateName(), ',
$this->getAttribute('var_name'),
$this->getAttribute('var_name').'_prof'))
->repr($this->getAttribute('type'))
->raw(', ')
->repr($this->getAttribute('name'))
->raw("));\n\n")
;
}
}
class_alias('Twig\Profiler\Node\EnterProfileNode',
'Twig_Profiler_Node_EnterProfile');
twig/src/Profiler/Node/LeaveProfileNode.php000064400000001526151161070030014646
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler\Node;
use Twig\Compiler;
use Twig\Node\Node;
/**
* Represents a profile leave node.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class LeaveProfileNode extends Node
{
public function __construct($varName)
{
parent::__construct([], ['var_name' => $varName]);
}
public function compile(Compiler $compiler)
{
$compiler
->write("\n")
->write(sprintf("\$%s->leave(\$%s);\n\n",
$this->getAttribute('var_name'),
$this->getAttribute('var_name').'_prof'))
;
}
}
class_alias('Twig\Profiler\Node\LeaveProfileNode',
'Twig_Profiler_Node_LeaveProfile');
twig/src/Profiler/NodeVisitor/ProfilerNodeVisitor.php000064400000004563151161070030017017
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler\NodeVisitor;
use Twig\Environment;
use Twig\Node\BlockNode;
use Twig\Node\BodyNode;
use Twig\Node\MacroNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;
use Twig\NodeVisitor\AbstractNodeVisitor;
use Twig\Profiler\Node\EnterProfileNode;
use Twig\Profiler\Node\LeaveProfileNode;
use Twig\Profiler\Profile;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class ProfilerNodeVisitor extends AbstractNodeVisitor
{
private $extensionName;
public function __construct($extensionName)
{
$this->extensionName = $extensionName;
}
protected function doEnterNode(Node $node, Environment $env)
{
return $node;
}
protected function doLeaveNode(Node $node, Environment $env)
{
if ($node instanceof ModuleNode) {
$varName = $this->getVarName();
$node->setNode('display_start', new Node([new
EnterProfileNode($this->extensionName, Profile::TEMPLATE,
$node->getTemplateName(), $varName),
$node->getNode('display_start')]));
$node->setNode('display_end', new Node([new
LeaveProfileNode($varName), $node->getNode('display_end')]));
} elseif ($node instanceof BlockNode) {
$varName = $this->getVarName();
$node->setNode('body', new BodyNode([
new EnterProfileNode($this->extensionName,
Profile::BLOCK, $node->getAttribute('name'), $varName),
$node->getNode('body'),
new LeaveProfileNode($varName),
]));
} elseif ($node instanceof MacroNode) {
$varName = $this->getVarName();
$node->setNode('body', new BodyNode([
new EnterProfileNode($this->extensionName,
Profile::MACRO, $node->getAttribute('name'), $varName),
$node->getNode('body'),
new LeaveProfileNode($varName),
]));
}
return $node;
}
private function getVarName()
{
return sprintf('__internal_%s', hash('sha256',
$this->extensionName));
}
public function getPriority()
{
return 0;
}
}
class_alias('Twig\Profiler\NodeVisitor\ProfilerNodeVisitor',
'Twig_Profiler_NodeVisitor_Profiler');
twig/src/Profiler/Profile.php000064400000007772151161070030012207
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Profiler;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
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($template = 'main', $type =
self::ROOT, $name = 'main')
{
$this->template = $template;
$this->type = $type;
$this->name = 0 === strpos($name, '__internal_') ?
'INTERNAL' : $name;
$this->enter();
}
public function getTemplate()
{
return $this->template;
}
public function getType()
{
return $this->type;
}
public function getName()
{
return $this->name;
}
public function isRoot()
{
return self::ROOT === $this->type;
}
public function isTemplate()
{
return self::TEMPLATE === $this->type;
}
public function isBlock()
{
return self::BLOCK === $this->type;
}
public function isMacro()
{
return self::MACRO === $this->type;
}
public function getProfiles()
{
return $this->profiles;
}
public function addProfile(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');
twig/src/RuntimeLoader/ContainerRuntimeLoader.php000064400000001722151161070030016201
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\RuntimeLoader;
use Psr\Container\ContainerInterface;
/**
* Lazily loads Twig runtime implementations from a PSR-11 container.
*
* Note that the runtime services MUST use their class names as
identifiers.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Robin Chalas <robin.chalas@gmail.com>
*/
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');
twig/src/RuntimeLoader/FactoryRuntimeLoader.php000064400000001603151161070030015664
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\RuntimeLoader;
/**
* Lazy loads the runtime implementations for a Twig element.
*
* @author Robin Chalas <robin.chalas@gmail.com>
*/
class FactoryRuntimeLoader implements RuntimeLoaderInterface
{
private $map;
/**
* @param array $map An array where keys are class names and values
factory callables
*/
public function __construct($map = [])
{
$this->map = $map;
}
public function load($class)
{
if (isset($this->map[$class])) {
$runtimeFactory = $this->map[$class];
return $runtimeFactory();
}
}
}
class_alias('Twig\RuntimeLoader\FactoryRuntimeLoader',
'Twig_FactoryRuntimeLoader');
twig/src/RuntimeLoader/RuntimeLoaderInterface.php000064400000001461151161070030016157
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\RuntimeLoader;
/**
* Creates runtime implementations for Twig elements
(filters/functions/tests).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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');
twig/src/Sandbox/SecurityError.php000064400000000743151161070030013233
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
use Twig\Error\Error;
/**
* Exception thrown when a security error occurs at runtime.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SecurityError extends Error
{
}
class_alias('Twig\Sandbox\SecurityError',
'Twig_Sandbox_SecurityError');
twig/src/Sandbox/SecurityNotAllowedFilterError.php000064400000001555151161070030016374
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
/**
* Exception thrown when a not allowed filter is used in a template.
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class SecurityNotAllowedFilterError extends SecurityError
{
private $filterName;
public function __construct($message, $functionName, $lineno = -1,
$filename = null, \Exception $previous = null)
{
parent::__construct($message, $lineno, $filename, $previous);
$this->filterName = $functionName;
}
public function getFilterName()
{
return $this->filterName;
}
}
class_alias('Twig\Sandbox\SecurityNotAllowedFilterError',
'Twig_Sandbox_SecurityNotAllowedFilterError');
twig/src/Sandbox/SecurityNotAllowedFunctionError.php000064400000001575151161070030016736
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
/**
* Exception thrown when a not allowed function is used in a template.
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class SecurityNotAllowedFunctionError extends SecurityError
{
private $functionName;
public function __construct($message, $functionName, $lineno = -1,
$filename = null, \Exception $previous = null)
{
parent::__construct($message, $lineno, $filename, $previous);
$this->functionName = $functionName;
}
public function getFunctionName()
{
return $this->functionName;
}
}
class_alias('Twig\Sandbox\SecurityNotAllowedFunctionError',
'Twig_Sandbox_SecurityNotAllowedFunctionError');
twig/src/Sandbox/SecurityNotAllowedMethodError.php000064400000002007151161070030016360
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
/**
* Exception thrown when a not allowed class method is used in a template.
*
* @author Kit Burton-Senior <mail@kitbs.com>
*/
class SecurityNotAllowedMethodError extends SecurityError
{
private $className;
private $methodName;
public function __construct($message, $className, $methodName, $lineno
= -1, $filename = null, \Exception $previous = null)
{
parent::__construct($message, $lineno, $filename, $previous);
$this->className = $className;
$this->methodName = $methodName;
}
public function getClassName()
{
return $this->className;
}
public function getMethodName()
{
return $this->methodName;
}
}
class_alias('Twig\Sandbox\SecurityNotAllowedMethodError',
'Twig_Sandbox_SecurityNotAllowedMethodError');
twig/src/Sandbox/SecurityNotAllowedPropertyError.php000064400000002033151161070030016763
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
/**
* Exception thrown when a not allowed class property is used in a
template.
*
* @author Kit Burton-Senior <mail@kitbs.com>
*/
class SecurityNotAllowedPropertyError extends SecurityError
{
private $className;
private $propertyName;
public function __construct($message, $className, $propertyName,
$lineno = -1, $filename = null, \Exception $previous = null)
{
parent::__construct($message, $lineno, $filename, $previous);
$this->className = $className;
$this->propertyName = $propertyName;
}
public function getClassName()
{
return $this->className;
}
public function getPropertyName()
{
return $this->propertyName;
}
}
class_alias('Twig\Sandbox\SecurityNotAllowedPropertyError',
'Twig_Sandbox_SecurityNotAllowedPropertyError');
twig/src/Sandbox/SecurityNotAllowedTagError.php000064400000001513151161070030015654
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
/**
* Exception thrown when a not allowed tag is used in a template.
*
* @author Martin Hasoň <martin.hason@gmail.com>
*/
class SecurityNotAllowedTagError extends SecurityError
{
private $tagName;
public function __construct($message, $tagName, $lineno = -1, $filename
= null, \Exception $previous = null)
{
parent::__construct($message, $lineno, $filename, $previous);
$this->tagName = $tagName;
}
public function getTagName()
{
return $this->tagName;
}
}
class_alias('Twig\Sandbox\SecurityNotAllowedTagError',
'Twig_Sandbox_SecurityNotAllowedTagError');
twig/src/Sandbox/SecurityPolicy.php000064400000007723151161070030013406
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
use Twig\Markup;
/**
* Represents a security policy which need to be enforced when sandbox mode
is enabled.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SecurityPolicy implements SecurityPolicyInterface
{
protected $allowedTags;
protected $allowedFilters;
protected $allowedMethods;
protected $allowedProperties;
protected $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 \Twig_TemplateInterface || $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');
twig/src/Sandbox/SecurityPolicyInterface.php000064400000001224151161070030015215
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Sandbox;
/**
* Interface that all security policy classes must implements.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface SecurityPolicyInterface
{
public function checkSecurity($tags, $filters, $functions);
public function checkMethodAllowed($obj, $method);
public function checkPropertyAllowed($obj, $method);
}
class_alias('Twig\Sandbox\SecurityPolicyInterface',
'Twig_Sandbox_SecurityPolicyInterface');
twig/src/Source.php000064400000002005151161070030010245 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Holds information about a non-compiled Twig template.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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($code, $name, $path = '')
{
$this->code = $code;
$this->name = $name;
$this->path = $path;
}
public function getCode()
{
return $this->code;
}
public function getName()
{
return $this->name;
}
public function getPath()
{
return $this->path;
}
}
class_alias('Twig\Source', 'Twig_Source');
twig/src/Template.php000064400000062163151161070030010573 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\Error;
use Twig\Error\LoaderError;
use Twig\Error\RuntimeError;
/**
* Default base class for compiled templates.
*
* This class is an implementation detail of how template compilation
currently
* works, which might change. It should never be used directly. Use
$twig->load()
* instead, which returns an instance of \Twig\TemplateWrapper.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @internal
*/
abstract class Template implements \Twig_TemplateInterface
{
/**
* @internal
*/
protected static $cache = [];
protected $parent;
protected $parents = [];
protected $env;
protected $blocks = [];
protected $traits = [];
protected $sandbox;
public function __construct(Environment $env)
{
$this->env = $env;
}
/**
* @internal this method will be removed in 2.0 and is only used
internally to provide an upgrade path from 1.x to 2.0
*/
public function __toString()
{
return $this->getTemplateName();
}
/**
* Returns the template name.
*
* @return string The template name
*/
abstract public function getTemplateName();
/**
* Returns debug information about the template.
*
* @return array Debug information
*/
public function getDebugInfo()
{
return [];
}
/**
* Returns the template source code.
*
* @return string The template source code
*
* @deprecated since 1.27 (to be removed in 2.0). Use
getSourceContext() instead
*/
public function getSource()
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.27 and will be removed in 2.0. Use
getSourceContext() instead.', E_USER_DEPRECATED);
return '';
}
/**
* Returns information about the original template source code.
*
* @return Source
*/
public function getSourceContext()
{
return new Source('', $this->getTemplateName());
}
/**
* @deprecated since 1.20 (to be removed in 2.0)
*/
public function getEnvironment()
{
@trigger_error('The '.__METHOD__.' method is
deprecated since version 1.20 and will be removed in 2.0.',
E_USER_DEPRECATED);
return $this->env;
}
/**
* Returns the parent template.
*
* This method is for internal use only and should never be called
* directly.
*
* @param array $context
*
* @return \Twig_TemplateInterface|TemplateWrapper|false The parent
template or false if there is no parent
*
* @internal
*/
public function getParent(array $context)
{
if (null !== $this->parent) {
return $this->parent;
}
try {
$parent = $this->doGetParent($context);
if (false === $parent) {
return false;
}
if ($parent instanceof self || $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
= [])
{
$name = (string) $name;
if (isset($this->traits[$name])) {
$this->traits[$name][0]->displayBlock($name, $context,
$blocks, false);
} elseif (false !== $parent = $this->getParent($context)) {
$parent->displayBlock($name, $context, $blocks, false);
} else {
throw new 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)
{
$name = (string) $name;
if ($useBlocks && isset($blocks[$name])) {
$template = $blocks[$name][0];
$block = $blocks[$name][1];
} elseif (isset($this->blocks[$name])) {
$template = $this->blocks[$name][0];
$block = $this->blocks[$name][1];
} else {
$template = null;
$block = null;
}
// avoid RCEs when sandbox is enabled
if (null !== $template && !$template instanceof self) {
throw new \LogicException('A block must be a method on a
\Twig\Template instance.');
}
if (null !== $template) {
try {
$template->$block($context, $blocks);
} catch (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);
} else {
@trigger_error(sprintf('Silent display of undefined block
"%s" in template "%s" is deprecated since version 1.29
and will throw an exception in 2.0. Use the "block(\'%s\')
is defined" expression to test for block existence.', $name,
$this->getTemplateName(), $name), E_USER_DEPRECATED);
}
}
/**
* Renders a parent block.
*
* This method is for internal use only and should never be called
* directly.
*
* @param string $name The block name to render from the parent
* @param array $context The context
* @param array $blocks The current set of blocks
*
* @return string The rendered block
*/
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 = null, array $blocks =
[])
{
if (null === $context) {
@trigger_error('The '.__METHOD__.' method is
internal and should never be called; calling it directly is deprecated
since version 1.28 and won\'t be possible anymore in 2.0.',
E_USER_DEPRECATED);
return isset($this->blocks[(string) $name]);
}
if (isset($blocks[$name])) {
return $blocks[$name][0] instanceof self;
}
if (isset($this->blocks[$name])) {
return true;
}
if (false !== $parent = $this->getParent($context)) {
return $parent->hasBlock($name, $context);
}
return false;
}
/**
* Returns all block names in the current context of the template.
*
* This method checks blocks defined in the current template
* or defined in "used" traits or defined in parent
templates.
*
* @param array $context The context
* @param array $blocks The current set of blocks
*
* @return array An array of block names
*/
public function getBlockNames(array $context = null, array $blocks =
[])
{
if (null === $context) {
@trigger_error('The '.__METHOD__.' method is
internal and should never be called; calling it directly is deprecated
since version 1.28 and won\'t be possible anymore in 2.0.',
E_USER_DEPRECATED);
return array_keys($this->blocks);
}
$names = array_merge(array_keys($blocks),
array_keys($this->blocks));
if (false !== $parent = $this->getParent($context)) {
$names = array_merge($names,
$parent->getBlockNames($context));
}
return array_unique($names);
}
/**
* @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 (\Exception $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
} catch (\Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean();
}
protected function displayWithErrorHandling(array $context, array
$blocks = [])
{
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 =
[]);
/**
* Returns a variable from the context.
*
* This method is for internal use only and should never be called
* directly.
*
* This method should not be overridden in a sub-class as this is an
* implementation detail that has been introduced to optimize variable
* access for versions of PHP before 5.4. This is not a way to override
* the way to get a variable value.
*
* @param array $context The context
* @param string $item The variable to return from the
context
* @param bool $ignoreStrictCheck Whether to ignore the strict
variable check or not
*
* @return mixed The content of the context variable
*
* @throws RuntimeError if the variable does not exist and Twig is
running in strict mode
*
* @internal
*/
final protected function getContext($context, $item, $ignoreStrictCheck
= false)
{
if (!\array_key_exists($item, $context)) {
if ($ignoreStrictCheck ||
!$this->env->isStrictVariables()) {
return;
}
throw new RuntimeError(sprintf('Variable "%s"
does not exist.', $item), -1, $this->getSourceContext());
}
return $context[$item];
}
/**
* Returns the attribute value for a given array/object.
*
* @param mixed $object The object or array from where to
get the item
* @param mixed $item The item to get from the array or
object
* @param array $arguments An array of arguments to pass if
the item is an object method
* @param string $type The type of attribute (@see
\Twig\Template constants)
* @param bool $isDefinedTest Whether this is only a defined
check
* @param bool $ignoreStrictCheck Whether to ignore the strict
attribute check or not
*
* @return mixed The attribute value, or a Boolean when $isDefinedTest
is true, or null when the attribute is not set and $ignoreStrictCheck is
true
*
* @throws RuntimeError if the attribute does not exist and Twig is
running in strict mode and $isDefinedTest is false
*
* @internal
*/
protected function getAttribute($object, $item, array $arguments = [],
$type = self::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false)
{
// array
if (self::METHOD_CALL !== $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 (self::ARRAY_CALL === $type || !\is_object($object)) {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck ||
!$this->env->isStrictVariables()) {
return;
}
if ($object instanceof \ArrayAccess) {
$message = sprintf('Key "%s" in object
with ArrayAccess of class "%s" does not exist.', $arrayItem,
\get_class($object));
} elseif (\is_object($object)) {
$message = sprintf('Impossible to access a key
"%s" on an object of class "%s" that does not implement
ArrayAccess interface.', $item, \get_class($object));
} elseif (\is_array($object)) {
if (empty($object)) {
$message = sprintf('Key "%s" does
not exist as the array is empty.', $arrayItem);
} else {
$message = sprintf('Key "%s" for
array with keys "%s" does not exist.', $arrayItem,
implode(', ', array_keys($object)));
}
} elseif (self::ARRAY_CALL === $type) {
if (null === $object) {
$message = sprintf('Impossible to access a key
("%s") on a null variable.', $item);
} else {
$message = sprintf('Impossible to access a key
("%s") on a %s variable ("%s").', $item,
\gettype($object), $object);
}
} elseif (null === $object) {
$message = sprintf('Impossible to access an
attribute ("%s") on a null variable.', $item);
} else {
$message = sprintf('Impossible to access an
attribute ("%s") on a %s variable ("%s").', $item,
\gettype($object), $object);
}
throw new RuntimeError($message, -1,
$this->getSourceContext());
}
}
if (!\is_object($object)) {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck ||
!$this->env->isStrictVariables()) {
return;
}
if (null === $object) {
$message = sprintf('Impossible to invoke a method
("%s") on a null variable.', $item);
} elseif (\is_array($object)) {
$message = sprintf('Impossible to invoke a method
("%s") on an array.', $item);
} else {
$message = sprintf('Impossible to invoke a method
("%s") on a %s variable ("%s").', $item,
\gettype($object), $object);
}
throw new RuntimeError($message, -1,
$this->getSourceContext());
}
// object property
if (self::METHOD_CALL !== $type && !$object instanceof
self) { // \Twig\Template does not have public properties, and we
don't want to allow access to internal ones
if (isset($object->$item) || \array_key_exists((string)
$item, (array) $object)) {
if ($isDefinedTest) {
return true;
}
if
($this->env->hasExtension('\Twig\Extension\SandboxExtension'))
{
$this->env->getExtension('\Twig\Extension\SandboxExtension')->checkPropertyAllowed($object,
$item);
}
return $object->$item;
}
}
$class = \get_class($object);
// object method
if (!isset(self::$cache[$class])) {
// get_class_methods returns all methods accessible in the
scope, but we only want public ones to be accessible in templates
if ($object instanceof self) {
$ref = new \ReflectionClass($class);
$methods = [];
foreach ($ref->getMethods(\ReflectionMethod::IS_PUBLIC)
as $refMethod) {
// Accessing the environment from templates is
forbidden to prevent untrusted changes to the environment
if ('getenvironment' !==
strtr($refMethod->name, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz')) {
$methods[] = $refMethod->name;
}
}
} else {
$methods = get_class_methods($object);
}
// sort values to have consistent behavior, so that
"get" methods win precedence over "is" methods
sort($methods);
$cache = [];
foreach ($methods as $method) {
$cache[$method] = $method;
$cache[$lcName = strtr($method,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz')] = $method;
if ('g' === $lcName[0] && 0 ===
strpos($lcName, 'get')) {
$name = substr($method, 3);
$lcName = substr($lcName, 3);
} elseif ('i' === $lcName[0] && 0 ===
strpos($lcName, 'is')) {
$name = substr($method, 2);
$lcName = substr($lcName, 2);
} else {
continue;
}
// skip get() and is() methods (in which case, $name is
empty)
if ($name) {
if (!isset($cache[$name])) {
$cache[$name] = $method;
}
if (!isset($cache[$lcName])) {
$cache[$lcName] = $method;
}
}
}
self::$cache[$class] = $cache;
}
$call = false;
if (isset(self::$cache[$class][$item])) {
$method = self::$cache[$class][$item];
} elseif (isset(self::$cache[$class][$lcItem = strtr($item,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
'abcdefghijklmnopqrstuvwxyz')])) {
$method = self::$cache[$class][$lcItem];
} elseif (isset(self::$cache[$class]['__call'])) {
$method = $item;
$call = true;
} else {
if ($isDefinedTest) {
return false;
}
if ($ignoreStrictCheck ||
!$this->env->isStrictVariables()) {
return;
}
throw new RuntimeError(sprintf('Neither the property
"%1$s" nor one of the methods "%1$s()",
"get%1$s()"/"is%1$s()" or "__call()" exist
and have public access in class "%2$s".', $item, $class),
-1, $this->getSourceContext());
}
if ($isDefinedTest) {
return true;
}
if
($this->env->hasExtension('\Twig\Extension\SandboxExtension'))
{
$this->env->getExtension('\Twig\Extension\SandboxExtension')->checkMethodAllowed($object,
$method);
}
// Some objects throw exceptions when they have __call, and the
method we try
// to call is not supported. If ignoreStrictCheck is true, we
should return null.
try {
if (!$arguments) {
$ret = $object->$method();
} else {
$ret = \call_user_func_array([$object, $method],
$arguments);
}
} catch (\BadMethodCallException $e) {
if ($call && ($ignoreStrictCheck ||
!$this->env->isStrictVariables())) {
return;
}
throw $e;
}
// @deprecated in 1.28
if ($object instanceof \Twig_TemplateInterface) {
$self = $object->getTemplateName() ===
$this->getTemplateName();
$message = sprintf('Calling "%s" on template
"%s" from template "%s" is deprecated since version
1.28 and won\'t be supported anymore in 2.0.', $item,
$object->getTemplateName(), $this->getTemplateName());
if ('renderBlock' === $method ||
'displayBlock' === $method) {
$message .= sprintf(' Use block("%s"%s)
instead).', $arguments[0], $self ? '' : ',
template');
} elseif ('hasBlock' === $method) {
$message .= sprintf(' Use
"block("%s"%s) is defined" instead).',
$arguments[0], $self ? '' : ', template');
} elseif ('render' === $method || 'display'
=== $method) {
$message .= sprintf(' Use include("%s")
instead).', $object->getTemplateName());
}
@trigger_error($message, E_USER_DEPRECATED);
return '' === $ret ? '' : new Markup($ret,
$this->env->getCharset());
}
return $ret;
}
}
class_alias('Twig\Template', 'Twig_Template');
twig/src/TemplateWrapper.php000064400000007636151161070030012140
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Exposes a template to userland.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
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
*
* @return string The rendered template
*/
public function render($context = [])
{
// using func_get_args() allows to not expose the blocks argument
// as it should only be used by internal code
return $this->template->render($context, \func_num_args()
> 1 ? func_get_arg(1) : []);
}
/**
* Displays the template.
*
* @param array $context An array of parameters to pass to the template
*/
public function display($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_num_args() > 1 ?
func_get_arg(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
*
* @return bool
*/
public function hasBlock($name, $context = [])
{
return $this->template->hasBlock($name, $context);
}
/**
* Returns defined block names in the template.
*
* @param array $context An array of parameters to pass to the template
*
* @return string[] An array of defined template block names
*/
public function getBlockNames($context = [])
{
return $this->template->getBlockNames($context);
}
/**
* Renders a template block.
*
* @param string $name The block name to render
* @param array $context An array of parameters to pass to the
template
*
* @return string The rendered block
*/
public function renderBlock($name, $context = [])
{
$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 (\Exception $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
} catch (\Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}
throw $e;
}
return ob_get_clean();
}
/**
* Displays a template block.
*
* @param string $name The block name to render
* @param array $context An array of parameters to pass to the
template
*/
public function displayBlock($name, $context = [])
{
$this->template->displayBlock($name,
$this->env->mergeGlobals($context));
}
/**
* @return Source
*/
public function getSourceContext()
{
return $this->template->getSourceContext();
}
/**
* @return string
*/
public function getTemplateName()
{
return $this->template->getTemplateName();
}
/**
* @internal
*
* @return Template
*/
public function unwrap()
{
return $this->template;
}
}
class_alias('Twig\TemplateWrapper',
'Twig_TemplateWrapper');
twig/src/Test/IntegrationTestCase.php000064400000020401151161070030013643
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Test;
use PHPUnit\Framework\TestCase;
use Twig\Environment;
use Twig\Error\Error;
use Twig\Extension\ExtensionInterface;
use Twig\Loader\ArrayLoader;
use Twig\Loader\SourceContextLoaderInterface;
use Twig\RuntimeLoader\RuntimeLoaderInterface;
use Twig\Source;
use Twig\TwigFilter;
use Twig\TwigFunction;
use Twig\TwigTest;
/**
* Integration test helper.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Karma Dordrak <drak@zikula.org>
*/
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)
{
$this->doIntegrationTest($file, $message, $condition,
$templates, $exception, $outputs);
}
/**
* @dataProvider getLegacyTests
* @group legacy
*/
public function testLegacyIntegration($file, $message, $condition,
$templates, $exception, $outputs)
{
$this->doIntegrationTest($file, $message, $condition,
$templates, $exception, $outputs);
}
public function getTests($name, $legacyTests = false)
{
$fixturesDir = realpath($this->getFixturesDir());
$tests = [];
foreach (new \RecursiveIteratorIterator(new
\RecursiveDirectoryIterator($fixturesDir),
\RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if (!preg_match('/\.test$/', $file)) {
continue;
}
if ($legacyTests xor false !== strpos($file->getRealpath(),
'.legacy.test')) {
continue;
}
$test = file_get_contents($file->getRealpath());
if
(preg_match('/--TEST--\s*(.*?)\s*(?:--CONDITION--\s*(.*))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)\s*(?:--DATA--\s*(.*))?\s*--EXCEPTION--\s*(.*)/sx',
$test, $match)) {
$message = $match[1];
$condition = $match[2];
$templates = self::parseTemplates($match[3]);
$exception = $match[5];
$outputs = [[null, $match[4], null, '']];
} elseif
(preg_match('/--TEST--\s*(.*?)\s*(?:--CONDITION--\s*(.*))?\s*((?:--TEMPLATE(?:\(.*?\))?--(?:.*?))+)--DATA--.*?--EXPECT--.*/s',
$test, $match)) {
$message = $match[1];
$condition = $match[2];
$templates = self::parseTemplates($match[3]);
$exception = false;
preg_match_all('/--DATA--(.*?)(?:--CONFIG--(.*?))?--EXPECT--(.*?)(?=\-\-DATA\-\-|$)/s',
$test, $outputs, PREG_SET_ORDER);
} else {
throw new \InvalidArgumentException(sprintf('Test
"%s" is not valid.', str_replace($fixturesDir.'/',
'', $file)));
}
$tests[] = [str_replace($fixturesDir.'/',
'', $file), $message, $condition, $templates, $exception,
$outputs];
}
if ($legacyTests && empty($tests)) {
// add a dummy test to avoid a PHPUnit message
return [['not', '-', '', [],
'', []]];
}
return $tests;
}
public function getLegacyTests()
{
return $this->getTests('testLegacyIntegration', true);
}
protected function doIntegrationTest($file, $message, $condition,
$templates, $exception, $outputs)
{
if (!$outputs) {
$this->markTestSkipped('no tests to run');
}
if ($condition) {
eval('$ret = '.$condition.';');
if (!$ret) {
$this->markTestSkipped($condition);
}
}
$loader = new 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);
}
$p = new \ReflectionProperty($twig,
'templateClassPrefix');
$p->setAccessible(true);
$p->setValue($twig,
'__TwigTemplate_'.hash('sha256', uniqid(mt_rand(),
true), false).'_');
try {
$template = $twig->load('index.twig');
} catch (\Exception $e) {
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);
}
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";
$loader = $twig->getLoader();
if (!$loader instanceof SourceContextLoaderInterface) {
$source = new Source($loader->getSource($name),
$name);
} else {
$source = $loader->getSourceContext($name);
}
echo
$twig->compile($twig->parse($twig->tokenize($source)));
}
}
$this->assertEquals($expected, $output, $message.' (in
'.$file.')');
}
}
protected static function parseTemplates($test)
{
$templates = [];
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');
twig/src/Test/NodeTestCase.php000064400000004152151161070030012252
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Test;
use PHPUnit\Framework\TestCase;
use Twig\Compiler;
use Twig\Environment;
use Twig\Loader\ArrayLoader;
use Twig\Node\Node;
abstract class NodeTestCase extends TestCase
{
abstract public function getTests();
/**
* @dataProvider getTests
*/
public function testCompile($node, $source, $environment = null,
$isPattern = false)
{
$this->assertNodeCompilation($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" :
'';
if (\PHP_VERSION_ID >= 70000) {
return sprintf('%s($context["%s"] ??
null)', $line, $name);
}
if (\PHP_VERSION_ID >= 50400) {
return sprintf('%s(isset($context["%s"]) ?
$context["%s"] : null)', $line, $name, $name);
}
return sprintf('%s$this->getContext($context,
"%s")', $line, $name);
}
protected function getAttributeGetter()
{
if (\function_exists('twig_template_get_attributes')) {
return 'twig_template_get_attributes($this, ';
}
return '$this->getAttribute(';
}
}
class_alias('Twig\Test\NodeTestCase',
'Twig_Test_NodeTestCase');
twig/src/Token.php000064400000013551151161070030010075 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Represents a Token.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class Token
{
protected $value;
protected $type;
protected $lineno;
const EOF_TYPE = -1;
const TEXT_TYPE = 0;
const BLOCK_START_TYPE = 1;
const VAR_START_TYPE = 2;
const BLOCK_END_TYPE = 3;
const VAR_END_TYPE = 4;
const NAME_TYPE = 5;
const NUMBER_TYPE = 6;
const STRING_TYPE = 7;
const OPERATOR_TYPE = 8;
const PUNCTUATION_TYPE = 9;
const INTERPOLATION_START_TYPE = 10;
const INTERPOLATION_END_TYPE = 11;
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');
twig/src/TokenParser/AbstractTokenParser.php000064400000001201151161070030015160
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Parser;
/**
* Base class for all token parsers.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class AbstractTokenParser implements TokenParserInterface
{
/**
* @var Parser
*/
protected $parser;
public function setParser(Parser $parser)
{
$this->parser = $parser;
}
}
class_alias('Twig\TokenParser\AbstractTokenParser',
'Twig_TokenParser');
twig/src/TokenParser/ApplyTokenParser.php000064400000002661151161070030014515
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\Expression\TempNameExpression;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Node\SetNode;
use Twig\Token;
/**
* Applies filters on a section of a template.
*
* {% apply upper %}
* This text becomes uppercase
* {% endapplys %}
*/
final class ApplyTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$name = $this->parser->getVarName();
$ref = new TempNameExpression($name, $lineno);
$ref->setAttribute('always_defined', true);
$filter =
$this->parser->getExpressionParser()->parseFilterExpressionRaw($ref,
$this->getTag());
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideApplyEnd'], true);
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new Node([
new SetNode(true, $ref, $body, $lineno, $this->getTag()),
new PrintNode($filter, $lineno, $this->getTag()),
]);
}
public function decideApplyEnd(Token $token)
{
return $token->test('endapply');
}
public function getTag()
{
return 'apply';
}
}
twig/src/TokenParser/AutoEscapeTokenParser.php000064400000005132151161070030015455
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\AutoEscapeNode;
use Twig\Node\Expression\ConstantExpression;
use Twig\Token;
/**
* Marks a section of a template to be escaped or not.
*
* {% autoescape true %}
* Everything will be automatically escaped in this block
* {% endautoescape %}
*
* {% autoescape false %}
* Everything will be outputed as is in this block
* {% endautoescape %}
*
* {% autoescape true js %}
* Everything will be automatically escaped in this block
* using the js escaping strategy
* {% endautoescape %}
*
* @final
*/
class AutoEscapeTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
if ($stream->test(Token::BLOCK_END_TYPE)) {
$value = 'html';
} else {
$expr =
$this->parser->getExpressionParser()->parseExpression();
if (!$expr instanceof ConstantExpression) {
throw new SyntaxError('An escaping strategy must be a
string or a bool.', $stream->getCurrent()->getLine(),
$stream->getSourceContext());
}
$value = $expr->getAttribute('value');
$compat = true === $value || false === $value;
if (true === $value) {
$value = 'html';
}
if ($compat && $stream->test(Token::NAME_TYPE)) {
@trigger_error('Using the autoescape tag with
"true" or "false" before the strategy name is
deprecated since version 1.21.', E_USER_DEPRECATED);
if (false === $value) {
throw new SyntaxError('Unexpected escaping
strategy as you set autoescaping to false.',
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$value = $stream->next()->getValue();
}
}
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideBlockEnd'], true);
$stream->expect(Token::BLOCK_END_TYPE);
return new AutoEscapeNode($value, $body, $lineno,
$this->getTag());
}
public function decideBlockEnd(Token $token)
{
return $token->test('endautoescape');
}
public function getTag()
{
return 'autoescape';
}
}
class_alias('Twig\TokenParser\AutoEscapeTokenParser',
'Twig_TokenParser_AutoEscape');
twig/src/TokenParser/BlockTokenParser.php000064400000004677151161070030014473
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\BlockNode;
use Twig\Node\BlockReferenceNode;
use Twig\Node\Node;
use Twig\Node\PrintNode;
use Twig\Token;
/**
* Marks a section of a template as being reusable.
*
* {% block head %}
* <link rel="stylesheet" href="style.css" />
* <title>{% block title %}{% endblock %} - My
Webpage</title>
* {% endblock %}
*
* @final
*/
class BlockTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$name = $stream->expect(Token::NAME_TYPE)->getValue();
if ($this->parser->hasBlock($name)) {
throw new SyntaxError(sprintf("The block '%s'
has already been defined line %d.", $name,
$this->parser->getBlock($name)->getTemplateLine()),
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$this->parser->setBlock($name, $block = new BlockNode($name,
new Node([]), $lineno));
$this->parser->pushLocalScope();
$this->parser->pushBlockStack($name);
if ($stream->nextIf(Token::BLOCK_END_TYPE)) {
$body = $this->parser->subparse([$this,
'decideBlockEnd'], true);
if ($token = $stream->nextIf(Token::NAME_TYPE)) {
$value = $token->getValue();
if ($value != $name) {
throw new SyntaxError(sprintf('Expected endblock
for block "%s" (but "%s" given).', $name, $value),
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
}
} else {
$body = new Node([
new
PrintNode($this->parser->getExpressionParser()->parseExpression(),
$lineno),
]);
}
$stream->expect(Token::BLOCK_END_TYPE);
$block->setNode('body', $body);
$this->parser->popBlockStack();
$this->parser->popLocalScope();
return new BlockReferenceNode($name, $lineno, $this->getTag());
}
public function decideBlockEnd(Token $token)
{
return $token->test('endblock');
}
public function getTag()
{
return 'block';
}
}
class_alias('Twig\TokenParser\BlockTokenParser',
'Twig_TokenParser_Block');
twig/src/TokenParser/DeprecatedTokenParser.php000064400000001765151161070030015474
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\DeprecatedNode;
use Twig\Token;
/**
* Deprecates a section of a template.
*
* {% deprecated 'The "base.twig" template is deprecated,
use "layout.twig" instead.' %}
* {% extends 'layout.html.twig' %}
*
* @author Yonel Ceruto <yonelceruto@gmail.com>
*
* @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');
twig/src/TokenParser/DoTokenParser.php000064400000001440151161070030013764
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\DoNode;
use Twig\Token;
/**
* Evaluates an expression, discarding the returned value.
*
* @final
*/
class DoTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$expr =
$this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new DoNode($expr, $token->getLine(), $this->getTag());
}
public function getTag()
{
return 'do';
}
}
class_alias('Twig\TokenParser\DoTokenParser',
'Twig_TokenParser_Do');
twig/src/TokenParser/EmbedTokenParser.php000064400000004304151161070030014440
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\EmbedNode;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Token;
/**
* Embeds a template.
*
* @final
*/
class EmbedTokenParser extends IncludeTokenParser
{
public function parse(Token $token)
{
$stream = $this->parser->getStream();
$parent =
$this->parser->getExpressionParser()->parseExpression();
list($variables, $only, $ignoreMissing) =
$this->parseArguments();
$parentToken = $fakeParentToken = new Token(Token::STRING_TYPE,
'__parent__', $token->getLine());
if ($parent instanceof ConstantExpression) {
$parentToken = new Token(Token::STRING_TYPE,
$parent->getAttribute('value'), $token->getLine());
} elseif ($parent instanceof NameExpression) {
$parentToken = new Token(Token::NAME_TYPE,
$parent->getAttribute('name'), $token->getLine());
}
// inject a fake parent to make the parent() function work
$stream->injectTokens([
new Token(Token::BLOCK_START_TYPE, '',
$token->getLine()),
new Token(Token::NAME_TYPE, 'extends',
$token->getLine()),
$parentToken,
new Token(Token::BLOCK_END_TYPE, '',
$token->getLine()),
]);
$module = $this->parser->parse($stream, [$this,
'decideBlockEnd'], true);
// override the parent with the correct one
if ($fakeParentToken === $parentToken) {
$module->setNode('parent', $parent);
}
$this->parser->embedTemplate($module);
$stream->expect(Token::BLOCK_END_TYPE);
return new EmbedNode($module->getTemplateName(),
$module->getAttribute('index'), $variables, $only,
$ignoreMissing, $token->getLine(), $this->getTag());
}
public function decideBlockEnd(Token $token)
{
return $token->test('endembed');
}
public function getTag()
{
return 'embed';
}
}
class_alias('Twig\TokenParser\EmbedTokenParser',
'Twig_TokenParser_Embed');
twig/src/TokenParser/ExtendsTokenParser.php000064400000002604151161070030015037
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Node;
use Twig\Token;
/**
* Extends a template by another one.
*
* {% extends "base.html" %}
*
* @final
*/
class ExtendsTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$stream = $this->parser->getStream();
if ($this->parser->peekBlockStack()) {
throw new SyntaxError('Cannot use "extend" in a
block.', $token->getLine(), $stream->getSourceContext());
} elseif (!$this->parser->isMainScope()) {
throw new SyntaxError('Cannot use "extend" in a
macro.', $token->getLine(), $stream->getSourceContext());
}
if (null !== $this->parser->getParent()) {
throw new SyntaxError('Multiple extends tags are
forbidden.', $token->getLine(), $stream->getSourceContext());
}
$this->parser->setParent($this->parser->getExpressionParser()->parseExpression());
$stream->expect(Token::BLOCK_END_TYPE);
return new Node();
}
public function getTag()
{
return 'extends';
}
}
class_alias('Twig\TokenParser\ExtendsTokenParser',
'Twig_TokenParser_Extends');
twig/src/TokenParser/FilterTokenParser.php000064400000003100151161070030014642
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\BlockNode;
use Twig\Node\Expression\BlockReferenceExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\PrintNode;
use Twig\Token;
/**
* Filters a section of a template by applying filters.
*
* {% filter upper %}
* This text becomes uppercase
* {% endfilter %}
*
* @final
*/
class FilterTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$name = $this->parser->getVarName();
$ref = new BlockReferenceExpression(new ConstantExpression($name,
$token->getLine()), null, $token->getLine(), $this->getTag());
$filter =
$this->parser->getExpressionParser()->parseFilterExpressionRaw($ref,
$this->getTag());
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideBlockEnd'], true);
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$block = new BlockNode($name, $body, $token->getLine());
$this->parser->setBlock($name, $block);
return new PrintNode($filter, $token->getLine(),
$this->getTag());
}
public function decideBlockEnd(Token $token)
{
return $token->test('endfilter');
}
public function getTag()
{
return 'filter';
}
}
class_alias('Twig\TokenParser\FilterTokenParser',
'Twig_TokenParser_Filter');
twig/src/TokenParser/FlushTokenParser.php000064400000001336151161070030014507
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\FlushNode;
use Twig\Token;
/**
* Flushes the output to the client.
*
* @see flush()
*
* @final
*/
class FlushTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new FlushNode($token->getLine(), $this->getTag());
}
public function getTag()
{
return 'flush';
}
}
class_alias('Twig\TokenParser\FlushTokenParser',
'Twig_TokenParser_Flush');
twig/src/TokenParser/ForTokenParser.php000064400000011152151161070030014151
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\ForNode;
use Twig\Token;
use Twig\TokenStream;
/**
* Loops over each item of a sequence.
*
* <ul>
* {% for user in users %}
* <li>{{ user.username|e }}</li>
* {% endfor %}
* </ul>
*
* @final
*/
class ForTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$targets =
$this->parser->getExpressionParser()->parseAssignmentExpression();
$stream->expect(Token::OPERATOR_TYPE, 'in');
$seq =
$this->parser->getExpressionParser()->parseExpression();
$ifexpr = null;
if ($stream->nextIf(Token::NAME_TYPE, 'if')) {
$ifexpr =
$this->parser->getExpressionParser()->parseExpression();
}
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideForFork']);
if ('else' == $stream->next()->getValue()) {
$stream->expect(Token::BLOCK_END_TYPE);
$else = $this->parser->subparse([$this,
'decideForEnd'], true);
} else {
$else = null;
}
$stream->expect(Token::BLOCK_END_TYPE);
if (\count($targets) > 1) {
$keyTarget = $targets->getNode(0);
$keyTarget = new
AssignNameExpression($keyTarget->getAttribute('name'),
$keyTarget->getTemplateLine());
$valueTarget = $targets->getNode(1);
$valueTarget = new
AssignNameExpression($valueTarget->getAttribute('name'),
$valueTarget->getTemplateLine());
} else {
$keyTarget = new AssignNameExpression('_key',
$lineno);
$valueTarget = $targets->getNode(0);
$valueTarget = new
AssignNameExpression($valueTarget->getAttribute('name'),
$valueTarget->getTemplateLine());
}
if ($ifexpr) {
$this->checkLoopUsageCondition($stream, $ifexpr);
$this->checkLoopUsageBody($stream, $body);
}
return new ForNode($keyTarget, $valueTarget, $seq, $ifexpr, $body,
$else, $lineno, $this->getTag());
}
public function decideForFork(Token $token)
{
return $token->test(['else', 'endfor']);
}
public function decideForEnd(Token $token)
{
return $token->test('endfor');
}
// the loop variable cannot be used in the condition
protected function checkLoopUsageCondition(TokenStream $stream,
\Twig_NodeInterface $node)
{
if ($node instanceof GetAttrExpression &&
$node->getNode('node') instanceof NameExpression &&
'loop' ==
$node->getNode('node')->getAttribute('name')) {
throw new SyntaxError('The "loop" variable
cannot be used in a looping condition.', $node->getTemplateLine(),
$stream->getSourceContext());
}
foreach ($node as $n) {
if (!$n) {
continue;
}
$this->checkLoopUsageCondition($stream, $n);
}
}
// check usage of non-defined loop-items
// it does not catch all problems (for instance when a for is included
into another or when the variable is used in an include)
protected function checkLoopUsageBody(TokenStream $stream,
\Twig_NodeInterface $node)
{
if ($node instanceof GetAttrExpression &&
$node->getNode('node') instanceof NameExpression &&
'loop' ==
$node->getNode('node')->getAttribute('name')) {
$attribute = $node->getNode('attribute');
if ($attribute instanceof ConstantExpression &&
\in_array($attribute->getAttribute('value'),
['length', 'revindex0', 'revindex',
'last'])) {
throw new SyntaxError(sprintf('The "loop.%s"
variable is not defined when looping with a condition.',
$attribute->getAttribute('value')),
$node->getTemplateLine(), $stream->getSourceContext());
}
}
// should check for parent.loop.XXX usage
if ($node instanceof ForNode) {
return;
}
foreach ($node as $n) {
if (!$n) {
continue;
}
$this->checkLoopUsageBody($stream, $n);
}
}
public function getTag()
{
return 'for';
}
}
class_alias('Twig\TokenParser\ForTokenParser',
'Twig_TokenParser_For');
twig/src/TokenParser/FromTokenParser.php000064400000003570151161070030014333
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\ImportNode;
use Twig\Token;
/**
* Imports macros.
*
* {% from 'forms.html' import forms %}
*
* @final
*/
class FromTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$macro =
$this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
$stream->expect(Token::NAME_TYPE, 'import');
$targets = [];
do {
$name = $stream->expect(Token::NAME_TYPE)->getValue();
$alias = $name;
if ($stream->nextIf('as')) {
$alias =
$stream->expect(Token::NAME_TYPE)->getValue();
}
$targets[$name] = $alias;
if (!$stream->nextIf(Token::PUNCTUATION_TYPE,
',')) {
break;
}
} while (true);
$stream->expect(Token::BLOCK_END_TYPE);
$var = new AssignNameExpression($this->parser->getVarName(),
$token->getLine());
$node = new ImportNode($macro, $var, $token->getLine(),
$this->getTag());
foreach ($targets as $name => $alias) {
if ($this->parser->isReservedMacroName($name)) {
throw new SyntaxError(sprintf('"%s" cannot
be an imported macro as it is a reserved keyword.', $name),
$token->getLine(), $stream->getSourceContext());
}
$this->parser->addImportedSymbol('function',
$alias, 'get'.$name, $var);
}
return $node;
}
public function getTag()
{
return 'from';
}
}
class_alias('Twig\TokenParser\FromTokenParser',
'Twig_TokenParser_From');
twig/src/TokenParser/IfTokenParser.php000064400000004713151161070030013766
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\IfNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Tests a condition.
*
* {% if users %}
* <ul>
* {% for user in users %}
* <li>{{ user.username|e }}</li>
* {% endfor %}
* </ul>
* {% endif %}
*
* @final
*/
class IfTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$expr =
$this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideIfFork']);
$tests = [$expr, $body];
$else = null;
$end = false;
while (!$end) {
switch ($stream->next()->getValue()) {
case 'else':
$stream->expect(Token::BLOCK_END_TYPE);
$else = $this->parser->subparse([$this,
'decideIfEnd']);
break;
case 'elseif':
$expr =
$this->parser->getExpressionParser()->parseExpression();
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideIfFork']);
$tests[] = $expr;
$tests[] = $body;
break;
case 'endif':
$end = true;
break;
default:
throw new SyntaxError(sprintf('Unexpected end of
template. Twig was looking for the following tags "else",
"elseif", or "endif" to close the "if" block
started at line %d).', $lineno),
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
}
$stream->expect(Token::BLOCK_END_TYPE);
return new IfNode(new Node($tests), $else, $lineno,
$this->getTag());
}
public function decideIfFork(Token $token)
{
return $token->test(['elseif', 'else',
'endif']);
}
public function decideIfEnd(Token $token)
{
return $token->test(['endif']);
}
public function getTag()
{
return 'if';
}
}
class_alias('Twig\TokenParser\IfTokenParser',
'Twig_TokenParser_If');
twig/src/TokenParser/ImportTokenParser.php000064400000002206151161070030014675
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\ImportNode;
use Twig\Token;
/**
* Imports macros.
*
* {% import 'forms.html' as forms %}
*
* @final
*/
class ImportTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$macro =
$this->parser->getExpressionParser()->parseExpression();
$this->parser->getStream()->expect(Token::NAME_TYPE,
'as');
$var = new
AssignNameExpression($this->parser->getStream()->expect(Token::NAME_TYPE)->getValue(),
$token->getLine());
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$this->parser->addImportedSymbol('template',
$var->getAttribute('name'));
return new ImportNode($macro, $var, $token->getLine(),
$this->getTag());
}
public function getTag()
{
return 'import';
}
}
class_alias('Twig\TokenParser\ImportTokenParser',
'Twig_TokenParser_Import');
twig/src/TokenParser/IncludeTokenParser.php000064400000003123151161070030015005
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\IncludeNode;
use Twig\Token;
/**
* Includes a template.
*
* {% include 'header.html' %}
* Body
* {% include 'footer.html' %}
*/
class IncludeTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$expr =
$this->parser->getExpressionParser()->parseExpression();
list($variables, $only, $ignoreMissing) =
$this->parseArguments();
return new IncludeNode($expr, $variables, $only, $ignoreMissing,
$token->getLine(), $this->getTag());
}
protected function parseArguments()
{
$stream = $this->parser->getStream();
$ignoreMissing = false;
if ($stream->nextIf(Token::NAME_TYPE, 'ignore')) {
$stream->expect(Token::NAME_TYPE, 'missing');
$ignoreMissing = true;
}
$variables = null;
if ($stream->nextIf(Token::NAME_TYPE, 'with')) {
$variables =
$this->parser->getExpressionParser()->parseExpression();
}
$only = false;
if ($stream->nextIf(Token::NAME_TYPE, 'only')) {
$only = true;
}
$stream->expect(Token::BLOCK_END_TYPE);
return [$variables, $only, $ignoreMissing];
}
public function getTag()
{
return 'include';
}
}
class_alias('Twig\TokenParser\IncludeTokenParser',
'Twig_TokenParser_Include');
twig/src/TokenParser/MacroTokenParser.php000064400000003565151161070030014475
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\BodyNode;
use Twig\Node\MacroNode;
use Twig\Node\Node;
use Twig\Token;
/**
* Defines a macro.
*
* {% macro input(name, value, type, size) %}
* <input type="{{ type|default('text') }}"
name="{{ name }}" value="{{ value|e }}" size="{{
size|default(20) }}" />
* {% endmacro %}
*
* @final
*/
class MacroTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$name = $stream->expect(Token::NAME_TYPE)->getValue();
$arguments =
$this->parser->getExpressionParser()->parseArguments(true, true);
$stream->expect(Token::BLOCK_END_TYPE);
$this->parser->pushLocalScope();
$body = $this->parser->subparse([$this,
'decideBlockEnd'], true);
if ($token = $stream->nextIf(Token::NAME_TYPE)) {
$value = $token->getValue();
if ($value != $name) {
throw new SyntaxError(sprintf('Expected endmacro for
macro "%s" (but "%s" given).', $name, $value),
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
}
$this->parser->popLocalScope();
$stream->expect(Token::BLOCK_END_TYPE);
$this->parser->setMacro($name, new MacroNode($name, new
BodyNode([$body]), $arguments, $lineno, $this->getTag()));
return new Node();
}
public function decideBlockEnd(Token $token)
{
return $token->test('endmacro');
}
public function getTag()
{
return 'macro';
}
}
class_alias('Twig\TokenParser\MacroTokenParser',
'Twig_TokenParser_Macro');
twig/src/TokenParser/SandboxTokenParser.php000064400000003444151161070030015026
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\IncludeNode;
use Twig\Node\SandboxNode;
use Twig\Node\TextNode;
use Twig\Token;
/**
* Marks a section of a template as untrusted code that must be evaluated
in the sandbox mode.
*
* {% sandbox %}
* {% include 'user.html' %}
* {% endsandbox %}
*
* @see https://twig.symfony.com/doc/api.html#sandbox-extension for details
*
* @final
*/
class SandboxTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$stream = $this->parser->getStream();
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideBlockEnd'], true);
$stream->expect(Token::BLOCK_END_TYPE);
// in a sandbox tag, only include tags are allowed
if (!$body instanceof IncludeNode) {
foreach ($body as $node) {
if ($node instanceof TextNode &&
ctype_space($node->getAttribute('data'))) {
continue;
}
if (!$node instanceof IncludeNode) {
throw new SyntaxError('Only "include"
tags are allowed within a "sandbox" section.',
$node->getTemplateLine(), $stream->getSourceContext());
}
}
}
return new SandboxNode($body, $token->getLine(),
$this->getTag());
}
public function decideBlockEnd(Token $token)
{
return $token->test('endsandbox');
}
public function getTag()
{
return 'sandbox';
}
}
class_alias('Twig\TokenParser\SandboxTokenParser',
'Twig_TokenParser_Sandbox');
twig/src/TokenParser/SetTokenParser.php000064400000004037151161070030014162
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\SetNode;
use Twig\Token;
/**
* Defines a variable.
*
* {% set foo = 'foo' %}
* {% set foo = [1, 2] %}
* {% set foo = {'foo': 'bar'} %}
* {% set foo = 'foo' ~ 'bar' %}
* {% set foo, bar = 'foo', 'bar' %}
* {% set foo %}Some content{% endset %}
*
* @final
*/
class SetTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$stream = $this->parser->getStream();
$names =
$this->parser->getExpressionParser()->parseAssignmentExpression();
$capture = false;
if ($stream->nextIf(Token::OPERATOR_TYPE, '=')) {
$values =
$this->parser->getExpressionParser()->parseMultitargetExpression();
$stream->expect(Token::BLOCK_END_TYPE);
if (\count($names) !== \count($values)) {
throw new SyntaxError('When using set, you must have
the same number of variables and assignments.',
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
} else {
$capture = true;
if (\count($names) > 1) {
throw new SyntaxError('When using set with a block,
you cannot have a multi-target.',
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$stream->expect(Token::BLOCK_END_TYPE);
$values = $this->parser->subparse([$this,
'decideBlockEnd'], true);
$stream->expect(Token::BLOCK_END_TYPE);
}
return new SetNode($capture, $names, $values, $lineno,
$this->getTag());
}
public function decideBlockEnd(Token $token)
{
return $token->test('endset');
}
public function getTag()
{
return 'set';
}
}
class_alias('Twig\TokenParser\SetTokenParser',
'Twig_TokenParser_Set');
twig/src/TokenParser/SpacelessTokenParser.php000064400000002262151161070030015347
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\SpacelessNode;
use Twig\Token;
/**
* Remove whitespaces between HTML tags.
*
* {% spaceless %}
* <div>
* <strong>foo</strong>
* </div>
* {% endspaceless %}
* {# output will be
<div><strong>foo</strong></div> #}
*
* @final
*/
class SpacelessTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$lineno = $token->getLine();
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideSpacelessEnd'], true);
$this->parser->getStream()->expect(Token::BLOCK_END_TYPE);
return new SpacelessNode($body, $lineno, $this->getTag());
}
public function decideSpacelessEnd(Token $token)
{
return $token->test('endspaceless');
}
public function getTag()
{
return 'spaceless';
}
}
class_alias('Twig\TokenParser\SpacelessTokenParser',
'Twig_TokenParser_Spaceless');
twig/src/TokenParser/TokenParserInterface.php000064400000002161151161070030015323
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Parser;
use Twig\Token;
/**
* Interface implemented by token parsers.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface TokenParserInterface
{
/**
* Sets the parser associated with this token parser.
*/
public function setParser(Parser $parser);
/**
* Parses a token and returns a node.
*
* @return \Twig_NodeInterface
*
* @throws SyntaxError
*/
public function parse(Token $token);
/**
* Gets the tag name associated with this token parser.
*
* @return string The tag name
*/
public function getTag();
}
class_alias('Twig\TokenParser\TokenParserInterface',
'Twig_TokenParserInterface');
// Ensure that the aliased name is loaded to keep BC for classes
implementing the typehint with the old aliased name.
class_exists('Twig\Token');
class_exists('Twig\Parser');
twig/src/TokenParser/UseTokenParser.php000064400000003712151161070030014162
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Error\SyntaxError;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Node;
use Twig\Token;
/**
* Imports blocks defined in another template into the current template.
*
* {% extends "base.html" %}
*
* {% use "blocks.html" %}
*
* {% block title %}{% endblock %}
* {% block content %}{% endblock %}
*
* @see https://twig.symfony.com/doc/templates.html#horizontal-reuse for
details.
*
* @final
*/
class UseTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$template =
$this->parser->getExpressionParser()->parseExpression();
$stream = $this->parser->getStream();
if (!$template instanceof ConstantExpression) {
throw new SyntaxError('The template references in a
"use" statement must be a string.',
$stream->getCurrent()->getLine(), $stream->getSourceContext());
}
$targets = [];
if ($stream->nextIf('with')) {
do {
$name =
$stream->expect(Token::NAME_TYPE)->getValue();
$alias = $name;
if ($stream->nextIf('as')) {
$alias =
$stream->expect(Token::NAME_TYPE)->getValue();
}
$targets[$name] = new ConstantExpression($alias, -1);
if (!$stream->nextIf(Token::PUNCTUATION_TYPE,
',')) {
break;
}
} while (true);
}
$stream->expect(Token::BLOCK_END_TYPE);
$this->parser->addTrait(new Node(['template' =>
$template, 'targets' => new Node($targets)]));
return new Node();
}
public function getTag()
{
return 'use';
}
}
class_alias('Twig\TokenParser\UseTokenParser',
'Twig_TokenParser_Use');
twig/src/TokenParser/WithTokenParser.php000064400000002410151161070030014333
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\TokenParser;
use Twig\Node\WithNode;
use Twig\Token;
/**
* Creates a nested scope.
*
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class WithTokenParser extends AbstractTokenParser
{
public function parse(Token $token)
{
$stream = $this->parser->getStream();
$variables = null;
$only = false;
if (!$stream->test(Token::BLOCK_END_TYPE)) {
$variables =
$this->parser->getExpressionParser()->parseExpression();
$only = $stream->nextIf(Token::NAME_TYPE, 'only');
}
$stream->expect(Token::BLOCK_END_TYPE);
$body = $this->parser->subparse([$this,
'decideWithEnd'], true);
$stream->expect(Token::BLOCK_END_TYPE);
return new WithNode($body, $variables, $only, $token->getLine(),
$this->getTag());
}
public function decideWithEnd(Token $token)
{
return $token->test('endwith');
}
public function getTag()
{
return 'with';
}
}
class_alias('Twig\TokenParser\WithTokenParser',
'Twig_TokenParser_With');
twig/src/TokenStream.php000064400000012564151161070030011254
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Error\SyntaxError;
/**
* Represents a token stream.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TokenStream
{
protected $tokens;
protected $current = 0;
protected $filename;
private $source;
/**
* @param array $tokens An array of tokens
* @param string|null $name The name of the template which tokens are
associated with
* @param string|null $source The source code associated with the
tokens
*/
public function __construct(array $tokens, $name = null, $source =
null)
{
if (!$name instanceof Source) {
if (null !== $name || null !== $source) {
@trigger_error(sprintf('Passing a string as the $name
argument of %s() is deprecated since version 1.27. Pass a \Twig\Source
instance instead.', __METHOD__), E_USER_DEPRECATED);
}
$this->source = new Source($source, $name);
} else {
$this->source = $name;
}
$this->tokens = $tokens;
// deprecated, not used anymore, to be removed in 2.0
$this->filename = $this->source->getName();
}
public function __toString()
{
return implode("\n", $this->tokens);
}
public function injectTokens(array $tokens)
{
$this->tokens = array_merge(\array_slice($this->tokens, 0,
$this->current), $tokens, \array_slice($this->tokens,
$this->current));
}
/**
* Sets the pointer to the next token and returns the old one.
*
* @return Token
*/
public function next()
{
if (!isset($this->tokens[++$this->current])) {
throw new SyntaxError('Unexpected end of template.',
$this->tokens[$this->current - 1]->getLine(), $this->source);
}
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.
*
* @return Token
*/
public function expect($type, $value = null, $message = null)
{
$token = $this->tokens[$this->current];
if (!$token->test($type, $value)) {
$line = $token->getLine();
throw new SyntaxError(sprintf('%sUnexpected token
"%s"%s ("%s" expected%s).',
$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.
*
* @param int $number
*
* @return Token
*/
public function look($number = 1)
{
if (!isset($this->tokens[$this->current + $number])) {
throw new SyntaxError('Unexpected end of template.',
$this->tokens[$this->current + $number - 1]->getLine(),
$this->source);
}
return $this->tokens[$this->current + $number];
}
/**
* Tests the current token.
*
* @return bool
*/
public function test($primary, $secondary = null)
{
return $this->tokens[$this->current]->test($primary,
$secondary);
}
/**
* Checks if end of stream was reached.
*
* @return bool
*/
public function isEOF()
{
return Token::EOF_TYPE ===
$this->tokens[$this->current]->getType();
}
/**
* @return Token
*/
public function getCurrent()
{
return $this->tokens[$this->current];
}
/**
* Gets the name associated with this stream (null if not defined).
*
* @return string|null
*
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function getFilename()
{
@trigger_error(sprintf('The %s() method is deprecated since
version 1.27 and will be removed in 2.0. Use getSourceContext()
instead.', __METHOD__), E_USER_DEPRECATED);
return $this->source->getName();
}
/**
* Gets the source code associated with this stream.
*
* @return string
*
* @internal Don't use this as it might be empty depending on the
environment configuration
*
* @deprecated since 1.27 (to be removed in 2.0)
*/
public function getSource()
{
@trigger_error(sprintf('The %s() method is deprecated since
version 1.27 and will be removed in 2.0. Use getSourceContext()
instead.', __METHOD__), E_USER_DEPRECATED);
return $this->source->getCode();
}
/**
* Gets the source associated with this stream.
*
* @return Source
*
* @internal
*/
public function getSourceContext()
{
return $this->source;
}
}
class_alias('Twig\TokenStream', 'Twig_TokenStream');
twig/src/TwigFilter.php000064400000005375151161070030011102
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Node\Node;
/**
* Represents a template filter.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TwigFilter
{
protected $name;
protected $callable;
protected $options;
protected $arguments = [];
public function __construct($name, $callable, array $options = [])
{
$this->name = $name;
$this->callable = $callable;
$this->options = array_merge([
'needs_environment' => false,
'needs_context' => false,
'is_variadic' => false,
'is_safe' => null,
'is_safe_callback' => null,
'pre_escape' => null,
'preserves_safety' => null,
'node_class' =>
'\Twig\Node\Expression\FilterExpression',
'deprecated' => false,
'alternative' => null,
], $options);
}
public function getName()
{
return $this->name;
}
public function getCallable()
{
return $this->callable;
}
public function getNodeClass()
{
return $this->options['node_class'];
}
public function setArguments($arguments)
{
$this->arguments = $arguments;
}
public function getArguments()
{
return $this->arguments;
}
public function needsEnvironment()
{
return $this->options['needs_environment'];
}
public function needsContext()
{
return $this->options['needs_context'];
}
public function getSafe(Node $filterArgs)
{
if (null !== $this->options['is_safe']) {
return $this->options['is_safe'];
}
if (null !== $this->options['is_safe_callback']) {
return
\call_user_func($this->options['is_safe_callback'],
$filterArgs);
}
}
public function getPreservesSafety()
{
return $this->options['preserves_safety'];
}
public function getPreEscape()
{
return $this->options['pre_escape'];
}
public function isVariadic()
{
return $this->options['is_variadic'];
}
public function isDeprecated()
{
return (bool) $this->options['deprecated'];
}
public function getDeprecatedVersion()
{
return $this->options['deprecated'];
}
public function getAlternative()
{
return $this->options['alternative'];
}
}
class_alias('Twig\TwigFilter', 'Twig_SimpleFilter');
// Ensure that the aliased name is loaded to keep BC for classes
implementing the typehint with the old aliased name.
class_exists('Twig\Node\Node');
twig/src/TwigFunction.php000064400000005017151161070030011433
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
use Twig\Node\Node;
/**
* Represents a template function.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TwigFunction
{
protected $name;
protected $callable;
protected $options;
protected $arguments = [];
public function __construct($name, $callable, array $options = [])
{
$this->name = $name;
$this->callable = $callable;
$this->options = array_merge([
'needs_environment' => false,
'needs_context' => false,
'is_variadic' => false,
'is_safe' => null,
'is_safe_callback' => null,
'node_class' =>
'\Twig\Node\Expression\FunctionExpression',
'deprecated' => false,
'alternative' => null,
], $options);
}
public function getName()
{
return $this->name;
}
public function getCallable()
{
return $this->callable;
}
public function getNodeClass()
{
return $this->options['node_class'];
}
public function setArguments($arguments)
{
$this->arguments = $arguments;
}
public function getArguments()
{
return $this->arguments;
}
public function needsEnvironment()
{
return $this->options['needs_environment'];
}
public function needsContext()
{
return $this->options['needs_context'];
}
public function getSafe(Node $functionArgs)
{
if (null !== $this->options['is_safe']) {
return $this->options['is_safe'];
}
if (null !== $this->options['is_safe_callback']) {
return
\call_user_func($this->options['is_safe_callback'],
$functionArgs);
}
return [];
}
public function isVariadic()
{
return $this->options['is_variadic'];
}
public function isDeprecated()
{
return (bool) $this->options['deprecated'];
}
public function getDeprecatedVersion()
{
return $this->options['deprecated'];
}
public function getAlternative()
{
return $this->options['alternative'];
}
}
class_alias('Twig\TwigFunction',
'Twig_SimpleFunction');
// Ensure that the aliased name is loaded to keep BC for classes
implementing the typehint with the old aliased name.
class_exists('Twig\Node\Node');
twig/src/TwigTest.php000064400000003227151161070030010566 0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Represents a template test.
*
* @final
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TwigTest
{
protected $name;
protected $callable;
protected $options;
private $arguments = [];
public function __construct($name, $callable, array $options = [])
{
$this->name = $name;
$this->callable = $callable;
$this->options = array_merge([
'is_variadic' => false,
'node_class' =>
'\Twig\Node\Expression\TestExpression',
'deprecated' => false,
'alternative' => null,
], $options);
}
public function getName()
{
return $this->name;
}
public function getCallable()
{
return $this->callable;
}
public function getNodeClass()
{
return $this->options['node_class'];
}
public function isVariadic()
{
return $this->options['is_variadic'];
}
public function isDeprecated()
{
return (bool) $this->options['deprecated'];
}
public function getDeprecatedVersion()
{
return $this->options['deprecated'];
}
public function getAlternative()
{
return $this->options['alternative'];
}
public function setArguments($arguments)
{
$this->arguments = $arguments;
}
public function getArguments()
{
return $this->arguments;
}
}
class_alias('Twig\TwigTest', 'Twig_SimpleTest');
twig/src/Util/DeprecationCollector.php000064400000004352151161070030014035
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Util;
use Twig\Environment;
use Twig\Error\SyntaxError;
use Twig\Source;
/**
* @author Fabien Potencier <fabien@symfony.com>
*
* @final
*/
class DeprecationCollector
{
private $twig;
private $deprecations;
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)
{
$this->deprecations = [];
set_error_handler([$this, 'errorHandler']);
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();
$deprecations = $this->deprecations;
$this->deprecations = [];
return $deprecations;
}
/**
* @internal
*/
public function errorHandler($type, $msg)
{
if (E_USER_DEPRECATED === $type) {
$this->deprecations[] = $msg;
}
}
}
class_alias('Twig\Util\DeprecationCollector',
'Twig_Util_DeprecationCollector');
twig/src/Util/TemplateDirIterator.php000064400000001116151161070030013650
0ustar00<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Util;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
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');