JsonSerializationTest.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of the Carbon package.
  5. *
  6. * (c) Brian Nesbitt <brian@nesbot.com>
  7. *
  8. * For the full copyright and license information, please view the LICENSE
  9. * file that was distributed with this source code.
  10. */
  11. namespace Tests\Carbon;
  12. use Carbon\Carbon;
  13. use Tests\AbstractTestCaseWithOldNow;
  14. class JsonSerializationTest extends AbstractTestCaseWithOldNow
  15. {
  16. public function testCarbonAllowsCustomSerializer()
  17. {
  18. Carbon::serializeUsing(function (Carbon $carbon) {
  19. return $carbon->getTimestamp();
  20. });
  21. $result = json_decode(json_encode(Carbon::now()), true);
  22. $this->assertSame(1498569255, $result);
  23. }
  24. public function testCarbonAllowsCustomSerializerString()
  25. {
  26. Carbon::serializeUsing('Y-m-d');
  27. $this->assertSame('"2017-06-27"', json_encode(Carbon::now()));
  28. }
  29. public function testCarbonAllowsCustomSerializerViaSettings()
  30. {
  31. $date = Carbon::now()->settings([
  32. 'toJsonFormat' => 'H:i:s',
  33. ]);
  34. $this->assertSame('"13:14:15"', json_encode($date));
  35. }
  36. public function testCarbonCanSerializeToJson()
  37. {
  38. $this->assertSame('2017-06-27T13:14:15.000000Z', Carbon::now()->jsonSerialize());
  39. }
  40. }