Skip to content

Commit

Permalink
Add timezone parameter to ChronosClock
Browse files Browse the repository at this point in the history
  • Loading branch information
odan authored and odan committed Oct 24, 2023
1 parent ac94c9c commit e3c3f6e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/ChronosClock.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,33 @@
*/

use DateTimeImmutable;
use DateTimeZone;
use Psr\Clock\ClockInterface;

/**
* PSR-20 Clock implementation.
*/
class ChronosClock implements ClockInterface
{
private DateTimeZone|string|null $timezone;

/**
* Constructor.
*
* @param DateTimeZone|string|null $timezone

Check failure on line 32 in src/ChronosClock.php

View workflow job for this annotation

GitHub Actions / cs-stan / Coding Standard & Static Analysis

Class name \DateTimeZone in @param should be referenced via a fully qualified name.
*/
public function __construct(DateTimeZone|string|null $timezone = null)
{
$this->timezone = $timezone;
}

/**
* Returns the current time as a Chronos Object
*
* @return \Cake\Chronos\Chronos The current time
*/
public function now(): DateTimeImmutable
{
return Chronos::now();
return Chronos::now($this->timezone);
}
}
16 changes: 16 additions & 0 deletions tests/TestCase/ChronosClockTest.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<?php

declare(strict_types=1);

Check failure on line 3 in tests/TestCase/ChronosClockTest.php

View workflow job for this annotation

GitHub Actions / cs-stan / Coding Standard & Static Analysis

Expected 0 lines before declare statement, found 1.

/**
Expand All @@ -17,6 +18,7 @@
use Cake\Chronos\Chronos;
use Cake\Chronos\ChronosClock;
use DateTimeImmutable;
use DateTimeZone;

class ChronosClockTest extends TestCase
{
Expand All @@ -31,4 +33,18 @@ public function testNow(): void
$this->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());
}
}

0 comments on commit e3c3f6e

Please sign in to comment.