Timebox.php
1.3 KB
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
<?php
namespace Illuminate\Support;
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.
*
* @param callable $callback
* @param int $microseconds
* @return mixed
*/
public function call(callable $callback, int $microseconds)
{
$start = microtime(true);
$result = $callback($this);
$remainder = $microseconds - ((microtime(true) - $start) * 1000000);
if (! $this->earlyReturn && $remainder > 0) {
$this->usleep($remainder);
}
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 $microseconds
* @return void
*/
protected function usleep($microseconds)
{
usleep($microseconds);
}
}