Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions src/Parser/TokenIterator.php
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ class TokenIterator

private ?string $newline = null;

/** @var list<int>|null */
private ?array $offsets = null;

/**
* @param list<array{string, int, int}> $tokens
*/
Expand Down Expand Up @@ -81,12 +84,16 @@ public function currentTokenType(): int

public function currentTokenOffset(): int
{
$offset = 0;
for ($i = 0; $i < $this->index; $i++) {
$offset += strlen($this->tokens[$i][Lexer::VALUE_OFFSET]);
if ($this->offsets === null) {
$offset = 0;
$this->offsets = [];
foreach ($this->tokens as $token) {
$this->offsets[] = $offset;
$offset += strlen($token[Lexer::VALUE_OFFSET]);
}
}

return $offset;
return $this->offsets[$this->index];
}

public function currentTokenLine(): int
Expand Down
17 changes: 17 additions & 0 deletions tests/PHPStan/Parser/TokenIteratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use PHPStan\PhpDocParser\Lexer\Lexer;
use PHPStan\PhpDocParser\ParserConfig;
use PHPUnit\Framework\TestCase;
use function strlen;
use function substr;
use const PHP_EOL;

class TokenIteratorTest extends TestCase
Expand Down Expand Up @@ -57,4 +59,19 @@ public function testGetDetectedNewline(string $phpDoc, ?string $expectedNewline)
$this->assertSame($expectedNewline, $tokens->getDetectedNewline());
}

public function testCurrentTokenOffset(): void
{
$lexer = new Lexer(new ParserConfig([]));
$phpDoc = "/**\n * @param array{size?: 'sm'|'md', icon: Icon} \$a\n */";
$tokens = new TokenIterator($lexer->tokenize($phpDoc));

do {
$this->assertSame($tokens->currentTokenValue(), substr($phpDoc, $tokens->currentTokenOffset(), strlen($tokens->currentTokenValue())));
$this->assertSame(strlen($tokens->getContentBetween(0, $tokens->currentTokenIndex())), $tokens->currentTokenOffset());
$tokens->next();
} while (!$tokens->isCurrentTokenType(Lexer::TOKEN_END));

$this->assertSame(strlen($phpDoc), $tokens->currentTokenOffset());
}

}
Loading