Skip to content

Commit

Permalink
[Clock] Add Clock::now(), get() and with()
Browse files Browse the repository at this point in the history
  • Loading branch information
nicolas-grekas committed Dec 15, 2022
1 parent bd6219d commit 6ef4125
Show file tree
Hide file tree
Showing 3 changed files with 90 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()`, `Clock::get()` and `Clock::with()`

6.2
---
Expand Down
58 changes: 58 additions & 0 deletions src/Symfony/Component/Clock/Clock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
<?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;

use Psr\Clock\ClockInterface;

/**
* A global clock.
*
* Note that you should prefer injecting a ClockInterface or using
* ClockAwareTrait when possible instead of using this class.
*
* Defined as enum to be final and non-instantiable.
*/
enum Clock
{
public static function now(): \DateTimeImmutable
{
return self::get()->now();
}

public static function with(ClockInterface $clock, callable $callback, mixed ...$arguments): mixed
{
$prevClock = self::get($clock);

try {
return $callback(...$arguments);
} finally {
self::get($prevClock);
}
}

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

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

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

return $prevClock;
}
}
31 changes: 31 additions & 0 deletions src/Symfony/Component/Clock/Tests/ClockTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?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());
$this->assertInstanceOf(NativeClock::class, Clock::get());

$clock = new MockClock();

$this->assertSame([123, $clock], Clock::with($clock, fn ($arg) => [$arg, Clock::get()], 123));
$this->assertInstanceOf(NativeClock::class, Clock::get());
}
}

0 comments on commit 6ef4125

Please sign in to comment.