-
Notifications
You must be signed in to change notification settings - Fork 162
/
Timebox.php
86 lines (71 loc) · 1.66 KB
/
Timebox.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace Illuminate\Support;
use Throwable;
class Timebox
{
/**
* Indicates if the timebox is allowed to return early.
*
* @var bool
*/
public $earlyReturn = false;
/**
* Invoke the given callback within the specified timebox minimum.
*
* @template TCallReturnType
*
* @param (callable($this): TCallReturnType) $callback
* @param int $microseconds
* @return TCallReturnType
*
* @throws \Throwable
*/
public function call(callable $callback, int $microseconds)
{
$exception = null;
$start = microtime(true);
try {
$result = $callback($this);
} catch (Throwable $caught) {
$exception = $caught;
}
$remainder = intval($microseconds - ((microtime(true) - $start) * 1000000));
if (! $this->earlyReturn && $remainder > 0) {
$this->usleep($remainder);
}
if ($exception) {
throw $exception;
}
return $result;
}
/**
* Indicate that the timebox can return early.
*
* @return $this
*/
public function returnEarly()
{
$this->earlyReturn = true;
return $this;
}
/**
* Indicate that the timebox cannot return early.
*
* @return $this
*/
public function dontReturnEarly()
{
$this->earlyReturn = false;
return $this;
}
/**
* Sleep for the specified number of microseconds.
*
* @param int $microseconds
* @return void
*/
protected function usleep(int $microseconds)
{
Sleep::usleep($microseconds);
}
}