Skip to content

Commit

Permalink
global carbon serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed Aug 24, 2017
1 parent ca0adb0 commit 6a18209
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
39 changes: 38 additions & 1 deletion src/Illuminate/Support/Carbon.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,47 @@

namespace Illuminate\Support;

use JsonSerializable;
use Carbon\Carbon as BaseCarbon;
use Illuminate\Support\Traits\Macroable;

class Carbon extends BaseCarbon
class Carbon extends BaseCarbon implements JsonSerializable
{
use Macroable;

/**
* The custom Carbon JSON serializer.
*
* @var callable|null
*/
protected static $serializer;

/**
* Prepare the object for JSON serialization.
*
* @return array|string
*/
public function jsonSerialize()
{
if (static::$serializer) {
return call_user_func(static::$serializer, $this);
}

$carbon = $this;

return call_user_func(function () use ($carbon) {
return get_object_vars($carbon);
});
}

/**
* JSON serialize all Carbon instances using the given callback.
*
* @param callable $callback
* @return void
*/
public static function serializeUsing($callback)
{
static::$serializer = $callback;
}
}
15 changes: 15 additions & 0 deletions tests/Support/SupportCarbonTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,4 +56,19 @@ public function testCarbonRaisesExceptionWhenMacroIsNotFound()
{
Carbon::now()->nonExistingMacro();
}

public function testCarbonAllowsCustomSerializer()
{
Carbon::serializeUsing(function ($carbon) {
return $carbon->getTimestamp();
});

$carbon = Carbon::now();

$result = json_decode(json_encode(['carbon' => $carbon]), true);

$this->assertTrue(is_numeric($result['carbon']));

Carbon::serializeUsing(null);
}
}

0 comments on commit 6a18209

Please sign in to comment.