diff --git a/src/Fields/Value.php b/src/Fields/Value.php index d4a95503d4..b7823890f6 100644 --- a/src/Fields/Value.php +++ b/src/Fields/Value.php @@ -12,6 +12,7 @@ use Statamic\Facades\Compare; use Statamic\Support\Str; use Statamic\View\Antlers\Language\Parser\DocumentTransformer; +use Traversable; class Value implements ArrayAccess, IteratorAggregate, JsonSerializable { @@ -96,10 +97,6 @@ private function iteratorValue() $value = $value->get(); } - if ($value instanceof Collection) { - $value = $value->all(); - } - return $value; } @@ -127,7 +124,9 @@ public function jsonSerialize($options = 0) #[\ReturnTypeWillChange] public function getIterator() { - return new ArrayIterator($this->iteratorValue()); + $value = $this->iteratorValue(); + + return $value instanceof Traversable ? $value : new ArrayIterator($value); } public function shouldParseAntlers() diff --git a/tests/Fields/ValueTest.php b/tests/Fields/ValueTest.php index bd88402554..6ec9af7566 100644 --- a/tests/Fields/ValueTest.php +++ b/tests/Fields/ValueTest.php @@ -8,6 +8,7 @@ use Statamic\Fields\Field; use Statamic\Fields\Fieldtype; use Statamic\Fields\Value; +use Statamic\Fields\Values; use Statamic\Query\Builder; use Tests\TestCase; @@ -301,6 +302,26 @@ public function it_can_iterate_over_query_builder() ], $arr); } + #[Test] + public function it_can_iterate_over_values() + { + $val = new Value(new Values([ + 'a' => 'alfa', + 'b' => 'bravo', + ])); + + $arr = []; + + foreach ($val as $key => $value) { + $arr[$key] = $value; + } + + $this->assertEquals([ + 'a' => 'alfa', + 'b' => 'bravo', + ], $arr); + } + #[Test] public function it_can_proxy_methods_to_value() { diff --git a/tests/Tags/IterateTest.php b/tests/Tags/IterateTest.php new file mode 100644 index 0000000000..227cafda86 --- /dev/null +++ b/tests/Tags/IterateTest.php @@ -0,0 +1,51 @@ +{{ /foreach:fieldname }}'; + + $this->assertSame('', $this->tag($template, ['fieldname' => $value])); + } + + public static function iterateProvider() + { + return [ + 'array' => [ + ['alfa' => 'one', 'bravo' => 'two'], + ], + 'collection' => [ + collect(['alfa' => 'one', 'bravo' => 'two']), + ], + 'values' => [ + new Values(['alfa' => 'one', 'bravo' => 'two']), + ], + 'value with array' => [ + new Value(['alfa' => 'one', 'bravo' => 'two']), + ], + 'value with collection' => [ + new Value(collect(['alfa' => 'one', 'bravo' => 'two'])), + ], + 'value with values' => [ + new Value(new Values(['alfa' => 'one', 'bravo' => 'two'])), + ], + ]; + } + + private function tag($tag, $context = []) + { + return (string) Parse::template($tag, $context); + } +}