MediaWiki master
Clock.php
Go to the documentation of this file.
1<?php
3
4use Wikimedia\Assert\Assert;
5
12class Clock {
17 private static ?int $mockTime = null;
18
24 private ?int $referenceTime = null;
25
26 public function __construct() {
27 Assert::precondition(
28 PHP_INT_SIZE >= 8,
29 'The Clock class requires 64-bit integers to support nanosecond timing'
30 );
31 }
32
36 public function getCurrentNanoTime(): int {
37 $this->referenceTime ??= (int)( 1e9 * microtime( true ) ) - hrtime( true );
38 return self::$mockTime ?? ( $this->referenceTime + hrtime( true ) );
39 }
40
48 public static function setMockTime( ?int $epochNanos ): void {
49 Assert::precondition( defined( 'MW_PHPUNIT_TEST' ), 'This method should only be used in tests' );
50 self::$mockTime = $epochNanos;
51 }
52}
A click providing the current time in nanoseconds, backed by hrtime.
Definition Clock.php:12
getCurrentNanoTime()
Get the current time, represented as the number of nanoseconds since the UNIX epoch.
Definition Clock.php:36
static setMockTime(?int $epochNanos)
Set a mock time to override the timestamp returned by Clock::getCurrentNanoTime().
Definition Clock.php:48