Skip to content

Commit

Permalink
[Clock] Add Clock::now()
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Dec 14, 2022
1 parent bd6219d commit e2e654f
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/Symfony/Component/Clock/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add `ClockAwareTrait` to help write time-sensitive classes
* Add `Clock::now()` and `Clock::get()`

6.2
---
Expand Down
42 changes: 42 additions & 0 deletions src/Symfony/Component/Clock/Clock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Clock;

/**
* A global clock.
*
* Defined as enum to be final and non-instantiable.
*/
enum Clock
{
public static function now(): \DateTimeImmutable
{
return self::get()->now();
}

/**
* Returns the current clock, or the previous one when passing a new clock as argument.
*/
public static function get(ClockInterface $newClock = null): ClockInterface
{
static $clock;

if (null === $newClock) {
return $clock ??= new NativeClock();
}

$previousClock = $clock ?? new NativeClock();
$clock = $newClock;

return $previousClock;
}
}
32 changes: 32 additions & 0 deletions src/Symfony/Component/Clock/Tests/ClockTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Clock\Tests;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Clock\Clock;
use Symfony\Component\Clock\MockClock;
use Symfony\Component\Clock\NativeClock;

class ClockTest extends TestCase
{
public function testClock()
{
$this->assertInstanceOf(\DateTimeImmutable::class, Clock::now());

$previousClock = Clock::get();
$this->assertInstanceOf(NativeClock::class, $previousClock);

$newClock = new MockClock();
$this->assertSame($previousClock, Clock::get($newClock));
$this->assertSame($newClock, Clock::get());
}
}

0 comments on commit e2e654f

Please sign in to comment.