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',