|
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 $commandLine |
|
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($commandLine, array $params = array(), $escape=true) |
|
25
|
|
|
{ |
|
26
|
15 |
|
if (empty($commandLine)) { |
|
27
|
3 |
|
throw new \Exception('Command line is empty'); |
|
28
|
|
|
} |
|
29
|
|
|
|
|
30
|
12 |
|
$commandLine = self::bindParams($commandLine, $params, $escape); |
|
31
|
|
|
|
|
32
|
12 |
|
exec($commandLine, $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: ' . $commandLine); |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
9 |
|
return $output; |
|
45
|
|
|
} |
|
46
|
|
|
|
|
47
|
|
|
/** |
|
48
|
|
|
* Bind params to command. |
|
49
|
|
|
* |
|
50
|
|
|
* @param string $commandLine |
|
51
|
|
|
* @param array $params |
|
52
|
|
|
* |
|
53
|
|
|
* @return string |
|
54
|
|
|
*/ |
|
55
|
12 |
|
public static function bindParams($commandLine, 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 |
|
$commandLine = 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
|
|
|
$commandLine |
|
83
|
9 |
|
); |
|
84
|
9 |
|
} |
|
85
|
|
|
|
|
86
|
12 |
|
return $commandLine; |
|
87
|
|
|
} |
|
88
|
|
|
} |
|
89
|
|
|
|