PhpToken.php 2.1 KB

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