Skip to content

Commit

Permalink
add test for nested objects
Browse files Browse the repository at this point in the history
  • Loading branch information
the-pulli committed Sep 20, 2023
1 parent 21ea587 commit 8c9d2e6
Show file tree
Hide file tree
Showing 4 changed files with 97 additions and 0 deletions.
17 changes: 17 additions & 0 deletions tests/Data/ChildObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Pulli\CollectionMacros\Test\Data;

readonly class ChildObject
{
public function __construct(private string $name)
{
}

public function toArray(): array
{
return [
'name' => $this->name,
];
}
}
17 changes: 17 additions & 0 deletions tests/Data/OtherObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

namespace Pulli\CollectionMacros\Test\Data;

readonly class OtherObject
{
public function __construct(private string $value)
{
}

public function toArray(): array
{
return [
'value' => $this->value,
];
}
}
24 changes: 24 additions & 0 deletions tests/Data/ParentObject.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

namespace Pulli\CollectionMacros\Test\Data;

use Illuminate\Support\Collection;

readonly class ParentObject
{
public function __construct(
private string $name,
private Collection $children,
private Collection $other,
) {
}

public function toArray(): array
{
return [
'name' => $this->name,
'children' => $this->children->toArray(),
'other' => $this->other->toArray(),
];
}
}
39 changes: 39 additions & 0 deletions tests/Macros/MapToCollectionTest.php
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
<?php

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

describe('mapToCollection macro', function () {
Expand Down Expand Up @@ -55,4 +58,40 @@
'job' => 'Designer',
]));
});

it('wraps nested arrays and objects into collection objects', function () {
$data = Collection::mapToCollection([
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->toArray())->toEqual([
[
'name' => 'parent1',
'children' => [
['name' => 'child1'],
],
'other' => [
['value' => 'other1'],
],
],
[
'name' => 'parent2',
'children' => [
['name' => 'child2'],
],
'other' => [
['value' => 'other2'],
],
],
]);
});
});

0 comments on commit 8c9d2e6

Please sign in to comment.