Skip to content

Commit

Permalink
add recursiveToArray macro
Browse files Browse the repository at this point in the history
  • Loading branch information
the-pulli committed Sep 21, 2023
1 parent 8c9d2e6 commit c012dfa
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/Macros/RecursiveToArray.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<?php

namespace Pulli\CollectionMacros\Macros;

use Illuminate\Support\Collection;

class RecursiveToArray
{
public function __invoke(): \Closure
{
return function(array $ary): array {
return Collection::mapToCollection($ary, true)->toArray();
};
}
}
3 changes: 2 additions & 1 deletion src/register.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
use Illuminate\Support\Collection;

$macros = [
'mapToCollection' => \Pulli\CollectionMacros\Macros\MapToCollection::class
'mapToCollection' => \Pulli\CollectionMacros\Macros\MapToCollection::class,
'recursiveToArray' => \Pulli\CollectionMacros\Macros\RecursiveToArray::class,
];

if (!function_exists('app')) {
Expand Down
44 changes: 44 additions & 0 deletions tests/Macros/RecursiveToArrayTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

use Illuminate\Support\Collection;
use Pulli\CollectionMacros\Test\Data\ChildObject;
use Pulli\CollectionMacros\Test\Data\OtherObject;
use Pulli\CollectionMacros\Test\Data\ParentObject;

describe('recursiveToArray macro', function () {
it('wraps nested collection and objects into array', function () {
$data = Collection::recursiveToArray([
new ParentObject(
name: 'parent1',
children: Collection::make([new ChildObject(name: 'child1')]),
other: Collection::make([new OtherObject(value: 'other1')]),
),
new ParentObject(
name: 'parent2',
children: Collection::make([new ChildObject(name: 'child2')]),
other: Collection::make([new OtherObject(value: 'other2')]),
),
], true);

expect($data)->toEqual([
[
'name' => 'parent1',
'children' => [
['name' => 'child1'],
],
'other' => [
['value' => 'other1'],
],
],
[
'name' => 'parent2',
'children' => [
['name' => 'child2'],
],
'other' => [
['value' => 'other2'],
],
],
]);
});
});

0 comments on commit c012dfa

Please sign in to comment.