brick / money

A money and currency library for PHP
MIT License
1.61k stars 96 forks source link

json serialization #65

Closed gmhafiz closed 1 year ago

gmhafiz commented 1 year ago

Using laravel, it can automatically serialize array or object into json. For example

class IndexController extends Controller
{
  public function index()
  {
    return ['amount' => 0.1, 'currency' => 'AUD'];
  }
}

becomes

{"amount":0.1,"currency":"AUD"}

However, if laravel is returning brick/money, it returns an empty object:

class IndexController extends Controller
{
  public function index()
  {
    return new Money::of(0.1,'AUD');
  }
}

becomes

{}

How do you make it to serialize into {"amount":0.1,"currency":"AUD"} response instead?

Other way I can think of is to implement JsonSerializable and implement jsonSerialize() function:

final class Money extends AbstractMoney implements JsonSerializable
{
    ...

    public function jsonSerialize(): array
    {
        return [
            'amount' => $this->getAmount()->toFloat(),
            'currency' => $this->getCurrency()->getCurrencyCode(),
        ];
    }
}

As for test:

public function testJSONSerialize(): void
{
    $money = Money::of('5.50', 'USD');
    $got = $money->jsonSerialize();

    $expected = [
        'amount' => 5.50,
        'currency' => 'USD'
    ];

    $this->assertEquals($expected, $got);
}

Also it needed ext-json in composer

"require": {
    "ext-json": "*"
},
gmhafiz commented 1 year ago

I realize there is a PR https://github.com/brick/money/pull/52 which will allow ourselves to implement JsonSerializable interface.

Let me know if you want to have a built-in jsonSerialize() or just let the library user to implement this ourselves. If this ever gets implemented, need to let library users to know that it is a breaking change.

BenMorel commented 1 year ago

Hi, thanks for the feature request.

JsonSerializable support has been added in version 0.7.0!