Token.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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.
  13. *
  14. * @author Fabien Potencier <fabien@symfony.com>
  15. */
  16. class Token
  17. {
  18. public $value;
  19. public $type;
  20. public $cursor;
  21. public const EOF_TYPE = 'end of expression';
  22. public const NAME_TYPE = 'name';
  23. public const NUMBER_TYPE = 'number';
  24. public const STRING_TYPE = 'string';
  25. public const OPERATOR_TYPE = 'operator';
  26. public const PUNCTUATION_TYPE = 'punctuation';
  27. /**
  28. * @param string $type The type of the token (self::*_TYPE)
  29. * @param string|int|float|null $value The token value
  30. * @param int $cursor The cursor position in the source
  31. */
  32. public function __construct(string $type, $value, ?int $cursor)
  33. {
  34. $this->type = $type;
  35. $this->value = $value;
  36. $this->cursor = $cursor;
  37. }
  38. /**
  39. * Returns a string representation of the token.
  40. *
  41. * @return string A string representation of the token
  42. */
  43. public function __toString()
  44. {
  45. return sprintf('%3d %-11s %s', $this->cursor, strtoupper($this->type), $this->value);
  46. }
  47. /**
  48. * Tests the current token for a type and/or a value.
  49. *
  50. * @param string $type The type to test
  51. *
  52. * @return bool
  53. */
  54. public function test($type, string $value = null)
  55. {
  56. return $this->type === $type && (null === $value || $this->value == $value);
  57. }
  58. }