TokenStream.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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 $message The syntax error message
  53. */
  54. public function expect($type, string $value = null, string $message = null)
  55. {
  56. $token = $this->current;
  57. if (!$token->test($type, $value)) {
  58. 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);
  59. }
  60. $this->next();
  61. }
  62. /**
  63. * Checks if end of stream was reached.
  64. *
  65. * @return bool
  66. */
  67. public function isEOF()
  68. {
  69. return Token::EOF_TYPE === $this->current->type;
  70. }
  71. /**
  72. * @internal
  73. */
  74. public function getExpression(): string
  75. {
  76. return $this->expression;
  77. }
  78. }