Skip to content

Commit b0a2117

Browse files
committed
Added NULL/empty value casting
1 parent 572642d commit b0a2117

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Casts/TimezonedDatetime.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ public function __construct(?string $format = null)
3737
*/
3838
public function get($model, $key, $value, $attributes)
3939
{
40+
if(! $value) {
41+
return null;
42+
}
43+
4044
$original = Timezone::store($value, fn($raw, $tz) => $this->asDateTime($raw, $tz, $model));
4145

4246
return Timezone::date($original);
@@ -53,6 +57,10 @@ public function get($model, $key, $value, $attributes)
5357
*/
5458
public function set($model, $key, $value, $attributes)
5559
{
60+
if(! $value) {
61+
return null;
62+
}
63+
5664
$requested = Timezone::date($value, fn($raw, $tz) => $this->asDateTime($raw, $tz, $model));
5765

5866
return Timezone::store($requested)->format($this->format ?? $model->getDateFormat());

tests/CastTest.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,30 @@
2828
expect($output->format('Y-m-d H:i:s'))->toBe('2022-12-15 10:00:00');
2929
});
3030

31+
it('can access NULL date as NULL', function() {
32+
setupFacade();
33+
34+
$cast = new TimezonedDatetime();
35+
36+
$input = null;
37+
38+
$output = $cast->get(fakeModel(), 'id', $input, []);
39+
40+
expect($output)->toBeNull();
41+
});
42+
43+
it('can access empty string as NULL', function() {
44+
setupFacade();
45+
46+
$cast = new TimezonedDatetime();
47+
48+
$input = '';
49+
50+
$output = $cast->get(fakeModel(), 'id', $input, []);
51+
52+
expect($output)->toBeNull();
53+
});
54+
3155
it('can mutate application timezone datetime string to UTC database date string', function() {
3256
setupFacade();
3357

@@ -74,4 +98,28 @@
7498
$output = $cast->set(fakeModel(), 'id', $input, []);
7599

76100
expect($output)->toBe('2022-12-15 09:00:00');
101+
});
102+
103+
it('can mutate NULL as NULL', function() {
104+
setupFacade();
105+
106+
$cast = new TimezonedDatetime();
107+
108+
$input = null;
109+
110+
$output = $cast->set(fakeModel(), 'id', $input, []);
111+
112+
expect($output)->toBeNull();
113+
});
114+
115+
it('can mutate empty string as NULL', function() {
116+
setupFacade();
117+
118+
$cast = new TimezonedDatetime();
119+
120+
$input = '';
121+
122+
$output = $cast->set(fakeModel(), 'id', $input, []);
123+
124+
expect($output)->toBeNull();
77125
});

0 commit comments

Comments
 (0)