Skip to content

Commit e9edabf

Browse files
committed
handle null or empty cases better
1 parent 49dfd19 commit e9edabf

File tree

3 files changed

+47
-3
lines changed

3 files changed

+47
-3
lines changed

Makefile

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
ci-php80:
2-
./vendor/bin/phpcs --standard=PSR2 src/ tests/
32
./vendor/bin/phpunit --testsuite php80
3+
./vendor/bin/phpcs --standard=PSR2 src/ tests/
44
vendor/bin/phpstan analyse src tests --level 5 -c phpstan.php80.neon
55

66
ci-php81:
7-
./vendor/bin/phpcs --standard=PSR2 src/ tests/
87
./vendor/bin/phpunit --testsuite php81
8+
./vendor/bin/phpcs --standard=PSR2 src/ tests/
99
vendor/bin/phpstan analyse src tests --level 5 -c phpstan.neon

src/Integrations/Laravel/JsonCaster.php

+5-1
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,15 @@ public function __construct(
1313

1414
public function get($model, $key, $value, $attributes)
1515
{
16+
if ($value === null || $value === '') {
17+
return $value;
18+
}
19+
1620
return $this->target::fromJsonString($value);
1721
}
1822

1923
public function set($model, $key, $value, $attributes)
2024
{
21-
return $value->toJson();
25+
return $value?->toJson();
2226
}
2327
}

tests/Integrations/Laravel/LaravelCastTest.php

+40
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,44 @@ public function testCasts()
4242
$this->assertEquals(Address::class, get_class($oaddr));
4343
$this->assertEquals($addr, $oaddr->toJson());
4444
}
45+
46+
public function testNullCase()
47+
{
48+
(new FirstModel([
49+
'name' => 'jane',
50+
'castable_address' => null,
51+
'address' => null,
52+
]))->save();
53+
$m = FirstModel::query()->first();
54+
$this->assertTrue(null === $m->getAttributes()['castable_address']);
55+
$this->assertTrue(null === $m->castable_address);
56+
$this->assertTrue(null === $m->getAttributes()['address']);
57+
$this->assertTrue(null === $m->address);
58+
}
59+
60+
public function testNotSet()
61+
{
62+
(new FirstModel([
63+
'name' => 'jane',
64+
]))->save();
65+
$m = FirstModel::query()->first();
66+
$this->assertTrue(null === $m->getAttributes()['castable_address']);
67+
$this->assertTrue(null === $m->castable_address);
68+
$this->assertTrue(null === $m->getAttributes()['address']);
69+
$this->assertTrue(null === $m->address);
70+
}
71+
72+
public function testEmptyString()
73+
{
74+
FirstModel::query()->insert([
75+
'name' => 'jane',
76+
'castable_address' => '',
77+
'address' => '',
78+
]);
79+
$m = FirstModel::query()->first();
80+
$this->assertTrue('' === $m->getAttributes()['castable_address']);
81+
$this->assertTrue('' === $m->castable_address);
82+
$this->assertTrue('' === $m->getAttributes()['address']);
83+
$this->assertTrue('' === $m->address);
84+
}
4585
}

0 commit comments

Comments
 (0)