TokenStream.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\ExpressionLanguage;
  11. /**
  12. * Represents a token stream.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class TokenStream
  17. {
  18. public $current;
  19. private $tokens;
  20. private $position = 0;
  21. private $expression;
  22. /**
  23. * @param array $tokens An array of tokens
  24. * @param string $expression
  25. */
  26. public function __construct(array $tokens, $expression = '')
  27. {
  28. $this->tokens = $tokens;
  29. $this->current = $tokens[0];
  30. $this->expression = $expression;
  31. }
  32. /**
  33. * Returns a string representation of the token stream.
  34. *
  35. * @return string
  36. */
  37. public function __toString()
  38. {
  39. return implode("\n", $this->tokens);
  40. }
  41. /**
  42. * Sets the pointer to the next token and returns the old one.
  43. */
  44. public function next()
  45. {
  46. ++$this->position;
  47. if (!isset($this->tokens[$this->position])) {
  48. throw new SyntaxError('Unexpected end of expression', $this->current->cursor, $this->expression);
  49. }
  50. $this->current = $this->tokens[$this->position];
  51. }
  52. /**
  53. * Tests a token.
  54. *
  55. * @param array|int $type The type to test
  56. * @param string|null $value The token value
  57. * @param string|null $message The syntax error message
  58. */
  59. public function expect($type, $value = null, $message = null)
  60. {
  61. $token = $this->current;
  62. if (!$token->test($type, $value)) {
  63. 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);
  64. }
  65. $this->next();
  66. }
  67. /**
  68. * Checks if end of stream was reached.
  69. *
  70. * @return bool
  71. */
  72. public function isEOF()
  73. {
  74. return Token::EOF_TYPE === $this->current->type;
  75. }
  76. /**
  77. * @internal
  78. *
  79. * @return string
  80. */
  81. public function getExpression()
  82. {
  83. return $this->expression;
  84. }
  85. }