| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
if (!defined('ABSPATH')) { |
| 5 |
exit; |
| 6 |
} |
| 7 |
|
| 8 |
class ABJ_404_Solution_Timer { |
| 9 |
|
| 10 |
/** @var float */ |
| 11 |
private $start = 0; |
| 12 |
|
| 13 |
/** @var float */ |
| 14 |
private $stop = 0; |
| 15 |
|
| 16 |
/** @var float */ |
| 17 |
private $elapsed = 0; |
| 18 |
|
| 19 |
/** @var bool */ |
| 20 |
private $isRunning = false; |
| 21 |
|
| 22 |
/** @var callable */ |
| 23 |
private $currentTime; |
| 24 |
|
| 25 |
/** |
| 26 |
* @param callable|null $currentTime Optional clock returning the current time in seconds. |
| 27 |
*/ |
| 28 |
public function __construct(?callable $currentTime = null) { |
| 29 |
$this->currentTime = $currentTime ?: static function (): float { |
| 30 |
return abj_clock()->nowFloat(); |
| 31 |
}; |
| 32 |
$this->start(); |
| 33 |
} |
| 34 |
|
| 35 |
/** @return float */ |
| 36 |
private function now(): float { |
| 37 |
return (float) call_user_func($this->currentTime); |
| 38 |
} |
| 39 |
|
| 40 |
/** Also restart. |
| 41 |
* @return void |
| 42 |
*/ |
| 43 |
function start(): void { |
| 44 |
$this->start = $this->now(); |
| 45 |
$this->elapsed = 0; |
| 46 |
$this->isRunning = true; |
| 47 |
} |
| 48 |
|
| 49 |
/** @return float */ |
| 50 |
function stop(): float { |
| 51 |
$this->stop = $this->now(); |
| 52 |
$elapsedThisTime = $this->stop - $this->start; |
| 53 |
$this->elapsed += $elapsedThisTime; |
| 54 |
$this->isRunning = false; |
| 55 |
|
| 56 |
return $this->getElapsedTime(); |
| 57 |
} |
| 58 |
|
| 59 |
/** @return void */ |
| 60 |
function restartKeepElapsed(): void { |
| 61 |
$this->start = $this->now(); |
| 62 |
$this->isRunning = true; |
| 63 |
} |
| 64 |
|
| 65 |
/** |
| 66 |
* @return float in seconds |
| 67 |
*/ |
| 68 |
function getElapsedTime() { |
| 69 |
if ($this->isRunning) { |
| 70 |
return $this->now() - $this->start + $this->elapsed; |
| 71 |
} |
| 72 |
return $this->elapsed; |
| 73 |
} |
| 74 |
|
| 75 |
/** @return float */ |
| 76 |
function getStartTime(): float { |
| 77 |
return $this->start; |
| 78 |
} |
| 79 |
|
| 80 |
} |
| 81 |
|