diff --git a/Changelog.md b/Changelog.md index b0613ae..1ce3f17 100644 --- a/Changelog.md +++ b/Changelog.md @@ -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 diff --git a/Dto/DetailedAmount.php b/Dto/DetailedAmount.php index 3285d23..c28e2d0 100644 --- a/Dto/DetailedAmount.php +++ b/Dto/DetailedAmount.php @@ -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(); @@ -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[] = [ diff --git a/Tests/DetailedAmountTest.php b/Tests/DetailedAmountTest.php index 53c44ce..4d02ab3 100644 --- a/Tests/DetailedAmountTest.php +++ b/Tests/DetailedAmountTest.php @@ -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')); + } }