about summary refs log tree commit diff
path: root/sourcecodes/terminal_commands.php
blob: fb4f44667556900f7c8c3cc6ec44ab55d62ec745 (plain)
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
<?php

function __command2string__(string $str_cmd, string $arg): string
{
    if(is_null($str_cmd) or trim($str_cmd) == '') {
        return trim($arg);
    }
    return sprintf("%s %s", $str_cmd, $arg);
}

/**
 * Run terminal commands: thin wrapper around `proc_open`.
 *
 * This wraps the `proc_open(...)` function, by doing some basic checks and
 * raising appropriate `RuntimeException errors in case of failures.`
 *
 * @param array $command An array of strings, where the first item is the
 *        command to run and the rest are arguments to that command.
 * @returns array Returns the exit code for the process, the output on the
 *          standard output and the output on the standard error.
 * @raises RuntimeException
 */
function runTerminalCommand(array $command): array
{
    if(!is_array($command))
    {
        throw new \RuntimeException(
            "Command *must* always be an array of strings.");
    }

    if(sizeof($command) == 0) {
        throw new \RuntimeException(
            "You must provide at least the command to run.");
    }

    $descriptors = [
        1 => ['pipe', 'w'], //stdout
        2 => ['pipe', 'w'], //stderr
    ];

    // Generate `$strcmd` below to use for user notifications.
    $strcmd = array_reduce(
        array_merge(
            [escapeshellcmd($command[0])],
            array_map(
                'escapeshellarg',
                array_slice($command, 1, sizeof($command)))),
        '__command2string__',
        "");
    $process = proc_open(
        $command, // `proc_open` auto-escapes array command
        $descriptors,
        $pipes);

    if(!is_resource($process)) {
        throw new \RunTimeException(sprintf(
            "PHP was not able to spawn the process [%s]. " . 
            "Check system resources or paths.",
            $strcmd
        ));
    }

    // Read streams:
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);

    // Clean streams and close process resource.
    fclose($pipes[1]);
    fclose($pipes[2]);
    $exitcode = proc_close($process);

    if($exitcode !== 0) {
        throw new \RuntimeException(sprintf(
            "Command [%s] failed with exit code %d.\n" .
            "Stdout: %s\n\nStderr: %s",
            $strcmd,
            $exitcode,
            trim($stdout),
            trim($stderr)
        ));
    }
    return [$exitcode, $stdout, $stderr];
}
?>