Skip to content

Commit

Permalink
Allow asserting the type of $this
Browse files Browse the repository at this point in the history
  • Loading branch information
ekisu authored and ondrejmirtes committed Sep 7, 2023
1 parent e540adc commit 3510b0a
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 14 deletions.
4 changes: 1 addition & 3 deletions src/Parser/PhpDocParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -1127,15 +1127,13 @@ private function parseAssertParameter(TokenIterator $tokens): array
{
if ($tokens->isCurrentTokenType(Lexer::TOKEN_THIS_VARIABLE)) {
$parameter = '$this';
$requirePropertyOrMethod = true;
$tokens->next();
} else {
$parameter = $tokens->currentTokenValue();
$requirePropertyOrMethod = false;
$tokens->consumeTokenType(Lexer::TOKEN_VARIABLE);
}

if ($requirePropertyOrMethod || $tokens->isCurrentTokenType(Lexer::TOKEN_ARROW)) {
if ($tokens->isCurrentTokenType(Lexer::TOKEN_ARROW)) {
$tokens->consumeTokenType(Lexer::TOKEN_ARROW);

$propertyOrMethod = $tokens->currentTokenValue();
Expand Down
57 changes: 46 additions & 11 deletions tests/PHPStan/Parser/PhpDocParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4563,21 +4563,56 @@ public function provideAssertTagsData(): Iterator
];

yield [
'invalid $this',
'OK $this',
'/** @phpstan-assert Type $this */',
new PhpDocNode([
new PhpDocTagNode(
'@phpstan-assert',
new InvalidTagValueNode(
'Type $this',
new ParserException(
'*/',
Lexer::TOKEN_CLOSE_PHPDOC,
31,
Lexer::TOKEN_ARROW,
null,
1
)
new AssertTagValueNode(
new IdentifierTypeNode('Type'),
'$this',
false,
''
)
),
]),
];

yield [
'OK $this with description',
'/** @phpstan-assert Type $this assert Type to $this */',
new PhpDocNode([
new PhpDocTagNode(
'@phpstan-assert',
new AssertTagValueNode(
new IdentifierTypeNode('Type'),
'$this',
false,
'assert Type to $this'
)
),
]),
];

yield [
'OK $this with generic type',
'/** @phpstan-assert GenericType<T> $this */',
new PhpDocNode([
new PhpDocTagNode(
'@phpstan-assert',
new AssertTagValueNode(
new GenericTypeNode(
new IdentifierTypeNode('GenericType'),
[
new IdentifierTypeNode('T'),
],
[
GenericTypeNode::VARIANCE_INVARIANT,
]
),
'$this',
false,
''
)
),
]),
Expand Down

0 comments on commit 3510b0a

Please sign in to comment.