| 1 |
<?php |
| 2 |
|
| 3 |
namespace React\Http\Io; |
| 4 |
|
| 5 |
use React\EventLoop\LoopInterface; |
| 6 |
|
| 7 |
/** |
| 8 |
* [internal] Clock source that returns current timestamp and memoize clock for same tick |
| 9 |
* |
| 10 |
* This is mostly used as an internal optimization to avoid unneeded syscalls to |
| 11 |
* get the current system time multiple times within the same loop tick. For the |
| 12 |
* purpose of the HTTP server, the clock is assumed to not change to a |
| 13 |
* significant degree within the same loop tick. If you need a high precision |
| 14 |
* clock source, you may want to use `\hrtime()` instead (PHP 7.3+). |
| 15 |
* |
| 16 |
* The API is modelled to resemble the PSR-20 `ClockInterface` (in draft at the |
| 17 |
* time of writing this), but uses a `float` return value for performance |
| 18 |
* reasons instead. |
| 19 |
* |
| 20 |
* Note that this is an internal class only and nothing you should usually care |
| 21 |
* about for outside use. |
| 22 |
* |
| 23 |
* @internal |
| 24 |
*/ |
| 25 |
class Clock |
| 26 |
{ |
| 27 |
/** @var LoopInterface $loop */ |
| 28 |
private $loop; |
| 29 |
|
| 30 |
/** @var ?float */ |
| 31 |
private $now; |
| 32 |
|
| 33 |
public function __construct(LoopInterface $loop) |
| 34 |
{ |
| 35 |
$this->loop = $loop; |
| 36 |
} |
| 37 |
|
| 38 |
/** @return float */ |
| 39 |
public function now() |
| 40 |
{ |
| 41 |
if ($this->now === null) { |
| 42 |
$this->now = \microtime(true); |
| 43 |
|
| 44 |
// remember clock for current loop tick only and update on next tick |
| 45 |
$now =& $this->now; |
| 46 |
$this->loop->futureTick(function () use (&$now) { |
| 47 |
assert($now !== null); |
| 48 |
$now = null; |
| 49 |
}); |
| 50 |
} |
| 51 |
|
| 52 |
return $this->now; |
| 53 |
} |
| 54 |
} |