Skip to content

Commit

Permalink
Support creating collections using Collection::mapFrom()
Browse files Browse the repository at this point in the history
  • Loading branch information
benr77 committed Jan 7, 2024
1 parent 034154b commit 3d18080
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ Change Log
- Added helper methods `Collection::isEmpty()` and `Collection::isNotEmpty()`.
- Added `Collection::reverse()` helper to reverse the order of the collection.
- Support creating collections from Doctrine Collections using `Collection::fromDoctrine()`.
- Support creating collections by mapping array of other objects using `Collection::mapFrom()`.

# 0.2.0
- Minimum PHP version bumped to 8.1.
Expand Down
12 changes: 12 additions & 0 deletions src/AbstractImmutableCollection.php
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,18 @@ public static function fromDoctrine(DoctrineCollection $items): static
return new $class($items->toArray());
}

/**
* @param array<mixed> $items
*/
public static function mapFrom(array $items, callable $mapper): static
{
$class = static::class;

return new $class(
array_map($mapper, $items)
);
}

public static function empty(): static
{
$class = static::class;
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/ImmutableCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,19 @@ public function test_can_create_collection_from_doctrine_collection(): void
$this->assertEquals($collectionItem2, $sut->lastOrFail());
}

public function test_can_create_collection_by_mapping_array_of_other_objects(): void
{
$collectionItem1 = new CompanionObject('one');
$collectionItem2 = new CompanionObject('two');

$sut = DummyImmutableCollection::mapFrom(
[$collectionItem1, $collectionItem2],
fn (CompanionObject $companionObject): DummyCollectionItem => new DummyCollectionItem($collectionItem2->name)
);

$this->assertEquals(2, $sut->count());
}

public function test_is_empty_check_is_correct(): void
{
$sut = DummyImmutableCollection::empty();
Expand Down

0 comments on commit 3d18080

Please sign in to comment.