1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Copyright 2017 NanoSector |
5
|
|
|
* |
6
|
|
|
* You should have received a copy of the MIT license with the project. |
7
|
|
|
* See the LICENSE file for more information. |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Yoshi2889\Tasks; |
11
|
|
|
|
12
|
|
|
class CallbackTask implements TaskInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var callable |
16
|
|
|
*/ |
17
|
|
|
protected $callback = null; |
|
|
|
|
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* @var int |
21
|
|
|
*/ |
22
|
|
|
protected $expiryTime = 0; |
|
|
|
|
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* @var array |
26
|
|
|
*/ |
27
|
|
|
protected $storedArguments = []; |
|
|
|
|
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* CallbackTask constructor. |
31
|
|
|
* |
32
|
|
|
* @param callable $callback |
33
|
|
|
* @param int $time |
34
|
|
|
* @param array $args |
35
|
|
|
*/ |
36
|
16 |
|
public function __construct(callable $callback, int $time, array $args = []) |
37
|
|
|
{ |
38
|
16 |
|
$this->callback = $callback; |
39
|
16 |
|
$this->setExpiryTime(time() + $time); |
40
|
16 |
|
$this->setStoredArguments($args); |
41
|
16 |
|
} |
42
|
|
|
|
43
|
10 |
|
public function run(): ?TaskInterface |
44
|
|
|
{ |
45
|
10 |
|
$result = call_user_func_array($this->getCallback(), $this->getStoredArguments()); |
46
|
|
|
|
47
|
10 |
|
if (!($result instanceof TaskInterface)) |
|
|
|
|
48
|
9 |
|
return null; |
49
|
|
|
|
50
|
2 |
|
return $result; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function cancel(): void |
54
|
|
|
{ |
55
|
|
|
$this->callback = function () {}; |
56
|
5 |
|
$this->setExpiryTime(0); |
57
|
5 |
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @return callable |
61
|
|
|
*/ |
62
|
12 |
|
public function getCallback(): callable |
63
|
|
|
{ |
64
|
12 |
|
return $this->callback; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return int |
69
|
|
|
*/ |
70
|
11 |
|
public function getExpiryTime(): int |
71
|
|
|
{ |
72
|
11 |
|
return $this->expiryTime; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** |
76
|
|
|
* @param int $expiryTime |
77
|
|
|
*/ |
78
|
16 |
|
public function setExpiryTime(int $expiryTime) |
79
|
|
|
{ |
80
|
16 |
|
$this->expiryTime = $expiryTime; |
81
|
16 |
|
} |
82
|
|
|
|
83
|
|
|
/** |
84
|
|
|
* @return array |
85
|
|
|
*/ |
86
|
10 |
|
public function getStoredArguments(): array |
87
|
|
|
{ |
88
|
10 |
|
return $this->storedArguments; |
89
|
|
|
} |
90
|
|
|
|
91
|
|
|
/** |
92
|
|
|
* @param array $storedArguments |
93
|
|
|
*/ |
94
|
16 |
|
public function setStoredArguments(array $storedArguments) |
95
|
|
|
{ |
96
|
16 |
|
$this->storedArguments = $storedArguments; |
97
|
16 |
|
} |
98
|
|
|
|
99
|
|
|
|
100
|
|
|
} |