Skip to content

Commit 82d9651

Browse files
committed
Add format_money modifier
1 parent 5b3a9d7 commit 82d9651

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

src/Modifiers/FormatMoney.php

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
<?php
2+
3+
namespace DuncanMcClean\Cargo\Modifiers;
4+
5+
use DuncanMcClean\Cargo\Support\Money;
6+
use Statamic\Facades\Site;
7+
use Statamic\Modifiers\Modifier;
8+
9+
class FormatMoney extends Modifier
10+
{
11+
public function index($value, $params, $context)
12+
{
13+
if (! $value) {
14+
return $value;
15+
}
16+
17+
if (! is_numeric($value)) {
18+
throw new \Exception('The format_money modifier requires a numeric value.');
19+
}
20+
21+
return Money::format($value, Site::current());
22+
}
23+
}
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
<?php
2+
3+
namespace Tests\Modifiers;
4+
5+
use PHPUnit\Framework\Attributes\DataProvider;
6+
use PHPUnit\Framework\Attributes\Test;
7+
use Statamic\Modifiers\Modify;
8+
use Tests\TestCase;
9+
10+
class FormatMoneyTest extends TestCase
11+
{
12+
public static function amountProvider(): array
13+
{
14+
return [
15+
[null, null],
16+
['1599', '£15.99'],
17+
['15.99', '£15.99'],
18+
[1599, '£15.99'],
19+
[15.99, '£15.99'],
20+
];
21+
}
22+
23+
#[Test]
24+
#[DataProvider('amountProvider')]
25+
public function it_formats_money($input, $expected)
26+
{
27+
$this->assertEquals($expected, $this->modify($input));
28+
}
29+
30+
#[Test]
31+
public function exception_is_thrown_when_non_numeric_value_is_provided()
32+
{
33+
$this->expectException(\Exception::class);
34+
$this->expectExceptionMessage('The format_money modifier requires a numeric value.');
35+
36+
$this->modify('Hello World!');
37+
}
38+
39+
private function modify($value)
40+
{
41+
return Modify::value($value)->formatMoney()->fetch();
42+
}
43+
}

0 commit comments

Comments
 (0)