lcobucci-clock-polyfill.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace Lcobucci\Clock;
  3. use DateTimeImmutable;
  4. use DateTimeZone;
  5. use function interface_exists;
  6. if (! interface_exists(Clock::class)) {
  7. interface Clock
  8. {
  9. /** @return DateTimeImmutable */
  10. public function now();
  11. }
  12. final class FrozenClock implements Clock
  13. {
  14. /** @var DateTimeImmutable */
  15. private $now;
  16. public function __construct(DateTimeImmutable $now)
  17. {
  18. $this->now = $now;
  19. }
  20. /** @return self */
  21. public static function fromUTC()
  22. {
  23. return new self(new DateTimeImmutable('now', new DateTimeZone('UTC')));
  24. }
  25. public function setTo(DateTimeImmutable $now)
  26. {
  27. $this->now = $now;
  28. }
  29. public function now()
  30. {
  31. return $this->now;
  32. }
  33. }
  34. final class SystemClock implements Clock
  35. {
  36. /** @var DateTimeZone */
  37. private $timezone;
  38. public function __construct(DateTimeZone $timezone)
  39. {
  40. $this->timezone = $timezone;
  41. }
  42. /** @return self */
  43. public static function fromUTC()
  44. {
  45. return new self(new DateTimeZone('UTC'));
  46. }
  47. /** @return self */
  48. public static function fromSystemTimezone()
  49. {
  50. return new self(new DateTimeZone(date_default_timezone_get()));
  51. }
  52. public function now()
  53. {
  54. return new DateTimeImmutable('now', $this->timezone);
  55. }
  56. }
  57. }