| 1 |
<?php declare(strict_types = 1); |
| 2 |
|
| 3 |
namespace PHPStan\PhpDocParser\Parser; |
| 4 |
|
| 5 |
use Exception; |
| 6 |
use PHPStan\PhpDocParser\Lexer\Lexer; |
| 7 |
use function assert; |
| 8 |
use function json_encode; |
| 9 |
use function sprintf; |
| 10 |
use const JSON_INVALID_UTF8_SUBSTITUTE; |
| 11 |
use const JSON_UNESCAPED_SLASHES; |
| 12 |
use const JSON_UNESCAPED_UNICODE; |
| 13 |
|
| 14 |
class ParserException extends Exception |
| 15 |
{ |
| 16 |
|
| 17 |
private string $currentTokenValue; |
| 18 |
|
| 19 |
private int $currentTokenType; |
| 20 |
|
| 21 |
private int $currentOffset; |
| 22 |
|
| 23 |
private int $expectedTokenType; |
| 24 |
|
| 25 |
private ?string $expectedTokenValue; |
| 26 |
|
| 27 |
private ?int $currentTokenLine; |
| 28 |
|
| 29 |
public function __construct( |
| 30 |
string $currentTokenValue, |
| 31 |
int $currentTokenType, |
| 32 |
int $currentOffset, |
| 33 |
int $expectedTokenType, |
| 34 |
?string $expectedTokenValue, |
| 35 |
?int $currentTokenLine |
| 36 |
) |
| 37 |
{ |
| 38 |
$this->currentTokenValue = $currentTokenValue; |
| 39 |
$this->currentTokenType = $currentTokenType; |
| 40 |
$this->currentOffset = $currentOffset; |
| 41 |
$this->expectedTokenType = $expectedTokenType; |
| 42 |
$this->expectedTokenValue = $expectedTokenValue; |
| 43 |
$this->currentTokenLine = $currentTokenLine; |
| 44 |
|
| 45 |
parent::__construct(sprintf( |
| 46 |
'Unexpected token %s, expected %s%s at offset %d%s', |
| 47 |
$this->formatValue($currentTokenValue), |
| 48 |
Lexer::TOKEN_LABELS[$expectedTokenType], |
| 49 |
$expectedTokenValue !== null ? sprintf(' (%s)', $this->formatValue($expectedTokenValue)) : '', |
| 50 |
$currentOffset, |
| 51 |
$currentTokenLine === null ? '' : sprintf(' on line %d', $currentTokenLine), |
| 52 |
)); |
| 53 |
} |
| 54 |
|
| 55 |
public function getCurrentTokenValue(): string |
| 56 |
{ |
| 57 |
return $this->currentTokenValue; |
| 58 |
} |
| 59 |
|
| 60 |
public function getCurrentTokenType(): int |
| 61 |
{ |
| 62 |
return $this->currentTokenType; |
| 63 |
} |
| 64 |
|
| 65 |
public function getCurrentOffset(): int |
| 66 |
{ |
| 67 |
return $this->currentOffset; |
| 68 |
} |
| 69 |
|
| 70 |
public function getExpectedTokenType(): int |
| 71 |
{ |
| 72 |
return $this->expectedTokenType; |
| 73 |
} |
| 74 |
|
| 75 |
public function getExpectedTokenValue(): ?string |
| 76 |
{ |
| 77 |
return $this->expectedTokenValue; |
| 78 |
} |
| 79 |
|
| 80 |
public function getCurrentTokenLine(): ?int |
| 81 |
{ |
| 82 |
return $this->currentTokenLine; |
| 83 |
} |
| 84 |
|
| 85 |
private function formatValue(string $value): string |
| 86 |
{ |
| 87 |
$json = json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_SUBSTITUTE); |
| 88 |
assert($json !== false); |
| 89 |
|
| 90 |
return $json; |
| 91 |
} |
| 92 |
|
| 93 |
} |