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
|
|
|
public function __construct(string $processName) |
24
|
|
|
{ |
25
|
|
|
$this->processName = $processName; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Return the name of the method to process during the thread |
30
|
|
|
* @return string |
31
|
|
|
*/ |
32
|
|
|
abstract protected function getMethodName(): string; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Return the list of dependencies that will be passed as parameters of the method referenced by getMethodName |
36
|
|
|
* @return array |
37
|
|
|
*/ |
38
|
|
|
abstract protected function getDependencies(): array; |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* @return int|null |
42
|
|
|
*/ |
43
|
|
|
public function getPid(): ?int |
44
|
|
|
{ |
45
|
|
|
return $this->pid; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param int $pid |
50
|
|
|
* @return AbstractThread |
51
|
|
|
*/ |
52
|
|
|
public function setPid(int $pid): self |
53
|
|
|
{ |
54
|
|
|
$this->pid = $pid; |
55
|
|
|
|
56
|
|
|
return $this; |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @return string |
61
|
|
|
*/ |
62
|
|
|
public function getProcessName(): ?string |
63
|
|
|
{ |
64
|
|
|
return $this->processName; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return int |
69
|
|
|
* @throws ThreadException |
70
|
|
|
*/ |
71
|
|
|
public function run(): int |
72
|
|
|
{ |
73
|
|
|
if (false === method_exists($this, $this->getMethodName())) { |
74
|
|
|
throw new ThreadException('No proper method defined for the thread'); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
$status = call_user_func_array( |
78
|
|
|
[$this, $this->getMethodName()], |
79
|
|
|
array_merge([$this->getProcessName()], $this->getDependencies()) |
80
|
|
|
); |
81
|
|
|
|
82
|
|
|
if (null === $status) { |
83
|
|
|
throw new ThreadException('Error. You must return a process status in your callback function'); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return $status; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
} |
90
|
|
|
|