DateTimeImmutable.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php declare(strict_types=1);
  2. /*
  3. * This file is part of the Monolog package.
  4. *
  5. * (c) Jordi Boggiano <j.boggiano@seld.be>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Monolog;
  11. /**
  12. * Overrides default json encoding of date time objects
  13. *
  14. * @author Menno Holtkamp
  15. * @author Jordi Boggiano <j.boggiano@seld.be>
  16. */
  17. class DateTimeImmutable extends \DateTimeImmutable implements \JsonSerializable
  18. {
  19. private $useMicroseconds;
  20. public function __construct($useMicroseconds, \DateTimeZone $timezone = null)
  21. {
  22. $date = 'now';
  23. if ($useMicroseconds) {
  24. // Circumvent DateTimeImmutable::createFromFormat() which always returns \DateTimeImmutable instead of `static`
  25. // @link https://bugs.php.net/bug.php?id=60302
  26. $timestamp = microtime(true);
  27. $microseconds = sprintf("%06d", ($timestamp - floor($timestamp)) * 1000000);
  28. $date = date('Y-m-d H:i:s.' . $microseconds, (int) $timestamp);
  29. }
  30. parent::__construct($date, $timezone);
  31. $this->useMicroseconds = $useMicroseconds;
  32. }
  33. public function jsonSerialize(): string
  34. {
  35. if ($this->useMicroseconds) {
  36. return $this->format('Y-m-d\TH:i:s.uP');
  37. }
  38. return $this->format('Y-m-d\TH:i:sP');
  39. }
  40. public function __toString(): string
  41. {
  42. return $this->jsonSerialize();
  43. }
  44. }