| 1 |
<?php |
| 2 |
|
| 3 |
/* |
| 4 |
* This file is part of the Symfony package. |
| 5 |
* |
| 6 |
* (c) Fabien Potencier <fabien@symfony.com> |
| 7 |
* |
| 8 |
* For the full copyright and license information, please view the LICENSE |
| 9 |
* file that was distributed with this source code. |
| 10 |
*/ |
| 11 |
|
| 12 |
namespace Symfony\Component\Console\Input; |
| 13 |
|
| 14 |
use Symfony\Component\Console\Exception\InvalidArgumentException; |
| 15 |
|
| 16 |
/** |
| 17 |
* StringInput represents an input provided as a string. |
| 18 |
* |
| 19 |
* Usage: |
| 20 |
* |
| 21 |
* $input = new StringInput('foo --bar="foobar"'); |
| 22 |
* |
| 23 |
* @author Fabien Potencier <fabien@symfony.com> |
| 24 |
*/ |
| 25 |
class StringInput extends ArgvInput |
| 26 |
{ |
| 27 |
public const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)'; |
| 28 |
public const REGEX_UNQUOTED_STRING = '([^\s\\\\]+?)'; |
| 29 |
public const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')'; |
| 30 |
|
| 31 |
/** |
| 32 |
* @param string $input A string representing the parameters from the CLI |
| 33 |
*/ |
| 34 |
public function __construct(string $input) |
| 35 |
{ |
| 36 |
parent::__construct([]); |
| 37 |
|
| 38 |
$this->setTokens($this->tokenize($input)); |
| 39 |
} |
| 40 |
|
| 41 |
/** |
| 42 |
* Tokenizes a string. |
| 43 |
* |
| 44 |
* @throws InvalidArgumentException When unable to parse input (should never happen) |
| 45 |
*/ |
| 46 |
private function tokenize(string $input): array |
| 47 |
{ |
| 48 |
$tokens = []; |
| 49 |
$length = \strlen($input); |
| 50 |
$cursor = 0; |
| 51 |
$token = null; |
| 52 |
while ($cursor < $length) { |
| 53 |
if ('\\' === $input[$cursor]) { |
| 54 |
$token .= $input[++$cursor] ?? ''; |
| 55 |
++$cursor; |
| 56 |
continue; |
| 57 |
} |
| 58 |
|
| 59 |
if (preg_match('/\s+/A', $input, $match, 0, $cursor)) { |
| 60 |
if (null !== $token) { |
| 61 |
$tokens[] = $token; |
| 62 |
$token = null; |
| 63 |
} |
| 64 |
} elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, 0, $cursor)) { |
| 65 |
$token .= $match[1].$match[2].stripcslashes(str_replace(['"\'', '\'"', '\'\'', '""'], '', substr($match[3], 1, -1))); |
| 66 |
} elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, 0, $cursor)) { |
| 67 |
$token .= stripcslashes(substr($match[0], 1, -1)); |
| 68 |
} elseif (preg_match('/'.self::REGEX_UNQUOTED_STRING.'/A', $input, $match, 0, $cursor)) { |
| 69 |
$token .= $match[1]; |
| 70 |
} else { |
| 71 |
// should never happen |
| 72 |
throw new InvalidArgumentException(sprintf('Unable to parse input near "... %s ...".', substr($input, $cursor, 10))); |
| 73 |
} |
| 74 |
|
| 75 |
$cursor += \strlen($match[0]); |
| 76 |
} |
| 77 |
|
| 78 |
if (null !== $token) { |
| 79 |
$tokens[] = $token; |
| 80 |
} |
| 81 |
|
| 82 |
return $tokens; |
| 83 |
} |
| 84 |
} |
| 85 |
|