Skip to content

Latest commit

 

History

History
115 lines (78 loc) · 2.15 KB

README.md

File metadata and controls

115 lines (78 loc) · 2.15 KB

Nette Clock

Orisai Clock and Symfony Clock integration for Nette

PSR-20 compatible

Content

Setup

Install with Composer

composer require orisai/nette-clock

Register DI extension

extensions:
    orisai.clock: OriNette\Clock\DI\ClockExtension

Current time

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();
	}

}

Sleep

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);

Shortcut function

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();

Tests

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'))

Clocks

Clock implementations and their usage are described by orisai/clock package.

Compatibility

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.