[Process] Fix escaping on Windows

Windows escaping is broken since the last merges.
This commit is contained in:
Romain Neutron 2014-03-18 14:37:22 +01:00
parent 02088bc62f
commit 0f65f90b06
3 changed files with 15 additions and 12 deletions

View File

@ -47,20 +47,18 @@ class ProcessUtils
$escapedArgument = ''; $escapedArgument = '';
$quote = false; $quote = false;
foreach (preg_split('/([%"])/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) { foreach (preg_split('/(")/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
if ('"' === $part) { if ('"' === $part) {
$escapedArgument .= '\\"'; $escapedArgument .= '\\"';
} elseif ('%' === $part) { } elseif (self::isSurroundedBy($part, '%')) {
$escapedArgument .= '^%'; // Avoid environment variable expansion
$escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
} else { } else {
// escape trailing backslash
if ('\\' === substr($part, -1)) { if ('\\' === substr($part, -1)) {
$part .= '\\'; $part .= '\\';
} }
$part = escapeshellarg($part); $quote = true;
if ('"' === $part[0] && '"' === $part[strlen($part) - 1]) {
$part = substr($part, 1, -1);
$quote = true;
}
$escapedArgument .= $part; $escapedArgument .= $part;
} }
} }
@ -73,4 +71,9 @@ class ProcessUtils
return escapeshellarg($argument); return escapeshellarg($argument);
} }
private static function isSurroundedBy($arg, $char)
{
return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
}
} }

View File

@ -142,13 +142,13 @@ class ProcessBuilderTest extends \PHPUnit_Framework_TestCase
public function testShouldEscapeArguments() public function testShouldEscapeArguments()
{ {
$pb = new ProcessBuilder(array('%path%', 'foo " bar')); $pb = new ProcessBuilder(array('%path%', 'foo " bar', '%baz%baz'));
$proc = $pb->getProcess(); $proc = $pb->getProcess();
if (defined('PHP_WINDOWS_VERSION_BUILD')) { if (defined('PHP_WINDOWS_VERSION_BUILD')) {
$this->assertSame('^%"path"^% "foo "\\"" bar"', $proc->getCommandLine()); $this->assertSame('^%"path"^% "foo \\" bar" "%baz%baz"', $proc->getCommandLine());
} else { } else {
$this->assertSame("'%path%' 'foo \" bar'", $proc->getCommandLine()); $this->assertSame("'%path%' 'foo \" bar' '%baz%baz'", $proc->getCommandLine());
} }
} }

View File

@ -30,7 +30,7 @@ class ProcessUtilsTest extends \PHPUnit_Framework_TestCase
array('"\"php\" \"-v\""', '"php" "-v"'), array('"\"php\" \"-v\""', '"php" "-v"'),
array('"foo bar"', 'foo bar'), array('"foo bar"', 'foo bar'),
array('^%"path"^%', '%path%'), array('^%"path"^%', '%path%'),
array('"<|>"\\"" "\\""\'f"', '<|>" "\'f'), array('"<|>\\" \\"\'f"', '<|>" "\'f'),
array('""', ''), array('""', ''),
array('"with\trailingbs\\\\"', 'with\trailingbs\\'), array('"with\trailingbs\\\\"', 'with\trailingbs\\'),
); );