2015-08-17 17:00:26 -07:00
< ? php
/*
* This file is part of the Symfony package .
*
* ( c ) Fabien Potencier < fabien @ symfony . com >
*
* For the full copyright and license information , please view the LICENSE
* file that was distributed with this source code .
*/
namespace Symfony\Component\Console\Input ;
2016-04-20 09:56:34 -07:00
use Symfony\Component\Console\Exception\InvalidArgumentException ;
2015-08-17 17:00:26 -07:00
/**
* StringInput represents an input provided as a string .
*
* Usage :
*
* $input = new StringInput ( 'foo --bar="foobar"' );
*
* @ author Fabien Potencier < fabien @ symfony . com >
*/
class StringInput extends ArgvInput
{
const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)' ;
const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')' ;
/**
2018-11-23 12:29:20 +00:00
* @ param string $input A string representing the parameters from the CLI
2015-08-17 17:00:26 -07:00
*/
2018-11-23 12:29:20 +00:00
public function __construct ( $input )
2015-08-17 17:00:26 -07:00
{
2018-11-23 12:29:20 +00:00
parent :: __construct ( array ());
2015-08-17 17:00:26 -07:00
$this -> setTokens ( $this -> tokenize ( $input ));
}
/**
* Tokenizes a string .
*
* @ param string $input The input to tokenize
*
* @ return array An array of tokens
*
2016-04-20 09:56:34 -07:00
* @ throws InvalidArgumentException When unable to parse input ( should never happen )
2015-08-17 17:00:26 -07:00
*/
private function tokenize ( $input )
{
$tokens = array ();
2018-11-23 12:29:20 +00:00
$length = \strlen ( $input );
2015-08-17 17:00:26 -07:00
$cursor = 0 ;
while ( $cursor < $length ) {
if ( preg_match ( '/\s+/A' , $input , $match , null , $cursor )) {
} elseif ( preg_match ( '/([^="\'\s]+?)(=?)(' . self :: REGEX_QUOTED_STRING . '+)/A' , $input , $match , null , $cursor )) {
2018-11-23 12:29:20 +00:00
$tokens [] = $match [ 1 ] . $match [ 2 ] . stripcslashes ( str_replace ( array ( '"\'' , '\'"' , '\'\'' , '""' ), '' , substr ( $match [ 3 ], 1 , \strlen ( $match [ 3 ]) - 2 )));
2015-08-17 17:00:26 -07:00
} elseif ( preg_match ( '/' . self :: REGEX_QUOTED_STRING . '/A' , $input , $match , null , $cursor )) {
2018-11-23 12:29:20 +00:00
$tokens [] = stripcslashes ( substr ( $match [ 0 ], 1 , \strlen ( $match [ 0 ]) - 2 ));
2015-08-17 17:00:26 -07:00
} elseif ( preg_match ( '/' . self :: REGEX_STRING . '/A' , $input , $match , null , $cursor )) {
$tokens [] = stripcslashes ( $match [ 1 ]);
} else {
// should never happen
2016-04-20 09:56:34 -07:00
throw new InvalidArgumentException ( sprintf ( 'Unable to parse input near "... %s ..."' , substr ( $input , $cursor , 10 )));
2015-08-17 17:00:26 -07:00
}
2018-11-23 12:29:20 +00:00
$cursor += \strlen ( $match [ 0 ]);
2015-08-17 17:00:26 -07:00
}
return $tokens ;
}
}