Skip to content

Commit c012dfa

Browse files
committed
add recursiveToArray macro
1 parent 8c9d2e6 commit c012dfa

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed

src/Macros/RecursiveToArray.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
<?php
2+
3+
namespace Pulli\CollectionMacros\Macros;
4+
5+
use Illuminate\Support\Collection;
6+
7+
class RecursiveToArray
8+
{
9+
public function __invoke(): \Closure
10+
{
11+
return function(array $ary): array {
12+
return Collection::mapToCollection($ary, true)->toArray();
13+
};
14+
}
15+
}

src/register.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
use Illuminate\Support\Collection;
44

55
$macros = [
6-
'mapToCollection' => \Pulli\CollectionMacros\Macros\MapToCollection::class
6+
'mapToCollection' => \Pulli\CollectionMacros\Macros\MapToCollection::class,
7+
'recursiveToArray' => \Pulli\CollectionMacros\Macros\RecursiveToArray::class,
78
];
89

910
if (!function_exists('app')) {
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<?php
2+
3+
use Illuminate\Support\Collection;
4+
use Pulli\CollectionMacros\Test\Data\ChildObject;
5+
use Pulli\CollectionMacros\Test\Data\OtherObject;
6+
use Pulli\CollectionMacros\Test\Data\ParentObject;
7+
8+
describe('recursiveToArray macro', function () {
9+
it('wraps nested collection and objects into array', function () {
10+
$data = Collection::recursiveToArray([
11+
new ParentObject(
12+
name: 'parent1',
13+
children: Collection::make([new ChildObject(name: 'child1')]),
14+
other: Collection::make([new OtherObject(value: 'other1')]),
15+
),
16+
new ParentObject(
17+
name: 'parent2',
18+
children: Collection::make([new ChildObject(name: 'child2')]),
19+
other: Collection::make([new OtherObject(value: 'other2')]),
20+
),
21+
], true);
22+
23+
expect($data)->toEqual([
24+
[
25+
'name' => 'parent1',
26+
'children' => [
27+
['name' => 'child1'],
28+
],
29+
'other' => [
30+
['value' => 'other1'],
31+
],
32+
],
33+
[
34+
'name' => 'parent2',
35+
'children' => [
36+
['name' => 'child2'],
37+
],
38+
'other' => [
39+
['value' => 'other2'],
40+
],
41+
],
42+
]);
43+
});
44+
});

0 commit comments

Comments
 (0)