TokenStream.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. public function __construct(array $tokens, string $expression = '')
  23. {
  24. $this->tokens = $tokens;
  25. $this->current = $tokens[0];
  26. $this->expression = $expression;
  27. }
  28. /**
  29. * Returns a string representation of the token stream.
  30. *
  31. * @return string
  32. */
  33. public function __toString()
  34. {
  35. return implode("\n", $this->tokens);
  36. }
  37. /**
  38. * Sets the pointer to the next token and returns the old one.
  39. */
  40. public function next()
  41. {
  42. ++$this->position;
  43. if (!isset($this->tokens[$this->position])) {
  44. throw new SyntaxError('Unexpected end of expression.', $this->current->cursor, $this->expression);
  45. }
  46. $this->current = $this->tokens[$this->position];
  47. }
  48. /**
  49. * Tests a token.
  50. *
  51. * @param array|int $type The type to test
  52. * @param string|null $value The token value
  53. * @param string|null $message The syntax error message
  54. */
  55. public function expect($type, $value = null, $message = null)
  56. {
  57. $token = $this->current;
  58. if (!$token->test($type, $value)) {
  59. 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);
  60. }
  61. $this->next();
  62. }
  63. /**
  64. * Checks if end of stream was reached.
  65. *
  66. * @return bool
  67. */
  68. public function isEOF()
  69. {
  70. return Token::EOF_TYPE === $this->current->type;
  71. }
  72. /**
  73. * @internal
  74. */
  75. public function getExpression(): string
  76. {
  77. return $this->expression;
  78. }
  79. }