diff --git a/src/TextTemplate.php b/src/TextTemplate.php index 3568d66..0489a1f 100644 --- a/src/TextTemplate.php +++ b/src/TextTemplate.php @@ -302,15 +302,15 @@ private function _removeWhitespace ($input) { } - private function _getValueByName ($context, $name, $softFail) { + private function _getRawValueByName ($context, $name, $softFail) { $dd = explode (".", $name); $value = $context; $cur = ""; foreach ($dd as $cur) { if (is_numeric($cur)) $cur = (int)$cur; - if (is_array($value)) { - if ( ! array_key_exists($cur, $value)) { + if (is_array($value) || $value instanceof \ArrayAccess) { + if ( ! array_key_exists($cur, $value) && ! isset($value[$cur])) { if ( ! $softFail) { throw new UndefinedVariableException("ParsingError: Can't parse element: '{$name}' Error on subelement: '$cur'", $name); } @@ -338,6 +338,14 @@ private function _getValueByName ($context, $name, $softFail) { } } } + + return $value; + } + + + private function _getValueByName ($context, $name, $softFail) { + $value = $this->_getRawValueByName($context, $name, $softFail); + if (is_object($value) && ! method_exists($value, "__toString")) $value = "##ERR:OBJECT_IN_TEXT:[{$name}]ON[{$cur}]:" . gettype($value) . "###"; @@ -412,10 +420,10 @@ private function _runFor (&$context, $content, $cmdParam, $softFail) { $iterateOverName = $matches[2]; $localName = $matches[1]; - $repeatVal = $this->_getValueByName($context, $iterateOverName, $softFail); + $repeatVal = $this->_getRawValueByName($context, $iterateOverName, $softFail); - if ( ! is_array($repeatVal)) + if ( ! is_array($repeatVal) && ! $repeatVal instanceof \Traversable) return ""; $index = 0; $result = ""; @@ -806,4 +814,4 @@ public function apply ($params, $softFail=TRUE, &$context=[]) { return $result; } -} \ No newline at end of file +} diff --git a/test/unit/tpls/04_simple_for/_in.php b/test/unit/tpls/04_simple_for/_in.php index 3a5416e..84617dd 100644 --- a/test/unit/tpls/04_simple_for/_in.php +++ b/test/unit/tpls/04_simple_for/_in.php @@ -5,5 +5,8 @@ "arrVal1" => [ "a", "b", "c" ], + "traversableVal1" => new ArrayIterator([ + "x", "y", "z" + ]), "value1" => "Some Value", -]; \ No newline at end of file +]; diff --git a/test/unit/tpls/04_simple_for/_in.txt b/test/unit/tpls/04_simple_for/_in.txt index 6fc7acd..4d879f3 100644 --- a/test/unit/tpls/04_simple_for/_in.txt +++ b/test/unit/tpls/04_simple_for/_in.txt @@ -2,4 +2,7 @@ {for curVal in arrVal1} 2: curVal = {=curVal} {/for} -5: Some other text \ No newline at end of file +{for curVal in traversableVal1} +3: curVal = {=curVal} +{/for} +5: Some other text diff --git a/test/unit/tpls/04_simple_for/out.txt b/test/unit/tpls/04_simple_for/out.txt index 6ff7a5f..11ac831 100644 --- a/test/unit/tpls/04_simple_for/out.txt +++ b/test/unit/tpls/04_simple_for/out.txt @@ -2,4 +2,7 @@ 2: curVal = a 2: curVal = b 2: curVal = c -5: Some other text \ No newline at end of file +3: curVal = x +3: curVal = y +3: curVal = z +5: Some other text