|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace Smr; |
|
4
|
|
|
|
|
5
|
|
|
use Smr\Container\DiContainer; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Stores the current time as a fixed value. |
|
9
|
|
|
* This is useful for ensuring that times are used consistently within the |
|
10
|
|
|
* context of an individual page request. It does not, however, represent |
|
11
|
|
|
* the start time of the request. |
|
12
|
|
|
* |
|
13
|
|
|
* The static methods are a convenience wrapper around the instance of this |
|
14
|
|
|
* class stored in the DI container (which is set on the first query, and |
|
15
|
|
|
* then remains unchanged in subsequent calls). |
|
16
|
|
|
*/ |
|
17
|
|
|
class Epoch { |
|
18
|
|
|
|
|
19
|
|
|
private float $microtime; |
|
20
|
|
|
private int $time; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct() { |
|
23
|
|
|
$this->microtime = microtime(true); |
|
24
|
|
|
$this->time = IFloor($this->microtime); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function getMicrotime() : float { |
|
28
|
|
|
return $this->microtime; |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
public function getTime() : int { |
|
32
|
|
|
return $this->time; |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Returns the instance of this class from the DI container. |
|
37
|
|
|
* The first time this is called, it will populate the DI container, |
|
38
|
|
|
* and this will be the time associated with the page request. |
|
39
|
|
|
*/ |
|
40
|
|
|
private static function getInstance() : self { |
|
41
|
|
|
return DiContainer::get(self::class); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* Return the time (in seconds, with microsecond-level precision) |
|
46
|
|
|
* associated with a page request (i.e. stored in the DI container). |
|
47
|
|
|
*/ |
|
48
|
|
|
public static function microtime() : float { |
|
49
|
|
|
return self::getInstance()->getMicrotime(); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* Return the time (in seconds) associated with a page request |
|
54
|
|
|
* (i.e. stored in the DI container). |
|
55
|
|
|
*/ |
|
56
|
|
|
public static function time() : int { |
|
57
|
|
|
return self::getInstance()->getTime(); |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
/** |
|
61
|
|
|
* Update the time associated with this page request |
|
62
|
|
|
* (i.e. stored in the DI container). |
|
63
|
|
|
* |
|
64
|
|
|
* NOTE: This should never be called by normal page requests, and should |
|
65
|
|
|
* only be used by the CLI programs that run continuously. |
|
66
|
|
|
*/ |
|
67
|
|
|
public static function update() : void { |
|
68
|
|
|
if (!defined('NPC_SCRIPT')) { |
|
69
|
|
|
throw new \Exception('Only call this function from CLI programs!'); |
|
70
|
|
|
} |
|
71
|
|
|
DiContainer::getContainer()->set(self::class, new self()); |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
} |
|
75
|
|
|
|