Orisai Clock and Symfony Clock integration for Nette
PSR-20 compatible
Install with Composer
composer require orisai/nette-clock
Register DI extension
extensions:
orisai.clock: OriNette\Clock\DI\ClockExtension
Request Clock
interface and get current time from clock (or Psr\Clock\ClockInterface
for psr/clock
compatibility)
use Orisai\Clock\Clock;
class ExampleService
{
private Clock $clock;
public function __construct(Clock $clock)
{
$this->clock = $clock;
}
public function doSomething(): void
{
$currentTime = $this->clock->now();
}
}
To prevent waiting periods in tests, replace calls to sleep()
and usleep()
functions with Clock->sleep()
method.
$clock->sleep(
1, // Seconds
2, // Milliseconds
3, // Microseconds
);
Or with named arguments, just:
$clock->sleep(microseconds: 10);
Get current time statically
use function Orisai\Clock\now;
$currentTime = now(); // \DateTimeImmutable
It is also possible to access clock statically
use Orisai\Clock\ClockHolder;
$clock = ClockHolder::getClock();
Configure clock to return exact time for testing
services:
# Set timestamp
orisai.clock.clock: Orisai\Clock\FrozenClock(978307200)
# Or a date time instance
orisai.clock.clock: Orisai\Clock\FrozenClock(\DateTimeImmutable('now'))
Clock
implementations and their usage are described by orisai/clock package.
In case symfony/clock
is installed, the extension automatically:
- registers adapter which makes
Symfony\Component\Clock\ClockInterface
available via DIC - sets clock to static class
Symfony\Component\Clock\Clock
during DIC startup.