4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Process;
14 use Symfony\Component\Process\Exception\InvalidArgumentException;
17 * ProcessUtils is a bunch of utility methods.
19 * This class contains static methods only and is not meant to be instantiated.
21 * @author Martin HasoĊ <martin.hason@gmail.com>
26 * This class should not be instantiated.
28 private function __construct()
33 * Escapes a string to be used as a shell argument.
35 * @param string $argument The argument that will be escaped
37 * @return string The escaped argument
39 public static function escapeArgument($argument)
41 //Fix for PHP bug #43784 escapeshellarg removes % from given string
42 //Fix for PHP bug #49446 escapeshellarg doesn't work on Windows
43 //@see https://bugs.php.net/bug.php?id=43784
44 //@see https://bugs.php.net/bug.php?id=49446
45 if ('\\' === DIRECTORY_SEPARATOR) {
46 if ('' === $argument) {
47 return escapeshellarg($argument);
50 $escapedArgument = '';
52 foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
54 $escapedArgument .= '\\"';
55 } elseif (self::isSurroundedBy($part, '%')) {
56 // Avoid environment variable expansion
57 $escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
59 // escape trailing backslash
60 if ('\\' === substr($part, -1)) {
64 $escapedArgument .= $part;
68 $escapedArgument = '"'.$escapedArgument.'"';
71 return $escapedArgument;
74 return "'".str_replace("'", "'\\''", $argument)."'";
78 * Validates and normalizes a Process input.
80 * @param string $caller The name of method call that validates the input
81 * @param mixed $input The input to validate
83 * @return mixed The validated input
85 * @throws InvalidArgumentException In case the input is not valid
87 public static function validateInput($caller, $input)
89 if (null !== $input) {
90 if (is_resource($input)) {
93 if (is_string($input)) {
96 if (is_scalar($input)) {
97 return (string) $input;
99 if ($input instanceof Process) {
100 return $input->getIterator($input::ITER_SKIP_ERR);
102 if ($input instanceof \Iterator) {
105 if ($input instanceof \Traversable) {
106 return new \IteratorIterator($input);
109 throw new InvalidArgumentException(sprintf('%s only accepts strings, Traversable objects or stream resources.', $caller));
115 private static function isSurroundedBy($arg, $char)
117 return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];