From: Tobias Schultze Date: Wed, 31 Oct 2012 16:11:57 +0000 (+0100) Subject: improved error message for non-existent or invalid attributes X-Git-Url: http://git.silmor.de/gitweb/?a=commitdiff_plain;h=6fb5afa28f28189e054420eac31e7ae8f3d20871;p=konrad%2Ftwig.git improved error message for non-existent or invalid attributes --- diff --git a/lib/Twig/Template.php b/lib/Twig/Template.php index 95e0819..9d60833 100644 --- a/lib/Twig/Template.php +++ b/lib/Twig/Template.php @@ -336,10 +336,10 @@ abstract class Twig_Template implements Twig_TemplateInterface */ protected function getAttribute($object, $item, array $arguments = array(), $type = Twig_TemplateInterface::ANY_CALL, $isDefinedTest = false, $ignoreStrictCheck = false) { + $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item; + // array if (Twig_TemplateInterface::METHOD_CALL !== $type) { - $arrayItem = is_bool($item) || is_float($item) ? (int) $item : $item; - if ((is_array($object) && array_key_exists($arrayItem, $object)) || ($object instanceof ArrayAccess && isset($object[$arrayItem])) ) { @@ -378,7 +378,13 @@ abstract class Twig_Template implements Twig_TemplateInterface return null; } - throw new Twig_Error_Runtime(sprintf('Item "%s" for "%s" does not exist', $item, is_array($object) ? 'Array' : $object), -1, $this->getTemplateName()); + if (Twig_TemplateInterface::METHOD_CALL === $type) { + throw new Twig_Error_Runtime(sprintf('Impossible to invoke a method ("%s") on a "%s" variable', $item, gettype($object)), -1, $this->getTemplateName()); + } elseif (is_array($object)) { + throw new Twig_Error_Runtime(sprintf('Key "%s" for array with keys "%s" does not exist', $arrayItem, implode(', ', array_keys($object))), -1, $this->getTemplateName()); + } else { + throw new Twig_Error_Runtime(sprintf('Impossible to access an item ("%s") on a "%s" variable', $item, gettype($object)), -1, $this->getTemplateName()); + } } $class = get_class($object); diff --git a/test/Twig/Tests/TemplateTest.php b/test/Twig/Tests/TemplateTest.php index 014e036..636ae60 100644 --- a/test/Twig/Tests/TemplateTest.php +++ b/test/Twig/Tests/TemplateTest.php @@ -301,9 +301,9 @@ class Twig_Tests_TemplateTest extends PHPUnit_Framework_TestCase // tests when input is not an array or object $tests = array_merge($tests, array( - array(false, null, 42, 'a', array(), $anyType, false, 'Item "a" for "42" does not exist'), - array(false, null, "string", 'a', array(), $anyType, false, 'Item "a" for "string" does not exist'), - array(false, null, array(), 'a', array(), $anyType, false, 'Item "a" for "Array" does not exist'), + array(false, null, 42, 'a', array(), $anyType, false, 'Impossible to access an item ("a") on a "integer" variable'), + array(false, null, "string", 'a', array(), $anyType, false, 'Impossible to access an item ("a") on a "string" variable'), + array(false, null, array(), 'a', array(), $anyType, false, 'Key "a" for array with keys "" does not exist'), )); // add twig_template_get_attributes tests