Command::bindParams()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 17
ccs 10
cts 10
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 9
nc 3
nop 2
crap 4
1
<?php
2
namespace pastuhov\Command;
3
4
/**
5
 * Command.
6
 */
7
final class Command
8
{
9
    private function __construct()
10
    {
11
    }
12
13
    /**
14
     * Execute command with params.
15
     *
16
     * @param string $command
17
     * @param array  $params
18
     *
19
     * @return bool|string
20
     *
21
     * @throws \Exception
22
     */
23 15
    public static function exec($command, array $params = array(), $mergeStdErr=true)
24
    {
25 15
        if (empty($command)) {
26 3
            throw new \InvalidArgumentException('Command line is empty');
27
        }
28
29 12
        $command = self::bindParams($command, $params);
30
31 12
        if ($mergeStdErr) {
32
            // Redirect stderr to stdout to include it in $output
33 12
            $command .= ' 2>&1';
34 12
        }
35
36 12
        exec($command, $output, $code);
37
38 12
        if (count($output) === 0) {
39
            $output = $code;
40
        } else {
41 12
            $output = implode(PHP_EOL, $output);
42
        }
43
44 12
        if ($code !== 0) {
45 3
            throw new CommandException($command, $output, $code);
46
        }
47
48 9
        return $output;
49
    }
50
51
    /**
52
     * Bind params to command.
53
     *
54
     * @param string $command
55
     * @param array  $params
56
     *
57
     * @return string
58
     */
59 12
    public static function bindParams($command, array $params)
60
    {
61 12
        $wrappers = array();
62 12
        $converters = array();
63 12
        foreach ($params as $key => $value) {
64
65
            // Escaped
66 9
            $wrappers[] = '{' . $key . '}';
67 9
            $converters[] = escapeshellarg(is_array($value) ? implode(' ', $value) : $value);
68
69
            // Unescaped
70 9
            $wrappers[] = '{!' . $key . '!}';
71 9
            $converters[] = is_array($value) ? implode(' ', $value) : $value;
72 12
        }
73
74 12
        return str_replace($wrappers, $converters, $command);
75
    }
76
}
77