Skip to content

Commit 4c7e519

Browse files
xurshudyanXurshudyantaylorotwell
authored
[12.x] Make Fluent class iterable (#56218)
* Allow iteration over Fluent * Add test * Update Fluent.php --------- Co-authored-by: Xurshudyan <[email protected]> Co-authored-by: Taylor Otwell <[email protected]>
1 parent d6ecb78 commit 4c7e519

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

src/Illuminate/Support/Fluent.php

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,15 @@
33
namespace Illuminate\Support;
44

55
use ArrayAccess;
6+
use ArrayIterator;
67
use Illuminate\Contracts\Support\Arrayable;
78
use Illuminate\Contracts\Support\Jsonable;
89
use Illuminate\Support\Traits\Conditionable;
910
use Illuminate\Support\Traits\InteractsWithData;
1011
use Illuminate\Support\Traits\Macroable;
12+
use IteratorAggregate;
1113
use JsonSerializable;
14+
use Traversable;
1215

1316
/**
1417
* @template TKey of array-key
@@ -17,7 +20,7 @@
1720
* @implements \Illuminate\Contracts\Support\Arrayable<TKey, TValue>
1821
* @implements \ArrayAccess<TKey, TValue>
1922
*/
20-
class Fluent implements Arrayable, ArrayAccess, Jsonable, JsonSerializable
23+
class Fluent implements Arrayable, ArrayAccess, IteratorAggregate, Jsonable, JsonSerializable
2124
{
2225
use Conditionable, InteractsWithData, Macroable {
2326
__call as macroCall;
@@ -245,6 +248,16 @@ public function offsetUnset($offset): void
245248
unset($this->attributes[$offset]);
246249
}
247250

251+
/**
252+
* Get an iterator for the attributes.
253+
*
254+
* @return ArrayIterator<TKey, TValue>
255+
*/
256+
public function getIterator(): Traversable
257+
{
258+
return new ArrayIterator($this->attributes);
259+
}
260+
248261
/**
249262
* Handle dynamic calls to the fluent instance to set attributes.
250263
*

tests/Support/SupportFluentTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -452,6 +452,25 @@ public function testMacroable()
452452
'baz' => 'zal',
453453
], $fluent->foo()->all());
454454
}
455+
456+
public function testFluentIsIterable()
457+
{
458+
$fluent = new Fluent([
459+
'name' => 'Taylor',
460+
'role' => 'admin',
461+
]);
462+
463+
$result = [];
464+
465+
foreach ($fluent as $key => $value) {
466+
$result[$key] = $value;
467+
}
468+
469+
$this->assertSame([
470+
'name' => 'Taylor',
471+
'role' => 'admin',
472+
], $result);
473+
}
455474
}
456475

457476
class FluentArrayIteratorStub implements IteratorAggregate

0 commit comments

Comments
 (0)