Skip to content

Commit

Permalink
Merge pull request #26 from FranMoraton/obtainFirstItem
Browse files Browse the repository at this point in the history
Obtain collection first item
  • Loading branch information
calmohallag authored May 26, 2021
2 parents f2bbe03 + c0413d4 commit 3b33b54
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/Domain/Model/ValueObject/CollectionValueObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ public function filter(callable $func)

public function map(callable $func): CollectionValueObject
{
return new self(\array_map($func, $this->items));
return new static(\array_map($func, $this->items));
}

public function reduce(callable $func, $initial)
Expand Down Expand Up @@ -104,4 +104,9 @@ protected function removeItem($item): self
static fn ($current) => $current !== $item,
);
}

public function first()
{
return $this->items[array_key_first($this->items)] ?? null;
}
}
40 changes: 40 additions & 0 deletions tests/Domain/Model/ValueObject/CollectionValueObjectTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,44 @@ public function given_collection_when_ask_to_remove_item_then_return_new_collect
$this->assertEquals([1, 2, 3, 4], $collection->jsonSerialize());
$this->assertEquals([1, 2, 4], $newCollection->jsonSerialize());
}

/**
* @test
*/
public function given_an_empty_collection_when_ask_to_obtain_first_item_then_return_null()
{
$collection = CollectionValueObjectTested::from([]);
$item = $collection->firstItem();

$this->assertEquals(null, $item);
}

/**
* @test
*/
public function given_a_hash_map_collection_when_ask_to_obtain_first_item_then_return_first_item()
{
$firstItem = 1;
$collection = CollectionValueObjectTested::from(['a' => $firstItem, 'b' => 2, 'c' => 3, 'd' => 4]);
$item = $collection->firstItem();

$this->assertEquals(['a' => $firstItem, 'b' => 2, 'c' => 3, 'd' => 4], $collection->jsonSerialize());
$this->assertEquals($firstItem, $item);
}

/**
* @test
*/
public function given_a_collection_when_ask_to_obtain_first_item_then_return_first_item()
{
$firstItem = 1;
$collection = CollectionValueObjectTested::from([$firstItem, 2, 3, 4]);
$item = $collection->firstItem();

$this->assertEquals([$firstItem, 2, 3, 4], $collection->jsonSerialize());
$this->assertEquals($firstItem, $item);
$this->assertNotEquals(2, $item);
$this->assertNotEquals(3, $item);
$this->assertNotEquals(4, $item);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,9 @@ public function remove($item)
{
return $this->removeItem($item);
}

public function firstItem()
{
return $this->first();
}
}

0 comments on commit 3b33b54

Please sign in to comment.