From 46a83e1af0e6a8aa0f5d0fccb79c8ee877cab4d8 Mon Sep 17 00:00:00 2001 From: Toon Van den Bos Date: Wed, 26 Jun 2024 18:41:02 +0200 Subject: [PATCH] Fixed serialization when working with RationalMoney --- src/Price.php | 15 ++++++++++++--- tests/Unit/SerializesToJsonTest.php | 15 ++++++++++++++- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/src/Price.php b/src/Price.php index 1916992..2c5e2aa 100644 --- a/src/Price.php +++ b/src/Price.php @@ -238,17 +238,26 @@ public function jsonSerialize(): array $incl = $this->inclusive(); return [ - 'base' => $this->base->toRational()->getAmount(), + 'base' => $this->getRational($this->base)->getAmount(), 'currency' => $this->base->getCurrency()->getCurrencyCode(), 'units' => $this->units, 'vat' => $this->vat->percentage(), 'total' => [ - 'exclusive' => $excl->toRational()->getAmount(), - 'inclusive' => $incl->toRational()->getAmount(), + 'exclusive' => $this->getRational($excl)->getAmount(), + 'inclusive' => $this->getRational($incl)->getAmount(), ], ]; } + protected function getRational(AbstractMoney $money): RationalMoney + { + if(is_a($money, RationalMoney::class)) { + return $money; + } + + return $money->toRational(); + } + /** * Hydrate a price object from a json string/array * @throws \InvalidArgumentException diff --git a/tests/Unit/SerializesToJsonTest.php b/tests/Unit/SerializesToJsonTest.php index 7e42e3d..3ae81a3 100644 --- a/tests/Unit/SerializesToJsonTest.php +++ b/tests/Unit/SerializesToJsonTest.php @@ -22,7 +22,7 @@ expect($data['total']['inclusive'] ?? null)->toBe('1661/100'); }); -it('hydrates instance from JSON string', function() { +it('hydrates Money instance from JSON string', function() { $price = Price::ofMinor(500, 'EUR') ->setUnits(3) ->setVat(10.75); @@ -35,6 +35,19 @@ expect($instance->vat()->percentage())->toBe(10.75); }); +it('hydrates RationalMoney instance from JSON string', function() { + $price = (new Price(Money::ofMinor(500, 'EUR')->toRational())) + ->setUnits(3) + ->setVat(10.75); + + $instance = Price::json(json_encode($price)); + + expect($instance)->toBeInstanceOf(Price::class); + expect($instance->getAmount()->compareTo($price->base()->getAmount()))->toBe(0); + expect($instance->units())->toBe(floatval(3)); + expect($instance->vat()->percentage())->toBe(10.75); +}); + it('hydrates instance from JSON array', function() { $data = [ 'base' => '500',