Skip to content

Commit

Permalink
Currency should be JSON serializable (#79)
Browse files Browse the repository at this point in the history
  • Loading branch information
joelvh committed Sep 23, 2023
1 parent 14ed55e commit 833b8ac
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/AbstractMoney.php
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,7 @@ final public function jsonSerialize(): array
{
return [
'amount' => (string) $this->getAmount(),
'currency' => (string) $this->getCurrency()
'currency' => $this->getCurrency()->jsonSerialize()
];
}
}
8 changes: 7 additions & 1 deletion src/Currency.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
namespace Brick\Money;

use Brick\Money\Exception\UnknownCurrencyException;
use JsonSerializable;
use Stringable;

/**
* A currency. This class is immutable.
*/
final class Currency implements Stringable
final class Currency implements Stringable, JsonSerializable
{
/**
* The currency code.
Expand Down Expand Up @@ -166,6 +167,11 @@ public function is(Currency|string|int $currency) : bool
|| ($this->numericCode !== 0 && $this->numericCode === (int) $currency);
}

final public function jsonSerialize(): string
{
return $this->currencyCode;
}

/**
* Returns the currency code.
*/
Expand Down
16 changes: 16 additions & 0 deletions tests/CurrencyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,4 +123,20 @@ public function testIs() : void
self::assertNotSame($currency, $clone);
self::assertTrue($clone->is($currency));
}

/**
* @dataProvider providerJsonSerialize
*/
public function testJsonSerialize(Currency $currency, string $expected): void
{
self::assertSame($expected, $currency->jsonSerialize());
self::assertSame(json_encode($expected), json_encode($currency));
}

public function providerJsonSerialize(): array
{
return [
[Currency::of('USD'), 'USD']
];
}
}

0 comments on commit 833b8ac

Please sign in to comment.