Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 10 additions & 6 deletions src/Money.php
Original file line number Diff line number Diff line change
Expand Up @@ -680,14 +680,18 @@ public function convertedTo(
* Note that NumberFormatter internally represents values using floating point arithmetic,
* so discrepancies can appear when formatting very large monetary values.
*
* @param NumberFormatter $formatter The formatter to format with.
* @param NumberFormatter|MoneyFormatter $formatter The formatter to format with.
*/
public function formatWith(NumberFormatter $formatter): string
public function formatWith(NumberFormatter|MoneyFormatter $formatter): string
{
return $formatter->formatCurrency(
$this->amount->toFloat(),
$this->currency->getCurrencyCode(),
);
if ($formatter instanceof NumberFormatter) {
return $formatter->formatCurrency(
$this->amount->toFloat(),
$this->currency->getCurrencyCode(),
);
}

return $formatter->format($this);
}

/**
Expand Down
10 changes: 10 additions & 0 deletions src/MoneyFormatter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

declare(strict_types=1);

namespace Brick\Money;

interface MoneyFormatter
{
public function format(Money $money): string;
}
29 changes: 29 additions & 0 deletions tests/MoneyTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use Brick\Money\Currency;
use Brick\Money\Exception\MoneyMismatchException;
use Brick\Money\Money;
use Brick\Money\MoneyFormatter;
use Generator;
use InvalidArgumentException;
use NumberFormatter;
Expand Down Expand Up @@ -834,6 +835,34 @@ public static function providerFormatWith(): array
];
}

/**
* @param array $money The money to test.
* @param MoneyFormatter $formatter The money formatter to test.
* @param string $expected The expected output.
*/
#[RequiresPhpExtension('intl')]
#[DataProvider('providerFormatWithMoneyFormatter')]
public function testFormatWithMoneyFormatter(array $money, MoneyFormatter $formatter, string $expected): void
{
$actual = Money::of(...$money)->formatWith($formatter);
self::assertSame($expected, $actual);
}

public static function providerFormatWithMoneyFormatter(): array
{
$formatter = (new class() implements MoneyFormatter {
public function format(Money $money): string
{
return $money->getAmount()->toScale(2) . ' ' . $money->getCurrency()->__toString();
}
});

return [
[['1.23', 'USD'], $formatter, '1.23 USD'],
[['1.7', 'EUR'], $formatter, '1.70 EUR'],
];
}

/**
* @param array $money The money to test.
* @param string $locale The target locale.
Expand Down