Skip to content

Commit

Permalink
Added the fromKeyValuePairs static factory and getDetail() method…
Browse files Browse the repository at this point in the history
…s to the DetailedAmount Dto class
  • Loading branch information
fulopattila122 committed Mar 26, 2023
1 parent 5b22bc5 commit 3527b89
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

## 3.x Series

## Unreleased
##### 2023-XX-YY

- Added the `fromKeyValuePairs` static factory and `getDetail()` methods to the DetailedAmount Dto class

## 3.6.1
##### 2023-03-09

Expand Down
21 changes: 21 additions & 0 deletions Dto/DetailedAmount.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,16 @@ public static function fromArray(array $details): self
return $instance;
}

public static function fromKeyValuePairs(array $details): self
{
$mapped = [];
foreach ($details as $title => $amount) {
$mapped[] = ['title' => $title, 'amount' => $amount];
}

return self::fromArray($mapped);
}

public function toArray()
{
return $this->getDetails();
Expand All @@ -75,6 +85,17 @@ public function getDetails(): array
return $this->details;
}

public function getDetail(string $title): float|int|null
{
foreach ($this->details as $detail) {
if ($detail['title'] === $title) {
return $detail['amount'];
}
}

return null;
}

public function addDetail(string $title, float $value, bool $recalculate = true): self
{
$this->details[] = [
Expand Down
27 changes: 27 additions & 0 deletions Tests/DetailedAmountTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -115,4 +115,31 @@ public function it_throws_an_error_if_the_title_is_missing_from_one_of_the_passe
['amount' => 0],
]);
}

/** @test */
public function it_can_be_created_from_key_value_pairs()
{
$amount = DetailedAmount::fromKeyValuePairs(['gst' => 5, 'pst' => 9, 'hst' => 0]);

$this->assertInstanceOf(DetailedAmount::class, $amount);
$this->assertCount(3, $amount->getDetails());
}

/** @test */
public function individual_details_can_be_retrieved_by_title()
{
$amount = DetailedAmount::fromKeyValuePairs(['gst' => 5, 'pst' => 9, 'hst' => 10]);

$this->assertEquals(5, $amount->getDetail('gst'));
$this->assertEquals(9, $amount->getDetail('pst'));
$this->assertEquals(10, $amount->getDetail('hst'));
}

/** @test */
public function an_unknown_detail_returns_null()
{
$amount = DetailedAmount::fromKeyValuePairs(['gst' => 5, 'pst' => 9, 'hst' => 10]);

$this->assertNull($amount->getDetail('hahaha'));
}
}

0 comments on commit 3527b89

Please sign in to comment.