-
Notifications
You must be signed in to change notification settings - Fork 161
/
ProcessUtils.php
69 lines (61 loc) · 2 KB
/
ProcessUtils.php
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
<?php
namespace Illuminate\Support;
/**
* ProcessUtils is a bunch of utility methods.
*
* This class was originally copied from Symfony 3.
*/
class ProcessUtils
{
/**
* Escapes a string to be used as a shell argument.
*
* @param string $argument
* @return string
*/
public static function escapeArgument($argument)
{
// Fix for PHP bug #43784 escapeshellarg removes % from given string
// Fix for PHP bug #49446 escapeshellarg doesn't work on Windows
// @see https://bugs.php.net/bug.php?id=43784
// @see https://bugs.php.net/bug.php?id=49446
if ('\\' === DIRECTORY_SEPARATOR) {
if ($argument === '') {
return '""';
}
$escapedArgument = '';
$quote = false;
foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
if ($part === '"') {
$escapedArgument .= '\\"';
} elseif (self::isSurroundedBy($part, '%')) {
// Avoid environment variable expansion
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
} else {
// escape trailing backslash
if (str_ends_with($part, '\\')) {
$part .= '\\';
}
$quote = true;
$escapedArgument .= $part;
}
}
if ($quote) {
$escapedArgument = '"'.$escapedArgument.'"';
}
return $escapedArgument;
}
return "'".str_replace("'", "'\\''", $argument)."'";
}
/**
* Is the given string surrounded by the given character?
*
* @param string $arg
* @param string $char
* @return bool
*/
protected static function isSurroundedBy($arg, $char)
{
return strlen($arg) > 2 && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
}
}