diff --git a/src/TypeMoney.php b/src/TypeMoney.php index 680dca1..22c48a4 100644 --- a/src/TypeMoney.php +++ b/src/TypeMoney.php @@ -47,4 +47,18 @@ public function __invoke(): array { return [$this->amount, $this->currency]; } + + public function toJson(): string + { + return json_encode([ + ($this->amount)(), + $this->currency->value + ]); + } + + public static function fromJson(string $data): self + { + [$amount, $currency] = json_decode($data, true); + return self::set($amount, $currency); + } } diff --git a/tests/Unit/TypeMoneyTest.php b/tests/Unit/TypeMoneyTest.php index 4715de9..041075c 100644 --- a/tests/Unit/TypeMoneyTest.php +++ b/tests/Unit/TypeMoneyTest.php @@ -138,4 +138,46 @@ public static function dataProviderForIsNotEqualTo(): array ], ]; } + + // --------------------------------------------------------------------------------------------------------------- + + #[Test] + #[DataProvider('dataProviderForToJson')] + public function checkToJson(TypeMoney $a, string $expected): void + { + self::assertEquals($expected, $a->toJson()); + } + + /** + * @return array> + */ + public static function dataProviderForToJson(): array + { + return [ + 'Positive' => [TypeMoney::set(123.45, 'EUR'), '[123.45,"EUR"]'], + 'Negative' => [TypeMoney::set(-123.45, 'USD'), '[-123.45,"USD"]'], + ]; + } + + // --------------------------------------------------------------------------------------------------------------- + + #[Test] + #[DataProvider('dataProviderForFromJson')] + public function checkFromJson(string $data, TypeMoney $expected): void + { + $aux = TypeMoney::fromJson($data); + + self::assertTrue($aux->isEqualTo($expected)); + } + + /** + * @return array> + */ + public static function dataProviderForFromJson(): array + { + return [ + 'Positive' => ['[123.45,"EUR"]', TypeMoney::set(123.45, 'EUR')], + 'Negative' => ['[-123.45,"USD"]', TypeMoney::set(-123.45, 'USD')], + ]; + } }