1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Polyfill\Php80;
13
14/**
15 * @author Fedonyuk Anton <info@ensostudio.ru>
16 *
17 * @internal
18 */
19class PhpToken implements \Stringable
20{
21    /**
22     * @var int
23     */
24    public $id;
25
26    /**
27     * @var string
28     */
29    public $text;
30
31    /**
32     * @var int
33     */
34    public $line;
35
36    /**
37     * @var int
38     */
39    public $pos;
40
41    public function __construct(int $id, string $text, int $line = -1, int $position = -1)
42    {
43        $this->id = $id;
44        $this->text = $text;
45        $this->line = $line;
46        $this->pos = $position;
47    }
48
49    public function getTokenName(): ?string
50    {
51        if ('UNKNOWN' === $name = token_name($this->id)) {
52            $name = \strlen($this->text) > 1 || \ord($this->text) < 32 ? null : $this->text;
53        }
54
55        return $name;
56    }
57
58    /**
59     * @param int|string|array $kind
60     */
61    public function is($kind): bool
62    {
63        foreach ((array) $kind as $value) {
64            if (\in_array($value, [$this->id, $this->text], true)) {
65                return true;
66            }
67        }
68
69        return false;
70    }
71
72    public function isIgnorable(): bool
73    {
74        return \in_array($this->id, [\T_WHITESPACE, \T_COMMENT, \T_DOC_COMMENT, \T_OPEN_TAG], true);
75    }
76
77    public function __toString(): string
78    {
79        return (string) $this->text;
80    }
81
82    /**
83     * @return static[]
84     */
85    public static function tokenize(string $code, int $flags = 0): array
86    {
87        $line = 1;
88        $position = 0;
89        $tokens = token_get_all($code, $flags);
90        foreach ($tokens as $index => $token) {
91            if (\is_string($token)) {
92                $id = \ord($token);
93                $text = $token;
94            } else {
95                [$id, $text, $line] = $token;
96            }
97            $tokens[$index] = new static($id, $text, $line, $position);
98            $position += \strlen($text);
99        }
100
101        return $tokens;
102    }
103}
104