Skip to content

Commit 0c67af5

Browse files
authored
Merge pull request #55 from keithbrink/patch/carbon-objects
Fix serialization of carbon objects
2 parents 944c564 + 15f4e3d commit 0c67af5

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

composer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
"php": "^7.3|^8.0"
2222
},
2323
"require-dev": {
24+
"nesbot/carbon": "^2.61",
2425
"pestphp/pest": "^1.21.3",
2526
"phpstan/phpstan": "^1.8.2",
2627
"symfony/var-dumper": "^5.4.11"

src/Serializers/Native.php

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
namespace Laravel\SerializableClosure\Serializers;
44

55
use Closure;
6+
use DateTimeInterface;
67
use Laravel\SerializableClosure\Contracts\Serializable;
78
use Laravel\SerializableClosure\SerializableClosure;
89
use Laravel\SerializableClosure\Support\ClosureScope;
@@ -460,6 +461,12 @@ protected function mapByReference(&$data)
460461

461462
$instance = $data;
462463

464+
if ($data instanceof DateTimeInterface) {
465+
$this->scope[$instance] = $data;
466+
467+
return;
468+
}
469+
463470
if ($data instanceof UnitEnum) {
464471
$this->scope[$instance] = $data;
465472

tests/SerializerTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,32 @@ function () {
401401
expect($f(new Model))->toBeInstanceOf(Model::class);
402402
})->with('serializers');
403403

404+
test('serializes carbon objects', function () {
405+
$carbon = new \Carbon\Carbon('now');
406+
407+
$closure = function () use ($carbon) {
408+
return $carbon;
409+
};
410+
411+
$u = s($closure);
412+
$r = $u();
413+
414+
expect($r)->toEqual($carbon);
415+
})->with('serializers');
416+
417+
test('serializes carbon immutable objects', function () {
418+
$carbon = new \Carbon\CarbonImmutable('now');
419+
420+
$closure = function () use ($carbon) {
421+
return $carbon;
422+
};
423+
424+
$u = s($closure);
425+
$r = $u();
426+
427+
expect($r)->toEqual($carbon);
428+
})->with('serializers');
429+
404430
class A
405431
{
406432
protected static function aStaticProtected()

0 commit comments

Comments
 (0)