PhpToken.php 2.2 KB

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