Skip to content

Commit

Permalink
feat: improved TypeMoney with import/export from/to JSON
Browse files Browse the repository at this point in the history
  • Loading branch information
Alcides Ramos committed May 20, 2024
1 parent 91fda48 commit b7bd2e7
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/TypeMoney.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
42 changes: 42 additions & 0 deletions tests/Unit/TypeMoneyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, array<int, mixed>>
*/
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<string, array<int, mixed>>
*/
public static function dataProviderForFromJson(): array
{
return [
'Positive' => ['[123.45,"EUR"]', TypeMoney::set(123.45, 'EUR')],
'Negative' => ['[-123.45,"USD"]', TypeMoney::set(-123.45, 'USD')],
];
}
}

0 comments on commit b7bd2e7

Please sign in to comment.