Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
68.42% |
13 / 19 |
|
0.00% |
0 / 1 |
CRAP | |
0.00% |
0 / 1 |
Passthru | |
68.42% |
13 / 19 |
|
0.00% |
0 / 1 |
10.02 | |
0.00% |
0 / 1 |
exec | |
68.42% |
13 / 19 |
|
0.00% |
0 / 1 |
10.02 |
1 | <?php |
2 | |
3 | namespace ExecWithFallback; |
4 | |
5 | /** |
6 | * Emulate exec() with passthru() |
7 | * |
8 | * @package ExecWithFallback |
9 | * @author Bjørn Rosell <it@rosell.dk> |
10 | */ |
11 | class Passthru |
12 | { |
13 | |
14 | /** |
15 | * Emulate exec() with passthru() |
16 | * |
17 | * @param string $command The command to execute |
18 | * @param string &$output (optional) |
19 | * @param int &$result_code (optional) |
20 | * |
21 | * @return string | false The last line of output or false in case of failure |
22 | */ |
23 | public static function exec($command, &$output = null, &$result_code = null) |
24 | { |
25 | ob_start(); |
26 | // Note: We use try/catch in order to close output buffering in case it throws |
27 | try { |
28 | passthru($command, $result_code); |
29 | } catch (\Exception $e) { |
30 | ob_get_clean(); |
31 | passthru($command, $result_code); |
32 | } catch (\Throwable $e) { |
33 | ob_get_clean(); |
34 | passthru($command, $result_code); |
35 | } |
36 | $result = ob_get_clean(); |
37 | |
38 | // split new lines. Also remove trailing space, as exec() does |
39 | $theOutput = preg_split('/\s*\r\n|\s*\n\r|\s*\n|\s*\r/', $result); |
40 | |
41 | // remove the last element if it is blank |
42 | if ((count($theOutput) > 0) && ($theOutput[count($theOutput) -1] == '')) { |
43 | array_pop($theOutput); |
44 | } |
45 | |
46 | if (count($theOutput) == 0) { |
47 | return ''; |
48 | } |
49 | if (gettype($output) == 'array') { |
50 | foreach ($theOutput as $line) { |
51 | $output[] = $line; |
52 | } |
53 | } else { |
54 | $output = $theOutput; |
55 | } |
56 | return $theOutput[count($theOutput) -1]; |
57 | } |
58 | } |