From 6df989bafe63aa212ddd53117098587fef4951ca Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Mon, 14 Jan 2019 13:00:46 +0100 Subject: [PATCH] fix key exists check for non ArrayObject objects --- lib/Twig/Template.php | 4 +++- test/Twig/Tests/TemplateTest.php | 33 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/lib/Twig/Template.php b/lib/Twig/Template.php index 6032f5178..78a57383f 100644 --- a/lib/Twig/Template.php +++ b/lib/Twig/Template.php @@ -508,7 +508,9 @@ abstract class Twig_Template implements Twig_TemplateInterface if (self::METHOD_CALL !== $type) { $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item; - if ((is_array($object) || $object instanceof ArrayAccess) && (isset($object[$arrayItem]) || array_key_exists($arrayItem, $object))) { + if (((is_array($object) || $object instanceof ArrayObject) && (isset($object[$arrayItem]) || array_key_exists($arrayItem, $object))) + || ($object instanceof ArrayAccess && isset($object[$arrayItem])) + ) { if ($isDefinedTest) { return true; } diff --git a/test/Twig/Tests/TemplateTest.php b/test/Twig/Tests/TemplateTest.php index 439a9ea3a..782cdd32b 100644 --- a/test/Twig/Tests/TemplateTest.php +++ b/test/Twig/Tests/TemplateTest.php @@ -418,6 +418,11 @@ class Twig_Tests_TemplateTest extends \PHPUnit\Framework\TestCase [false, null, $methodAndPropObject, 'c', [], $arrayType], ]); + $arrayAccess = new Twig_TemplateArrayAccess(); + $tests = array_merge($tests, [ + [true, ['foo' => 'bar'], $arrayAccess, 'vars', [], $anyType], + ]); + // tests when input is not an array or object $tests = array_merge($tests, [ [false, null, 42, 'a', [], $anyType, 'Impossible to access an attribute ("a") on a integer variable ("42") in "index.twig".'], @@ -720,6 +725,34 @@ class Twig_TemplateMethodAndPropObject } } +class Twig_TemplateArrayAccess implements ArrayAccess +{ + public $vars = [ + 'foo' => 'bar', + ]; + private $children = []; + + public function offsetExists($offset) + { + return array_key_exists($offset, $this->children); + } + + public function offsetGet($offset) + { + return $this->children[$offset]; + } + + public function offsetSet($offset, $value) + { + $this->children[$offset] = $value; + } + + public function offsetUnset($offset) + { + unset($this->children[$offset]); + } +} + class Twig_TemplateMagicMethodObject { public function __call($method, $arguments)