money icon indicating copy to clipboard operation
money copied to clipboard

json serialization

Open gmhafiz opened this issue 3 years ago • 0 comments

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 avatar Sep 21 '22 04:09 gmhafiz