1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Tleckie\Async; |
4
|
|
|
|
5
|
|
|
use Opis\Closure\SerializableClosure; |
6
|
|
|
use Symfony\Component\Process\Process; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* Class TaskFactory |
10
|
|
|
* |
11
|
|
|
* @package Tleckie\Async |
12
|
|
|
* @author Teodoro Leckie Westberg <[email protected]> |
13
|
|
|
*/ |
14
|
|
|
class TaskFactory implements TaskFactoryInterface |
15
|
|
|
{ |
16
|
|
|
/** @var int */ |
17
|
|
|
protected int $pid = 0; |
18
|
|
|
|
19
|
|
|
/** @var int */ |
20
|
|
|
protected int $index = 0; |
21
|
|
|
|
22
|
|
|
/** @var string */ |
23
|
|
|
protected string $script; |
24
|
|
|
|
25
|
|
|
/** @var string */ |
26
|
|
|
protected string $autoloader; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* TaskFactory constructor. |
30
|
|
|
*/ |
31
|
|
|
public function __construct() |
32
|
|
|
{ |
33
|
|
|
$this->autoloader = $this->find('vendor/autoload.php'); |
34
|
|
|
$this->script = $this->find('bin/child'); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param string $file |
39
|
|
|
* @return string |
40
|
|
|
*/ |
41
|
|
|
protected function find(string $file): string |
42
|
|
|
{ |
43
|
|
|
$paths = array_filter([ |
44
|
|
|
__DIR__ . '/../../../../' . $file, |
45
|
|
|
__DIR__ . '/../../../' . $file, |
46
|
|
|
__DIR__ . '/../../' . $file, |
47
|
|
|
__DIR__ . '/../' . $file, |
48
|
|
|
], static function (string $path) { |
49
|
|
|
return file_exists($path); |
50
|
|
|
}); |
51
|
|
|
|
52
|
|
|
return reset($paths); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @inheritdoc |
57
|
|
|
*/ |
58
|
|
|
public function createTask( |
59
|
|
|
$process, |
60
|
|
|
Encoder $encoder, |
61
|
|
|
$binary = PHP_BINARY |
62
|
|
|
): TaskInterface { |
63
|
|
|
$process = new Process([ |
64
|
|
|
$binary, |
65
|
|
|
$this->script, |
66
|
|
|
$this->autoloader, |
67
|
|
|
$encoder->encode(new SerializableClosure($process)) |
68
|
|
|
]); |
69
|
|
|
|
70
|
|
|
return new Task($process, $encoder, $this->id()); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @return int |
75
|
|
|
*/ |
76
|
|
|
protected function id(): int |
77
|
|
|
{ |
78
|
|
|
return (++$this->index) * $this->pid(); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
/** |
82
|
|
|
* @return int |
83
|
|
|
*/ |
84
|
|
|
protected function pid(): int |
85
|
|
|
{ |
86
|
|
|
$this->pid = $this->pid ?? getmypid(); |
87
|
|
|
|
88
|
|
|
return $this->pid; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|