Completed
Pull Request — master (#5)
by Dan Michael O.
18:23 queued 14:26
created

Command::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 1
nc 1
nop 0
crap 2
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
     * @param bool   $escape  True to escape each param using escapeshellarg
19
     *
20
     * @return bool|string
21
     *
22
     * @throws \Exception
23
     */
24 15
    public static function exec($command, array $params = array(), $escape=true)
25
    {
26 15
        if (empty($command)) {
27 3
            throw new \Exception('Command line is empty');
28
        }
29
30 12
        $command = self::bindParams($command, $params, $escape);
31
32 12
        exec($command, $output, $code);
33
34 12
        if (count($output) === 0) {
35 3
            $output = $code;
36 3
        } else {
37 9
            $output = implode(PHP_EOL, $output);
38
        }
39
40 12
        if ($code !== 0) {
41 3
            throw new \Exception($output . ' Command line: ' . $command);
42
        }
43
44 9
        return $output;
45
    }
46
47
    /**
48
     * Bind params to command.
49
     *
50
     * @param string $command
51
     * @param array  $params
52
     *
53
     * @return string
54
     */
55 12
    public static function bindParams($command, array $params, $escape)
56
    {
57 12
        if (count($params) > 0) {
58
            $wrapper = function ($string) {
59 9
                return '{' . $string . '}';
60 9
            };
61 9
            $converter = function ($var) use ($escape) {
62 9
                if (is_array($var)) {
63 3
                    $var = implode(' ', $var);
64 3
                }
65
66 9
                if ($escape) {
67 6
                    $var = escapeshellarg($var);
68 6
                }
69
70 9
                return $var;
71 9
            };
72
73 9
            $command = str_replace(
74 9
                array_map(
75 9
                    $wrapper,
76 9
                    array_keys($params)
77 9
                ),
78 9
                array_map(
79 9
                    $converter,
80 9
                    array_values($params)
81 9
                ),
82
                $command
83 9
            );
84 9
        }
85
86 12
        return $command;
87
    }
88
}
89