-
Notifications
You must be signed in to change notification settings - Fork 30
/
Process.php
executable file
·100 lines (84 loc) · 2.12 KB
/
Process.php
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
namespace yiicod\socketio;
use Yii;
use yii\helpers\HtmlPurifier;
/**
* Class Process
*
* @package SfCod\SocketIoBundle
*/
/**
* Class Process
*
* @package yiicod\socketio
*/
class Process
{
/**
* @var array
*/
private static $_inWork = [];
/**
* @var
*/
public $yiiAlias;
/**
* @return int
*/
public function getParallelEnv(): int
{
return getenv('SOCKET_IO.PARALLEL') ? getenv('SOCKET_IO.PARALLEL') : 10;
}
/**
* Run process. If more then limit then wait and try run process on more time.
*
* @param string $handle
* @param array $data
*
* @return \Symfony\Component\Process\Process
*/
public function run(string $handle, array $data)
{
$this->inWork();
while (count(self::$_inWork) >= $this->getParallelEnv()) {
usleep(100);
$this->inWork();
}
return $this->push($handle, $data);
}
/**
* In work processes
*/
private function inWork()
{
foreach (self::$_inWork as $i => $proccess) {
if (false === $proccess->isRunning()) {
unset(self::$_inWork[$i]);
}
}
}
/**
* Create cmd process and push to queue.
*
* @param string $handle
* @param array $data
*
* @return \Symfony\Component\Process\Process
*/
private function push(string $handle, array $data): \Symfony\Component\Process\Process
{
$cmd = HtmlPurifier::process(sprintf('php yii socketio/process %s %s', escapeshellarg($handle), escapeshellarg(json_encode($data))));
if (is_null($this->yiiAlias)) {
if (file_exists(Yii::getAlias('@app/yii'))) {
$this->yiiAlias = '@app';
} elseif (file_exists(Yii::getAlias('@app/../yii'))) {
$this->yiiAlias = '@app/../';
}
}
$process = new \Symfony\Component\Process\Process($cmd, Yii::getAlias($this->yiiAlias));
$process->setTimeout(10);
$process->start();
self::$_inWork[] = $process;
return $process;
}
}