|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace PhpCfdi\RfcLinc\Util; |
|
6
|
|
|
|
|
7
|
|
|
class CommandReader implements ReaderInterface |
|
8
|
|
|
{ |
|
9
|
|
|
/** @var resource|null */ |
|
10
|
|
|
private $process; |
|
11
|
|
|
|
|
12
|
|
|
/** @var resource|null */ |
|
13
|
|
|
private $inputPipe; |
|
14
|
|
|
|
|
15
|
3 |
|
public function __destruct() |
|
16
|
|
|
{ |
|
17
|
3 |
|
$this->close(); |
|
18
|
3 |
|
} |
|
19
|
|
|
|
|
20
|
5 |
|
public function open(string $command) |
|
21
|
|
|
{ |
|
22
|
5 |
|
$this->close(); |
|
23
|
5 |
|
$process = proc_open( |
|
24
|
5 |
|
$command, |
|
25
|
|
|
[ |
|
26
|
5 |
|
0 => ['pipe', 'r'], |
|
27
|
|
|
1 => ['pipe', 'w'], |
|
28
|
|
|
2 => ['pipe', 'w'], |
|
29
|
|
|
], |
|
30
|
5 |
|
$pipes |
|
31
|
|
|
); |
|
32
|
|
|
|
|
33
|
|
|
// if the process is not a resource |
|
34
|
5 |
|
if (! is_resource($process)) { |
|
35
|
|
|
throw new \RuntimeException('Cannot create a reader from the command'); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
// close stdin and stderr |
|
39
|
5 |
|
foreach ([0, 2] as $pipeIndex) { |
|
40
|
5 |
|
if (isset($pipes[$pipeIndex]) && is_resource($pipes[$pipeIndex])) { |
|
41
|
5 |
|
fclose($pipes[$pipeIndex]); |
|
42
|
|
|
} |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
// setup object |
|
46
|
5 |
|
$this->process = $process; |
|
47
|
5 |
|
$this->inputPipe = $pipes[1]; |
|
48
|
5 |
|
} |
|
49
|
|
|
|
|
50
|
5 |
|
public function readLine() |
|
51
|
|
|
{ |
|
52
|
5 |
|
if (! is_resource($this->process)) { |
|
53
|
1 |
|
throw new \RuntimeException('File is not open (command)'); |
|
54
|
|
|
} |
|
55
|
4 |
|
if (! is_resource($this->inputPipe)) { |
|
56
|
|
|
throw new \RuntimeException('File is not open (pipe)'); |
|
57
|
|
|
} |
|
58
|
4 |
|
return stream_get_line($this->inputPipe, 1024, PHP_EOL); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
6 |
|
public function close() |
|
62
|
|
|
{ |
|
63
|
6 |
|
if (is_resource($this->inputPipe)) { |
|
64
|
5 |
|
fclose($this->inputPipe); |
|
65
|
5 |
|
$this->inputPipe = null; |
|
66
|
|
|
} |
|
67
|
6 |
|
if (is_resource($this->process)) { |
|
68
|
5 |
|
$status = proc_get_status($this->process) ? : []; |
|
69
|
5 |
|
if ($status['running'] ?? false) { |
|
70
|
2 |
|
proc_terminate($this->process); |
|
71
|
|
|
} |
|
72
|
5 |
|
proc_close($this->process); |
|
73
|
5 |
|
$this->process = null; |
|
74
|
|
|
} |
|
75
|
6 |
|
} |
|
76
|
|
|
|
|
77
|
4 |
|
public function isOpen(): bool |
|
78
|
|
|
{ |
|
79
|
4 |
|
return is_resource($this->process); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|