| 1 |
<?php |
| 2 |
namespace Wikimedia\Telemetry; |
| 3 |
|
| 4 |
use Wikimedia\Assert\Assert; |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
class Clock { |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
private static ?int $mockTime = null; |
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 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 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
public function getCurrentNanoTime(): int { |
| 38 |
$this->referenceTime ??= (int)( 1e9 * microtime( true ) ) - hrtime( true ); |
| 39 |
return self::$mockTime ?? ( $this->referenceTime + hrtime( true ) ); |
| 40 |
} |
| 41 |
|
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
public static function setMockTime( ?int $epochNanos ): void { |
| 50 |
Assert::precondition( defined( 'MW_PHPUNIT_TEST' ), 'This method should only be used in tests' ); |
| 51 |
self::$mockTime = $epochNanos; |
| 52 |
} |
| 53 |
} |