Debian Codegraph @

includes/libs/telemetry/Clock.php

raw symbols SCIP
1 <?php
2 namespace Wikimedia\Telemetry;
3
4 use Wikimedia\Assert\Assert;
5
6 /**
7 * A click providing the current time in nanoseconds, backed by {@link hrtime}.
8 *
9 * @since 1.43
10 * @internal
11 */
12 class Clock {
13 /**
14 * Timestamp to return in place of the current time, or `null` to use the current time.
15 * @var int|null
16 */
17 private static ?int $mockTime = null;
18
19 /**
20 * The reference UNIX timestamp in nanoseconds which hrtime() offsets should be added to
21 * to derive an absolute timestamp.
22 * @var int|null
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 * Get the current time, represented as the number of nanoseconds since the UNIX epoch.
35 * @return int
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 * Set a mock time to override the timestamp returned by {@link Clock::getCurrentNanoTime()}.
44 * Useful for testing.
45 *
46 * @param int|null $epochNanos The override timestamp, or `null` to return to using the current time.
47 * @return void
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 }