PhpToken.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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\Polyfill\Php80;
  11. /**
  12. * @author Fedonyuk Anton <info@ensostudio.ru>
  13. *
  14. * @internal
  15. */
  16. class PhpToken
  17. {
  18. /**
  19. * @var int
  20. */
  21. public $id;
  22. /**
  23. * @var string
  24. */
  25. public $text;
  26. /**
  27. * @var int
  28. */
  29. public $line;
  30. /**
  31. * @var int
  32. */
  33. public $pos;
  34. /**
  35. * @param int $id
  36. * @param string $text
  37. * @param int $line
  38. * @param int $position
  39. */
  40. public function __construct($id, $text, $line = -1, $position = -1)
  41. {
  42. $this->id = $id;
  43. $this->text = $text;
  44. $this->line = $line;
  45. $this->pos = $position;
  46. }
  47. public function getTokenName()
  48. {
  49. if ('UNKNOWN' === $name = token_name($this->id)) {
  50. $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text;
  51. }
  52. return $name;
  53. }
  54. /**
  55. * @param int|string|array $kind
  56. */
  57. public function is($kind)
  58. {
  59. foreach ((array) $kind as $value) {
  60. if (\in_array($value, [$this->id, $this->text], true)) {
  61. return true;
  62. }
  63. }
  64. return false;
  65. }
  66. public function isIgnorable()
  67. {
  68. return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true);
  69. }
  70. public function __toString()
  71. {
  72. return (string) $this->text;
  73. }
  74. /**
  75. * @return static[]
  76. * @param string $code
  77. * @param int $flags
  78. */
  79. public static function tokenize($code, $flags = 0)
  80. {
  81. $line = 1;
  82. $position = 0;
  83. $tokens = token_get_all($code, $flags);
  84. foreach ($tokens as $index => $token) {
  85. if (\is_string($token)) {
  86. $id = \ord($token);
  87. $text = $token;
  88. } else {
  89. [$id, $text, $line] = $token;
  90. }
  91. $tokens[$index] = new static($id, $text, $line, $position);
  92. $position += \strlen($text);
  93. }
  94. return $tokens;
  95. }
  96. }