|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Recca0120\Terminal; |
|
4
|
|
|
|
|
5
|
|
|
/** |
|
6
|
|
|
* ProcessUtils is a bunch of utility methods. |
|
7
|
|
|
* |
|
8
|
|
|
* This class was originally copied from Symfony 3. |
|
9
|
|
|
*/ |
|
10
|
|
|
class ProcessUtils |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* Escapes a string to be used as a shell argument. |
|
14
|
|
|
* |
|
15
|
|
|
* @param string $argument |
|
16
|
|
|
* @return string |
|
17
|
|
|
*/ |
|
18
|
3 |
|
public static function escapeArgument($argument) |
|
19
|
|
|
{ |
|
20
|
|
|
// Fix for PHP bug #43784 escapeshellarg removes % from given string |
|
21
|
|
|
// Fix for PHP bug #49446 escapeshellarg doesn't work on Windows |
|
22
|
|
|
// @see https://bugs.php.net/bug.php?id=43784 |
|
23
|
|
|
// @see https://bugs.php.net/bug.php?id=49446 |
|
24
|
3 |
|
if ('\\' === DIRECTORY_SEPARATOR) { |
|
25
|
|
|
if ('' === $argument) { |
|
26
|
|
|
return '""'; |
|
27
|
|
|
} |
|
28
|
|
|
$escapedArgument = ''; |
|
29
|
|
|
$quote = false; |
|
30
|
|
|
foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { |
|
31
|
|
|
if ('"' === $part) { |
|
32
|
|
|
$escapedArgument .= '\\"'; |
|
33
|
|
|
} elseif (self::isSurroundedBy($part, '%')) { |
|
34
|
|
|
// Avoid environment variable expansion |
|
35
|
|
|
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%'; |
|
36
|
|
|
} else { |
|
37
|
|
|
// escape trailing backslash |
|
38
|
|
|
if ('\\' === substr($part, -1)) { |
|
39
|
|
|
$part .= '\\'; |
|
40
|
|
|
} |
|
41
|
|
|
$quote = true; |
|
42
|
|
|
$escapedArgument .= $part; |
|
43
|
|
|
} |
|
44
|
|
|
} |
|
45
|
|
|
if ($quote) { |
|
46
|
|
|
$escapedArgument = '"'.$escapedArgument.'"'; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
return $escapedArgument; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
3 |
|
return "'".str_replace("'", "'\\''", $argument)."'"; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Is the given string surrounded by the given character? |
|
57
|
|
|
* |
|
58
|
|
|
* @param string $arg |
|
59
|
|
|
* @param string $char |
|
60
|
|
|
* @return bool |
|
61
|
|
|
*/ |
|
62
|
|
|
protected static function isSurroundedBy($arg, $char) |
|
63
|
|
|
{ |
|
64
|
|
|
return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1]; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|