2013-09-01 20:41:49 +01: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\ExpressionLanguage ;
/**
* Represents a token stream .
*
* @ author Fabien Potencier < fabien @ symfony . com >
*/
class TokenStream
{
public $current ;
private $tokens ;
2013-11-10 17:06:47 +00:00
private $position = 0 ;
2017-03-31 09:01:13 +01:00
private $expression ;
2013-09-01 20:41:49 +01:00
/**
* Constructor .
*
2017-03-31 09:01:13 +01:00
* @ param array $tokens An array of tokens
* @ param string $expression
2013-09-01 20:41:49 +01:00
*/
2017-03-31 09:01:13 +01:00
public function __construct ( array $tokens , $expression = '' )
2013-09-01 20:41:49 +01:00
{
$this -> tokens = $tokens ;
$this -> current = $tokens [ 0 ];
2017-03-31 09:01:13 +01:00
$this -> expression = $expression ;
2013-09-01 20:41:49 +01:00
}
/**
* Returns a string representation of the token stream .
*
* @ return string
*/
public function __toString ()
{
return implode ( " \n " , $this -> tokens );
}
/**
* Sets the pointer to the next token and returns the old one .
*/
public function next ()
{
if ( ! isset ( $this -> tokens [ $this -> position ])) {
2017-03-31 09:01:13 +01:00
throw new SyntaxError ( 'Unexpected end of expression' , $this -> current -> cursor , $this -> expression );
2013-09-01 20:41:49 +01:00
}
++ $this -> position ;
$this -> current = $this -> tokens [ $this -> position ];
}
/**
* Tests a token .
2016-09-02 19:13:13 +01:00
*
* @ param array | int $type The type to test
* @ param string | null $value The token value
* @ param string | null $message The syntax error message
2013-09-01 20:41:49 +01:00
*/
public function expect ( $type , $value = null , $message = null )
{
$token = $this -> current ;
if ( ! $token -> test ( $type , $value )) {
2017-03-31 09:01:13 +01:00
throw new SyntaxError ( sprintf ( '%sUnexpected token "%s" of value "%s" ("%s" expected%s)' , $message ? $message . '. ' : '' , $token -> type , $token -> value , $type , $value ? sprintf ( ' with value "%s"' , $value ) : '' ), $token -> cursor , $this -> expression );
2013-09-01 20:41:49 +01:00
}
$this -> next ();
}
/**
2015-08-24 07:53:33 +01:00
* Checks if end of stream was reached .
2013-09-01 20:41:49 +01:00
*
* @ return bool
*/
public function isEOF ()
{
return $this -> current -> type === Token :: EOF_TYPE ;
}
2017-03-31 09:01:13 +01:00
/**
* @ internal
*
* @ return string
*/
public function getExpression ()
{
return $this -> expression ;
}
2013-09-01 20:41:49 +01:00
}