|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of SebastianFeldmann\Cli. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Sebastian Feldmann <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
*/ |
|
11
|
|
|
|
|
12
|
|
|
namespace SebastianFeldmann\Cli\Processor; |
|
13
|
|
|
|
|
14
|
|
|
use RuntimeException; |
|
15
|
|
|
use SebastianFeldmann\Cli\Command\Result; |
|
16
|
|
|
use SebastianFeldmann\Cli\Processor; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Class ProcOpen |
|
20
|
|
|
* |
|
21
|
|
|
* @package SebastianFeldmann\Cli |
|
22
|
|
|
* @author Sebastian Feldmann <[email protected]> |
|
23
|
|
|
* @link https://github.com/sebastianfeldmann/cli |
|
24
|
|
|
* @since Class available since Release 0.9.0 |
|
25
|
|
|
*/ |
|
26
|
|
|
class ProcOpen implements Processor |
|
27
|
|
|
{ |
|
28
|
|
|
/** |
|
29
|
|
|
* Execute the command |
|
30
|
|
|
* |
|
31
|
|
|
* @param string $cmd |
|
32
|
|
|
* @param int[] $acceptableExitCodes |
|
33
|
3 |
|
* @return \SebastianFeldmann\Cli\Command\Result |
|
34
|
|
|
*/ |
|
35
|
3 |
|
public function run(string $cmd, array $acceptableExitCodes = [0]): Result |
|
36
|
|
|
{ |
|
37
|
3 |
|
$old = error_reporting(0); |
|
38
|
|
|
$descriptorSpec = [ |
|
39
|
|
|
['pipe', 'r'], |
|
40
|
|
|
['pipe', 'w'], |
|
41
|
|
|
['pipe', 'w'], |
|
42
|
3 |
|
]; |
|
43
|
3 |
|
|
|
44
|
|
|
$process = proc_open($cmd, $descriptorSpec, $pipes); |
|
45
|
|
|
if (!is_resource($process)) { |
|
46
|
|
|
throw new RuntimeException('can\'t execute \'proc_open\''); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
3 |
|
// Loop on process until it exits normally. |
|
50
|
3 |
|
$stdOut = ""; |
|
51
|
|
|
$stdErr = ""; |
|
52
|
3 |
|
do { |
|
53
|
3 |
|
// Consume output streams while the process runs. The buffer will block process updates when full |
|
54
|
3 |
|
$status = proc_get_status($process); |
|
55
|
|
|
$stdOut .= stream_get_contents($pipes[1]); |
|
56
|
|
|
$stdErr .= stream_get_contents($pipes[2]); |
|
57
|
3 |
|
} while ($status && $status['running']); |
|
|
|
|
|
|
58
|
3 |
|
|
|
59
|
3 |
|
$code = $status['exitcode'] ?? -1; |
|
60
|
|
|
|
|
61
|
|
|
// make sure all pipes are closed before calling proc_close |
|
62
|
3 |
|
foreach ($pipes as $index => $pipe) { |
|
63
|
3 |
|
fclose($pipe); |
|
64
|
|
|
unset($pipes[$index]); |
|
65
|
3 |
|
} |
|
66
|
|
|
|
|
67
|
|
|
proc_close($process); |
|
68
|
|
|
error_reporting($old); |
|
69
|
|
|
|
|
70
|
|
|
return new Result($cmd, $code, $stdOut, $stdErr, '', $acceptableExitCodes); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.
Consider making the comparison explicit by using
empty(..)or! empty(...)instead.