|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Wonderland\Thread; |
|
4
|
|
|
|
|
5
|
|
|
use Wonderland\Thread\Exception\ThreadException; |
|
6
|
|
|
|
|
7
|
|
|
abstract class AbstractThread extends AbstractThreadMediator |
|
8
|
|
|
{ |
|
9
|
|
|
const EXIT_STATUS_SUCCESS = 0; |
|
10
|
|
|
const EXIT_STATUS_ERROR = 1; |
|
11
|
|
|
|
|
12
|
|
|
/** @var int $pid */ |
|
13
|
|
|
private $pid; |
|
14
|
|
|
|
|
15
|
|
|
/** @var string $processName */ |
|
16
|
|
|
private $processName; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* AbstractThread constructor. |
|
20
|
|
|
* |
|
21
|
|
|
* @param string $processName |
|
22
|
|
|
*/ |
|
23
|
10 |
|
public function __construct(string $processName) |
|
24
|
|
|
{ |
|
25
|
10 |
|
$this->processName = $processName; |
|
26
|
10 |
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Return the name of the method to process during the thread |
|
30
|
|
|
* |
|
31
|
|
|
* @return string |
|
32
|
|
|
*/ |
|
33
|
|
|
abstract protected function getMethodName(): string; |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Return the list of dependencies that will be passed as parameters of the method referenced by getMethodName |
|
37
|
|
|
* |
|
38
|
|
|
* @return array |
|
39
|
|
|
*/ |
|
40
|
|
|
abstract protected function getDependencies(): array; |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* @return int|null |
|
44
|
|
|
*/ |
|
45
|
2 |
|
public function getPid(): ?int |
|
46
|
|
|
{ |
|
47
|
2 |
|
return $this->pid; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** |
|
51
|
|
|
* @param int $pid |
|
52
|
|
|
* @return AbstractThread |
|
53
|
|
|
*/ |
|
54
|
6 |
|
public function setPid(int $pid): self |
|
55
|
|
|
{ |
|
56
|
6 |
|
$this->pid = $pid; |
|
57
|
|
|
|
|
58
|
6 |
|
return $this; |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** |
|
62
|
|
|
* @return string |
|
63
|
|
|
*/ |
|
64
|
3 |
|
public function getProcessName(): ?string |
|
65
|
|
|
{ |
|
66
|
3 |
|
return $this->processName; |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
|
|
/** |
|
70
|
|
|
* @return int |
|
71
|
|
|
* @throws ThreadException |
|
72
|
|
|
*/ |
|
73
|
3 |
|
public function run(): int |
|
74
|
|
|
{ |
|
75
|
3 |
|
if (false === method_exists($this, $this->getMethodName())) { |
|
76
|
1 |
|
throw new ThreadException('No proper method defined for the thread'); |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
2 |
|
$status = call_user_func_array( |
|
80
|
2 |
|
[$this, $this->getMethodName()], |
|
81
|
2 |
|
array_merge([$this->getProcessName()], $this->getDependencies()) |
|
82
|
|
|
); |
|
83
|
|
|
|
|
84
|
2 |
|
if (null === $status) { |
|
85
|
1 |
|
throw new ThreadException( |
|
86
|
1 |
|
'Error. You must return a process status in '.get_class($this).':'.$this->getMethodName() |
|
87
|
|
|
); |
|
88
|
|
|
} |
|
89
|
|
|
|
|
90
|
1 |
|
return $status; |
|
91
|
|
|
} |
|
92
|
|
|
|
|
93
|
|
|
} |
|
94
|
|
|
|