Skip to content

Commit

Permalink
Fixed serialization when working with RationalMoney
Browse files Browse the repository at this point in the history
  • Loading branch information
toonvandenbos committed Jun 26, 2024
1 parent 58cfaac commit 46a83e1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
15 changes: 12 additions & 3 deletions src/Price.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion tests/Unit/SerializesToJsonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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',
Expand Down

0 comments on commit 46a83e1

Please sign in to comment.