deprecated Twig_ExtensionInterface::getName()

This commit is contained in:
Fabien Potencier
2016-09-26 16:19:47 -07:00
parent 52e9e01353
commit 71f03df011
32 changed files with 151 additions and 108 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
* 1.25.1 (2016-XX-XX) * 1.26.0 (2016-XX-XX)
* n/a * deprecated Twig_ExtensionInterface::getName()
* 1.25.0 (2016-09-21) * 1.25.0 (2016-09-21)
+1 -1
View File
@@ -40,7 +40,7 @@
}, },
"extra": { "extra": {
"branch-alias": { "branch-alias": {
"dev-master": "1.25-dev" "dev-master": "1.26-dev"
} }
} }
} }
+10 -20
View File
@@ -613,32 +613,27 @@ An extension is a class that implements the following interface::
* Returns the name of the extension. * Returns the name of the extension.
* *
* @return string The extension name * @return string The extension name
*
* @deprecated since 1.26 (to be removed in 2.0), not used anymore internally
*/ */
function getName(); function getName();
} }
To keep your extension class clean and lean, it can inherit from the built-in To keep your extension class clean and lean, inherit from the built-in
``Twig_Extension`` class instead of implementing the whole interface. That ``Twig_Extension`` class instead of implementing the interface as it provides
way, you just need to implement the ``getName()`` method as the empty implementations for all methods:
``Twig_Extension`` provides empty implementations for all other methods.
The ``getName()`` method must return a unique identifier for your extension.
Now, with this information in mind, let's create the most basic extension
possible::
class Project_Twig_Extension extends Twig_Extension class Project_Twig_Extension extends Twig_Extension
{ {
public function getName()
{
return 'project';
}
} }
Of course, this extension does nothing for now. We will customize it in the
next sections.
.. note:: .. note::
Of course, this extension does nothing for now. We will customize it in Prior to Twig 1.26, you must implement the ``getName()`` method which must
the next sections. return a unique identifier for the extension.
Twig does not care where you save your extension on the filesystem, as all Twig does not care where you save your extension on the filesystem, as all
extensions must be registered explicitly to be available in your templates. extensions must be registered explicitly to be available in your templates.
@@ -790,11 +785,6 @@ possible** (order matters)::
{ {
// do something different from the built-in date filter // do something different from the built-in date filter
} }
public function getName()
{
return 'project';
}
} }
$twig = new Twig_Environment($loader); $twig = new Twig_Environment($loader);
+3
View File
@@ -37,6 +37,9 @@ Extensions
deprecated. Implement ``Twig_Extension_GlobalsInterface`` to avoid deprecated. Implement ``Twig_Extension_GlobalsInterface`` to avoid
deprecation notices. deprecation notices.
* As of Twig 1.26, the ``Twig_ExtensionInterface::getName()`` method is
deprecated and it is not used internally anymore.
PEAR PEAR
---- ----
+6
View File
@@ -54,6 +54,9 @@ dates and the second one is the default format for date intervals:
.. code-block:: php .. code-block:: php
$twig = new Twig_Environment($loader); $twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setDateFormat('d/m/Y', '%d days');
// before Twig 1.26
$twig->getExtension('core')->setDateFormat('d/m/Y', '%d days'); $twig->getExtension('core')->setDateFormat('d/m/Y', '%d days');
Timezone Timezone
@@ -79,6 +82,9 @@ The default timezone can also be set globally by calling ``setTimezone()``:
.. code-block:: php .. code-block:: php
$twig = new Twig_Environment($loader); $twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setTimezone('Europe/Paris');
// before Twig 1.26
$twig->getExtension('core')->setTimezone('Europe/Paris'); $twig->getExtension('core')->setTimezone('Europe/Paris');
Arguments Arguments
+3
View File
@@ -97,6 +97,9 @@ used in the ``escape`` call) and the second one must be a valid PHP callable:
.. code-block:: php .. code-block:: php
$twig = new Twig_Environment($loader); $twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setEscaper('csv', 'csv_escaper');
// before Twig 1.26
$twig->getExtension('core')->setEscaper('csv', 'csv_escaper'); $twig->getExtension('core')->setEscaper('csv', 'csv_escaper');
When called by Twig, the callable receives the Twig environment instance, the When called by Twig, the callable receives the Twig environment instance, the
+3
View File
@@ -30,6 +30,9 @@ These defaults can be easily changed through the core extension:
.. code-block:: php .. code-block:: php
$twig = new Twig_Environment($loader); $twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setNumberFormat(3, '.', ',');
// before Twig 1.26
$twig->getExtension('core')->setNumberFormat(3, '.', ','); $twig->getExtension('core')->setNumberFormat(3, '.', ',');
The defaults set for ``number_format`` can be over-ridden upon each call using the The defaults set for ``number_format`` can be over-ridden upon each call using the
+3
View File
@@ -41,6 +41,9 @@ If no argument is passed, the function returns the current date:
.. code-block:: php .. code-block:: php
$twig = new Twig_Environment($loader); $twig = new Twig_Environment($loader);
$twig->getExtension('Twig_Extension_Core')->setTimezone('Europe/Paris');
// before Twig 1.26
$twig->getExtension('core')->setTimezone('Europe/Paris'); $twig->getExtension('core')->setTimezone('Europe/Paris');
Arguments Arguments
+1 -1
View File
@@ -15,7 +15,7 @@
#ifndef PHP_TWIG_H #ifndef PHP_TWIG_H
#define PHP_TWIG_H #define PHP_TWIG_H
#define PHP_TWIG_VERSION "1.25.1-DEV" #define PHP_TWIG_VERSION "1.26.0-DEV"
#include "php.h" #include "php.h"
+8 -8
View File
@@ -916,8 +916,8 @@ PHP_FUNCTION(twig_template_get_attributes)
return true; return true;
} }
if ($this->env->hasExtension('sandbox')) { if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
$this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item); $this->env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item);
} }
return $object->$item; return $object->$item;
@@ -935,8 +935,8 @@ PHP_FUNCTION(twig_template_get_attributes)
efree(item); efree(item);
RETURN_TRUE; RETURN_TRUE;
} }
if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "sandbox" TSRMLS_CC)) { if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "Twig_Extension_Sandbox" TSRMLS_CC)) {
TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "sandbox" TSRMLS_CC), "checkPropertyAllowed", object, zitem TSRMLS_CC); TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "Twig_Extension_Sandbox" TSRMLS_CC), "checkPropertyAllowed", object, zitem TSRMLS_CC);
} }
if (EG(exception)) { if (EG(exception)) {
efree(item); efree(item);
@@ -1052,14 +1052,14 @@ PHP_FUNCTION(twig_template_get_attributes)
RETURN_TRUE; RETURN_TRUE;
} }
/* /*
if ($this->env->hasExtension('sandbox')) { if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
$this->env->getExtension('sandbox')->checkMethodAllowed($object, $method); $this->env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method);
} }
*/ */
MAKE_STD_ZVAL(zmethod); MAKE_STD_ZVAL(zmethod);
ZVAL_STRING(zmethod, method, 1); ZVAL_STRING(zmethod, method, 1);
if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "sandbox" TSRMLS_CC)) { if (TWIG_CALL_SB(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "hasExtension", "Twig_Extension_Sandbox" TSRMLS_CC)) {
TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "sandbox" TSRMLS_CC), "checkMethodAllowed", object, zmethod TSRMLS_CC); TWIG_CALL_ZZ(TWIG_CALL_S(TWIG_PROPERTY_CHAR(template, "env" TSRMLS_CC), "getExtension", "Twig_Extension_Sandbox" TSRMLS_CC), "checkMethodAllowed", object, zmethod TSRMLS_CC);
} }
zval_ptr_dtor(&zmethod); zval_ptr_dtor(&zmethod);
if (EG(exception)) { if (EG(exception)) {
+42 -18
View File
@@ -16,7 +16,7 @@
*/ */
class Twig_Environment class Twig_Environment
{ {
const VERSION = '1.25.1-DEV'; const VERSION = '1.26.0-DEV';
protected $charset; protected $charset;
protected $loader; protected $loader;
@@ -49,6 +49,7 @@ class Twig_Environment
private $bcWriteCacheFile = false; private $bcWriteCacheFile = false;
private $bcGetCacheFilename = false; private $bcGetCacheFilename = false;
private $lastModifiedExtension = 0; private $lastModifiedExtension = 0;
private $legacyExtensionNames = array();
/** /**
* Constructor. * Constructor.
@@ -771,29 +772,41 @@ class Twig_Environment
/** /**
* Returns true if the given extension is registered. * Returns true if the given extension is registered.
* *
* @param string $name The extension name * @param string $class The extension class name
* *
* @return bool Whether the extension is registered or not * @return bool Whether the extension is registered or not
*/ */
public function hasExtension($name) public function hasExtension($class)
{ {
return isset($this->extensions[$name]); if (isset($this->legacyExtensionNames[$class])) {
$class = $this->legacyExtensionNames[$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 isset($this->extensions[ltrim($class, '\\')]);
} }
/** /**
* Gets an extension by name. * Gets an extension by class name.
* *
* @param string $name The extension name * @param string $class The extension class name
* *
* @return Twig_ExtensionInterface A Twig_ExtensionInterface instance * @return Twig_ExtensionInterface A Twig_ExtensionInterface instance
*/ */
public function getExtension($name) public function getExtension($class)
{ {
if (!isset($this->extensions[$name])) { if (isset($this->legacyExtensionNames[$class])) {
throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $name)); $class = $this->legacyExtensionNames[$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[$name]; $class = ltrim($class, '\\');
if (!isset($this->extensions[$class])) {
throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $class));
}
return $this->extensions[$class];
} }
/** /**
@@ -803,19 +816,25 @@ class Twig_Environment
*/ */
public function addExtension(Twig_ExtensionInterface $extension) public function addExtension(Twig_ExtensionInterface $extension)
{ {
$name = $extension->getName(); $class = get_class($extension);
if ($this->extensionInitialized) { if ($this->extensionInitialized) {
throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $name)); throw new LogicException(sprintf('Unable to register extension "%s" as extensions have already been initialized.', $class));
} }
if (isset($this->extensions[$name])) { $m = new ReflectionMethod($extension, 'getName');
@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.', $name), E_USER_DEPRECATED); $legacyName = 'Twig_Extension' !== $m->getDeclaringClass()->getName() ? $extension->getName() : null;
if (isset($this->extensions[$class]) || (null !== $legacyName && isset($this->legacyExtensionNames[$legacyName]))) {
unset($this->extensions[$this->legacyExtensionNames[$legacyName]], $this->legacyExtensionNames[$legacyName]);
@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.', $class), E_USER_DEPRECATED);
} }
$this->lastModifiedExtension = 0; $this->lastModifiedExtension = 0;
if ($legacyName !== $class) {
$this->extensions[$name] = $extension; $this->legacyExtensionNames[$legacyName] = $class;
}
$this->extensions[$class] = $extension;
} }
/** /**
@@ -831,11 +850,16 @@ class Twig_Environment
{ {
@trigger_error(sprintf('The %s method is deprecated since version 1.12 and will be removed in Twig 2.0.', __METHOD__), E_USER_DEPRECATED); @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 (isset($this->legacyExtensionNames[$name])) {
$name = $this->legacyExtensionNames[$name];
@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.', $name), E_USER_DEPRECATED);
}
if ($this->extensionInitialized) { if ($this->extensionInitialized) {
throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name)); throw new LogicException(sprintf('Unable to remove extension "%s" as extensions have already been initialized.', $name));
} }
unset($this->extensions[$name]); unset($this->extensions[ltrim($name, '\\')]);
} }
/** /**
@@ -853,7 +877,7 @@ class Twig_Environment
/** /**
* Returns all registered extensions. * Returns all registered extensions.
* *
* @return array An array of extensions * @return Twig_ExtensionInterface[] An array of extensions (keys are for internal usage only and should not be relied on)
*/ */
public function getExtensions() public function getExtensions()
{ {
+10
View File
@@ -76,4 +76,14 @@ abstract class Twig_Extension implements Twig_ExtensionInterface
{ {
return array(); return array();
} }
/**
* {@inheritdoc}
*
* @deprecated since 1.26 (to be removed in 2.0), not used anymore internally
*/
public function getName()
{
return get_class($this);
}
} }
+8 -8
View File
@@ -433,7 +433,7 @@ function twig_random(Twig_Environment $env, $values = null)
function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null) function twig_date_format_filter(Twig_Environment $env, $date, $format = null, $timezone = null)
{ {
if (null === $format) { if (null === $format) {
$formats = $env->getExtension('core')->getDateFormat(); $formats = $env->getExtension('Twig_Extension_Core')->getDateFormat();
$format = $date instanceof DateInterval ? $formats[1] : $formats[0]; $format = $date instanceof DateInterval ? $formats[1] : $formats[0];
} }
@@ -488,7 +488,7 @@ function twig_date_converter(Twig_Environment $env, $date = null, $timezone = nu
// determine the timezone // determine the timezone
if (false !== $timezone) { if (false !== $timezone) {
if (null === $timezone) { if (null === $timezone) {
$timezone = $env->getExtension('core')->getTimezone(); $timezone = $env->getExtension('Twig_Extension_Core')->getTimezone();
} elseif (!$timezone instanceof DateTimeZone) { } elseif (!$timezone instanceof DateTimeZone) {
$timezone = new DateTimeZone($timezone); $timezone = new DateTimeZone($timezone);
} }
@@ -509,14 +509,14 @@ function twig_date_converter(Twig_Environment $env, $date = null, $timezone = nu
} }
if (null === $date || 'now' === $date) { if (null === $date || 'now' === $date) {
return new DateTime($date, false !== $timezone ? $timezone : $env->getExtension('core')->getTimezone()); return new DateTime($date, false !== $timezone ? $timezone : $env->getExtension('Twig_Extension_Core')->getTimezone());
} }
$asString = (string) $date; $asString = (string) $date;
if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) { if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) {
$date = new DateTime('@'.$date); $date = new DateTime('@'.$date);
} else { } else {
$date = new DateTime($date, $env->getExtension('core')->getTimezone()); $date = new DateTime($date, $env->getExtension('Twig_Extension_Core')->getTimezone());
} }
if (false !== $timezone) { if (false !== $timezone) {
@@ -589,7 +589,7 @@ function twig_round($value, $precision = 0, $method = 'common')
*/ */
function twig_number_format_filter(Twig_Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null) function twig_number_format_filter(Twig_Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null)
{ {
$defaults = $env->getExtension('core')->getNumberFormat(); $defaults = $env->getExtension('Twig_Extension_Core')->getNumberFormat();
if (null === $decimal) { if (null === $decimal) {
$decimal = $defaults[0]; $decimal = $defaults[0];
} }
@@ -1115,7 +1115,7 @@ function twig_escape_filter(Twig_Environment $env, $string, $strategy = 'html',
static $escapers; static $escapers;
if (null === $escapers) { if (null === $escapers) {
$escapers = $env->getExtension('core')->getEscapers(); $escapers = $env->getExtension('Twig_Extension_Core')->getEscapers();
} }
if (isset($escapers[$strategy])) { if (isset($escapers[$strategy])) {
@@ -1451,8 +1451,8 @@ function twig_include(Twig_Environment $env, $context, $template, $variables = a
$variables = array_merge($context, $variables); $variables = array_merge($context, $variables);
} }
if ($isSandboxed = $sandboxed && $env->hasExtension('sandbox')) { if ($isSandboxed = $sandboxed && $env->hasExtension('Twig_Extension_Sandbox')) {
$sandbox = $env->getExtension('sandbox'); $sandbox = $env->getExtension('Twig_Extension_Sandbox');
if (!$alreadySandboxed = $sandbox->isSandboxed()) { if (!$alreadySandboxed = $sandbox->isSandboxed()) {
$sandbox->enableSandbox(); $sandbox->enableSandbox();
} }
+2
View File
@@ -82,6 +82,8 @@ interface Twig_ExtensionInterface
* Returns the name of the extension. * Returns the name of the extension.
* *
* @return string The extension name * @return string The extension name
*
* @deprecated since 1.26 (to be removed in 2.0), not used anymore internally
*/ */
public function getName(); public function getName();
} }
+1 -1
View File
@@ -37,6 +37,6 @@ class Twig_Filter_Method extends Twig_Filter
public function compile() public function compile()
{ {
return sprintf('$this->env->getExtension(\'%s\')->%s', $this->extension->getName(), $this->method); return sprintf('$this->env->getExtension(\'%s\')->%s', get_class($this->extension), $this->method);
} }
} }
+1 -1
View File
@@ -38,6 +38,6 @@ class Twig_Function_Method extends Twig_Function
public function compile() public function compile()
{ {
return sprintf('$this->env->getExtension(\'%s\')->%s', $this->extension->getName(), $this->method); return sprintf('$this->env->getExtension(\'%s\')->%s', get_class($this->extension), $this->method);
} }
} }
+1 -1
View File
@@ -46,7 +46,7 @@ class Twig_Node_CheckSecurity extends Twig_Node
->write('$functions = ')->repr(array_filter($functions))->raw(";\n\n") ->write('$functions = ')->repr(array_filter($functions))->raw(";\n\n")
->write("try {\n") ->write("try {\n")
->indent() ->indent()
->write("\$this->env->getExtension('sandbox')->checkSecurity(\n") ->write("\$this->env->getExtension('Twig_Extension_Sandbox')->checkSecurity(\n")
->indent() ->indent()
->write(!$tags ? "array(),\n" : "array('".implode("', '", array_keys($tags))."'),\n") ->write(!$tags ? "array(),\n" : "array('".implode("', '", array_keys($tags))."'),\n")
->write(!$filters ? "array(),\n" : "array('".implode("', '", array_keys($filters))."'),\n") ->write(!$filters ? "array(),\n" : "array('".implode("', '", array_keys($filters))."'),\n")
+1 -1
View File
@@ -17,7 +17,7 @@ abstract class Twig_Node_Expression_Call extends Twig_Node_Expression
if (is_string($callable)) { if (is_string($callable)) {
$compiler->raw($callable); $compiler->raw($callable);
} elseif (is_array($callable) && $callable[0] instanceof Twig_ExtensionInterface) { } elseif (is_array($callable) && $callable[0] instanceof Twig_ExtensionInterface) {
$compiler->raw(sprintf('$this->env->getExtension(\'%s\')->%s', $callable[0]->getName(), $callable[1])); $compiler->raw(sprintf('$this->env->getExtension(\'%s\')->%s', get_class($callable[0]), $callable[1]));
} else { } else {
$type = ucfirst($this->getAttribute('type')); $type = ucfirst($this->getAttribute('type'));
$compiler->raw(sprintf('call_user_func_array($this->env->get%s(\'%s\')->getCallable(), array', $type, $this->getAttribute('name'))); $compiler->raw(sprintf('call_user_func_array($this->env->get%s(\'%s\')->getCallable(), array', $type, $this->getAttribute('name')));
+1 -1
View File
@@ -25,7 +25,7 @@ class Twig_Node_Sandbox extends Twig_Node
{ {
$compiler $compiler
->addDebugInfo($this) ->addDebugInfo($this)
->write("\$sandbox = \$this->env->getExtension('sandbox');\n") ->write("\$sandbox = \$this->env->getExtension('Twig_Extension_Sandbox');\n")
->write("if (!\$alreadySandboxed = \$sandbox->isSandboxed()) {\n") ->write("if (!\$alreadySandboxed = \$sandbox->isSandboxed()) {\n")
->indent() ->indent()
->write("\$sandbox->enableSandbox();\n") ->write("\$sandbox->enableSandbox();\n")
+1 -1
View File
@@ -25,7 +25,7 @@ class Twig_Node_SandboxedPrint extends Twig_Node_Print
{ {
$compiler $compiler
->addDebugInfo($this) ->addDebugInfo($this)
->write('echo $this->env->getExtension(\'sandbox\')->ensureToStringAllowed(') ->write('echo $this->env->getExtension(\'Twig_Extension_Sandbox\')->ensureToStringAllowed(')
->subcompile($this->getNode('expr')) ->subcompile($this->getNode('expr'))
->raw(");\n") ->raw(");\n")
; ;
+1 -1
View File
@@ -34,7 +34,7 @@ class Twig_NodeVisitor_Escaper extends Twig_BaseNodeVisitor
protected function doEnterNode(Twig_Node $node, Twig_Environment $env) protected function doEnterNode(Twig_Node $node, Twig_Environment $env)
{ {
if ($node instanceof Twig_Node_Module) { if ($node instanceof Twig_Node_Module) {
if ($env->hasExtension('escaper') && $defaultStrategy = $env->getExtension('escaper')->getDefaultStrategy($node->getAttribute('filename'))) { if ($env->hasExtension('Twig_Extension_Escaper') && $defaultStrategy = $env->getExtension('Twig_Extension_Escaper')->getDefaultStrategy($node->getAttribute('filename'))) {
$this->defaultStrategy = $defaultStrategy; $this->defaultStrategy = $defaultStrategy;
} }
$this->safeVars = array(); $this->safeVars = array();
+2 -2
View File
@@ -56,7 +56,7 @@ class Twig_NodeVisitor_Optimizer extends Twig_BaseNodeVisitor
$this->enterOptimizeFor($node, $env); $this->enterOptimizeFor($node, $env);
} }
if (PHP_VERSION_ID < 50400 && self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('sandbox')) { if (PHP_VERSION_ID < 50400 && self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('Twig_Extension_Sandbox')) {
if ($this->inABody) { if ($this->inABody) {
if (!$node instanceof Twig_Node_Expression) { if (!$node instanceof Twig_Node_Expression) {
if (get_class($node) !== 'Twig_Node') { if (get_class($node) !== 'Twig_Node') {
@@ -90,7 +90,7 @@ class Twig_NodeVisitor_Optimizer extends Twig_BaseNodeVisitor
$node = $this->optimizePrintNode($node, $env); $node = $this->optimizePrintNode($node, $env);
if (self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('sandbox')) { if (self::OPTIMIZE_VAR_ACCESS === (self::OPTIMIZE_VAR_ACCESS & $this->optimizers) && !$env->isStrictVariables() && !$env->hasExtension('Twig_Extension_Sandbox')) {
if ($node instanceof Twig_Node_Body) { if ($node instanceof Twig_Node_Body) {
$this->inABody = false; $this->inABody = false;
} elseif ($this->inABody) { } elseif ($this->inABody) {
+4 -4
View File
@@ -527,8 +527,8 @@ abstract class Twig_Template implements Twig_TemplateInterface
return true; return true;
} }
if ($this->env->hasExtension('sandbox')) { if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
$this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item); $this->env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object, $item);
} }
return $object->$item; return $object->$item;
@@ -586,8 +586,8 @@ abstract class Twig_Template implements Twig_TemplateInterface
return true; return true;
} }
if ($this->env->hasExtension('sandbox')) { if ($this->env->hasExtension('Twig_Extension_Sandbox')) {
$this->env->getExtension('sandbox')->checkMethodAllowed($object, $method); $this->env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object, $method);
} }
// Some objects throw exceptions when they have __call, and the method we try // Some objects throw exceptions when they have __call, and the method we try
+1 -1
View File
@@ -35,6 +35,6 @@ class Twig_Test_Method extends Twig_Test
public function compile() public function compile()
{ {
return sprintf('$this->env->getExtension(\'%s\')->%s', $this->extension->getName(), $this->method); return sprintf('$this->env->getExtension(\'%s\')->%s', get_class($this->extension), $this->method);
} }
} }
+29 -25
View File
@@ -250,6 +250,17 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase
$twig->loadTemplate($templateName); $twig->loadTemplate($templateName);
} }
public function testHasGetExtensionByClassName()
{
$twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock());
$twig->addExtension($ext = new Twig_Tests_EnvironmentTest_Extension());
$this->assertTrue($twig->hasExtension('Twig_Tests_EnvironmentTest_Extension'));
$this->assertTrue($twig->hasExtension('\Twig_Tests_EnvironmentTest_Extension'));
$this->assertSame($ext, $twig->getExtension('Twig_Tests_EnvironmentTest_Extension'));
$this->assertSame($ext, $twig->getExtension('\Twig_Tests_EnvironmentTest_Extension'));
}
public function testAddExtension() public function testAddExtension()
{ {
$twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock());
@@ -286,7 +297,7 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase
$this->assertArrayHasKey('foo_global', $twig->getGlobals()); $this->assertArrayHasKey('foo_global', $twig->getGlobals());
$this->assertCount(1, $this->deprecations); $this->assertCount(1, $this->deprecations);
$this->assertContains('Defining the getGlobals() method in the "environment_test" extension ', $this->deprecations[0]); $this->assertContains('Defining the getGlobals() method in the "Twig_Tests_EnvironmentTest_Extension_WithGlobals" extension ', $this->deprecations[0]);
restore_error_handler(); restore_error_handler();
} }
@@ -297,7 +308,7 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase
public function testRemoveExtension() public function testRemoveExtension()
{ {
$twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock());
$twig->addExtension(new Twig_Tests_EnvironmentTest_Extension()); $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName());
$twig->removeExtension('environment_test'); $twig->removeExtension('environment_test');
$this->assertFalse(array_key_exists('test', $twig->getTags())); $this->assertFalse(array_key_exists('test', $twig->getTags()));
@@ -312,17 +323,22 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase
public function testAddMockExtension() public function testAddMockExtension()
{ {
$extension = $this->getMockBuilder('Twig_ExtensionInterface')->getMock(); // should be replaced by the following in 2.0 (this current code is just to avoid a dep notice)
$extension->expects($this->once()) // $extension = $this->getMockBuilder('Twig_Extension')->getMock();
->method('getName') $extension = eval(<<<EOF
->will($this->returnValue('mock')); class Twig_Tests_EnvironmentTest_ExtensionInEval extends Twig_Extension
{
}
EOF
);
$extension = new Twig_Tests_EnvironmentTest_ExtensionInEval();
$loader = new Twig_Loader_Array(array('page' => 'hey')); $loader = new Twig_Loader_Array(array('page' => 'hey'));
$twig = new Twig_Environment($loader); $twig = new Twig_Environment($loader);
$twig->addExtension($extension); $twig->addExtension($extension);
$this->assertInstanceOf('Twig_ExtensionInterface', $twig->getExtension('mock')); $this->assertInstanceOf('Twig_ExtensionInterface', $twig->getExtension(get_class($extension)));
$this->assertTrue($twig->isTemplateFresh('page', time())); $this->assertTrue($twig->isTemplateFresh('page', time()));
} }
@@ -348,7 +364,7 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase
$twig->initRuntime(); $twig->initRuntime();
$this->assertCount(1, $this->deprecations); $this->assertCount(1, $this->deprecations);
$this->assertContains('Defining the initRuntime() method in the "with_deprecation" extension is deprecated since version 1.23.', $this->deprecations[0]); $this->assertContains('Defining the initRuntime() method in the "Twig_Tests_EnvironmentTest_ExtensionWithDeprecationInitRuntime" extension is deprecated since version 1.23.', $this->deprecations[0]);
restore_error_handler(); restore_error_handler();
} }
@@ -371,8 +387,8 @@ class Twig_Tests_EnvironmentTest extends PHPUnit_Framework_TestCase
$this->deprecations = array(); $this->deprecations = array();
set_error_handler(array($this, 'handleError')); set_error_handler(array($this, 'handleError'));
$twig->addExtension(new Twig_Tests_EnvironmentTest_Extension()); $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName());
$twig->addExtension(new Twig_Tests_EnvironmentTest_Extension()); $twig->addExtension(new Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName());
$this->assertCount(1, $this->deprecations); $this->assertCount(1, $this->deprecations);
$this->assertContains('The possibility to register the same extension twice', $this->deprecations[0]); $this->assertContains('The possibility to register the same extension twice', $this->deprecations[0]);
@@ -404,11 +420,6 @@ class Twig_Tests_EnvironmentTest_Extension_WithGlobals extends Twig_Extension
'foo_global' => 'foo_global', 'foo_global' => 'foo_global',
); );
} }
public function getName()
{
return 'environment_test';
}
} }
class Twig_Tests_EnvironmentTest_Extension extends Twig_Extension implements Twig_Extension_GlobalsInterface class Twig_Tests_EnvironmentTest_Extension extends Twig_Extension implements Twig_Extension_GlobalsInterface
@@ -462,7 +473,10 @@ class Twig_Tests_EnvironmentTest_Extension extends Twig_Extension implements Twi
'foo_global' => 'foo_global', 'foo_global' => 'foo_global',
); );
} }
}
class Twig_Tests_EnvironmentTest_Extension_WithDeprecatedName extends Twig_Extension
{
public function getName() public function getName()
{ {
return 'environment_test'; return 'environment_test';
@@ -504,11 +518,6 @@ class Twig_Tests_EnvironmentTest_ExtensionWithDeprecationInitRuntime extends Twi
public function initRuntime(Twig_Environment $env) public function initRuntime(Twig_Environment $env)
{ {
} }
public function getName()
{
return 'with_deprecation';
}
} }
class Twig_Tests_EnvironmentTest_ExtensionWithoutDeprecationInitRuntime extends Twig_Extension implements Twig_Extension_InitRuntimeInterface class Twig_Tests_EnvironmentTest_ExtensionWithoutDeprecationInitRuntime extends Twig_Extension implements Twig_Extension_InitRuntimeInterface
@@ -516,9 +525,4 @@ class Twig_Tests_EnvironmentTest_ExtensionWithoutDeprecationInitRuntime extends
public function initRuntime(Twig_Environment $env) public function initRuntime(Twig_Environment $env)
{ {
} }
public function getName()
{
return 'without_deprecation';
}
} }
+1 -1
View File
@@ -118,7 +118,7 @@ class Twig_Tests_Extension_CoreTest extends PHPUnit_Framework_TestCase
public function testCustomEscaper() public function testCustomEscaper()
{ {
$twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock()); $twig = new Twig_Environment($this->getMockBuilder('Twig_LoaderInterface')->getMock());
$twig->getExtension('core')->setEscaper('foo', 'foo_escaper_for_test'); $twig->getExtension('Twig_Extension_Core')->setEscaper('foo', 'foo_escaper_for_test');
$this->assertEquals('fooUTF-8', twig_escape_filter($twig, 'foo', 'foo')); $this->assertEquals('fooUTF-8', twig_escape_filter($twig, 'foo', 'foo'));
$this->assertEquals('UTF-8', twig_escape_filter($twig, null, 'foo')); $this->assertEquals('UTF-8', twig_escape_filter($twig, null, 'foo'));
@@ -5,7 +5,7 @@
{{ date1|date('d/m/Y') }} {{ date1|date('d/m/Y') }}
--DATA-- --DATA--
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
$twig->getExtension('core')->setDateFormat('Y-m-d', '%d days %h hours'); $twig->getExtension('Twig_Extension_Core')->setDateFormat('Y-m-d', '%d days %h hours');
return array( return array(
'date1' => mktime(13, 45, 0, 10, 4, 2010), 'date1' => mktime(13, 45, 0, 10, 4, 2010),
) )
@@ -7,7 +7,7 @@ version_compare(phpversion(), '5.3.0', '>=')
{{ date2|date('%d days') }} {{ date2|date('%d days') }}
--DATA-- --DATA--
date_default_timezone_set('UTC'); date_default_timezone_set('UTC');
$twig->getExtension('core')->setDateFormat('Y-m-d', '%d days %h hours'); $twig->getExtension('Twig_Extension_Core')->setDateFormat('Y-m-d', '%d days %h hours');
return array( return array(
'date2' => new DateInterval('P2D'), 'date2' => new DateInterval('P2D'),
) )
@@ -9,7 +9,7 @@
{{ 1020.25|number_format(2, ',') }} {{ 1020.25|number_format(2, ',') }}
{{ 1020.25|number_format(2, ',', '.') }} {{ 1020.25|number_format(2, ',', '.') }}
--DATA-- --DATA--
$twig->getExtension('core')->setNumberFormat(2, '!', '='); $twig->getExtension('Twig_Extension_Core')->setNumberFormat(2, '!', '=');
return array(); return array();
--EXPECT-- --EXPECT--
20!00 20!00
-5
View File
@@ -230,9 +230,4 @@ class TwigTestExtension extends Twig_Extension
{ {
return false !== strpos($value, ' '); return false !== strpos($value, ' ');
} }
public function getName()
{
return 'integration_test';
}
} }
+1 -1
View File
@@ -28,7 +28,7 @@ class Twig_Tests_Node_SandboxTest extends Twig_Test_NodeTestCase
$tests[] = array($node, <<<EOF $tests[] = array($node, <<<EOF
// line 1 // line 1
\$sandbox = \$this->env->getExtension('sandbox'); \$sandbox = \$this->env->getExtension('Twig_Extension_Sandbox');
if (!\$alreadySandboxed = \$sandbox->isSandboxed()) { if (!\$alreadySandboxed = \$sandbox->isSandboxed()) {
\$sandbox->enableSandbox(); \$sandbox->enableSandbox();
} }
+1 -1
View File
@@ -24,7 +24,7 @@ class Twig_Tests_Node_SandboxedPrintTest extends Twig_Test_NodeTestCase
$tests[] = array(new Twig_Node_SandboxedPrint(new Twig_Node_Expression_Constant('foo', 1), 1), <<<EOF $tests[] = array(new Twig_Node_SandboxedPrint(new Twig_Node_Expression_Constant('foo', 1), 1), <<<EOF
// line 1 // line 1
echo \$this->env->getExtension('sandbox')->ensureToStringAllowed("foo"); echo \$this->env->getExtension('Twig_Extension_Sandbox')->ensureToStringAllowed("foo");
EOF EOF
); );