Skip to content

Commit 6c129ea

Browse files
committed
Fix cast nullable column to money
1 parent 5a526f1 commit 6c129ea

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

src/Casts/MoneyCast.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,30 @@
33
namespace PostScripton\Money\Casts;
44

55
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
6+
use PostScripton\Money\Money;
67

78
class MoneyCast implements CastsAttributes
89
{
910
public function get($model, string $key, $value, array $attributes)
1011
{
12+
if (is_null($value)) {
13+
return null;
14+
}
15+
1116
return money($value);
1217
}
1318

1419
public function set($model, string $key, $value, array $attributes)
1520
{
21+
if (is_null($value)) {
22+
return null;
23+
}
24+
25+
$isMonetary = gettype($value) === 'object' && $value instanceof Money;
26+
if (! $isMonetary) {
27+
$value = money($value);
28+
}
29+
1630
return $value->upload();
1731
}
1832
}

tests/Unit/MoneyCastTest.php

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
<?php
2+
3+
namespace PostScripton\Money\Tests\Unit;
4+
5+
use Illuminate\Database\Eloquent\Model;
6+
use PostScripton\Money\Casts\MoneyCast;
7+
use PostScripton\Money\Money;
8+
use PostScripton\Money\Tests\TestCase;
9+
10+
class MoneyCastTest extends TestCase
11+
{
12+
public function testGet(): void
13+
{
14+
$product1 = $this->getTestingModel();
15+
$product2 = $this->getTestingModel();
16+
$product2->price = money('12345');
17+
18+
$this->assertNull($product1->price);
19+
$this->assertInstanceOf(Money::class, $product2->price);
20+
$this->assertEquals('$ 1 234.5', $product2->price->toString());
21+
}
22+
23+
public function testSet(): void
24+
{
25+
$product1 = $this->getTestingModel();
26+
$product1->price = money('12345');
27+
$product2 = $this->getTestingModel();
28+
$product2->price = '12345';
29+
$product3 = $this->getTestingModel();
30+
$product3->price = 12345;
31+
$product4 = $this->getTestingModel();
32+
$product4->price = null;
33+
$expectedMoneyString = '$ 1 234.5';
34+
35+
$this->assertInstanceOf(Money::class, $product1->price);
36+
$this->assertEquals($expectedMoneyString, $product1->price->toString());
37+
$this->assertInstanceOf(Money::class, $product2->price);
38+
$this->assertEquals($expectedMoneyString, $product2->price->toString());
39+
$this->assertInstanceOf(Money::class, $product3->price);
40+
$this->assertEquals($expectedMoneyString, $product3->price->toString());
41+
$this->assertNull($product4->price);
42+
}
43+
44+
private function getTestingModel(): Model
45+
{
46+
return new class extends Model {
47+
protected $fillable = [
48+
'price',
49+
];
50+
51+
protected $casts = [
52+
'price' => MoneyCast::class,
53+
];
54+
};
55+
}
56+
}

0 commit comments

Comments
 (0)