From e3c3f6e694894ebd012662028010935c24746537 Mon Sep 17 00:00:00 2001 From: odan Date: Tue, 24 Oct 2023 10:28:56 +0200 Subject: [PATCH] Add timezone parameter to ChronosClock --- src/ChronosClock.php | 15 ++++++++++++++- tests/TestCase/ChronosClockTest.php | 16 ++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/src/ChronosClock.php b/src/ChronosClock.php index 87ffaaf..0bfd627 100644 --- a/src/ChronosClock.php +++ b/src/ChronosClock.php @@ -16,6 +16,7 @@ */ use DateTimeImmutable; +use DateTimeZone; use Psr\Clock\ClockInterface; /** @@ -23,6 +24,18 @@ */ class ChronosClock implements ClockInterface { + private DateTimeZone|string|null $timezone; + + /** + * Constructor. + * + * @param DateTimeZone|string|null $timezone + */ + public function __construct(DateTimeZone|string|null $timezone = null) + { + $this->timezone = $timezone; + } + /** * Returns the current time as a Chronos Object * @@ -30,6 +43,6 @@ class ChronosClock implements ClockInterface */ public function now(): DateTimeImmutable { - return Chronos::now(); + return Chronos::now($this->timezone); } } diff --git a/tests/TestCase/ChronosClockTest.php b/tests/TestCase/ChronosClockTest.php index 9b48e17..db16cc8 100644 --- a/tests/TestCase/ChronosClockTest.php +++ b/tests/TestCase/ChronosClockTest.php @@ -1,4 +1,5 @@ assertInstanceOf(Chronos::class, $now); $this->assertSame('2001-01-31', $now->toDateString()); } + + public function testConstructWithTimezone(): void + { + Chronos::setTestNow('2024-01-31 12:13:14.123456'); + + $londonTimezone = new DateTimeZone('Europe/London'); + $clock = new ChronosClock($londonTimezone); + $now = $clock->now(); + + $this->assertInstanceOf(DateTimeImmutable::class, $now); + $this->assertInstanceOf(Chronos::class, $now); + $this->assertSame('2024-01-31', $now->toDateString()); + $this->assertSame('Europe/London', $now->getTimezone()->getName()); + } }