Skip to content

Commit

Permalink
Fix nullable constructor promotion detection (#321)
Browse files Browse the repository at this point in the history
  • Loading branch information
sirbrillig committed Apr 13, 2024
1 parent c019db0 commit ca242a0
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Tests/VariableAnalysisSniff/VariableAnalysisTest.php
Expand Up @@ -194,6 +194,8 @@ public function testClassWithMembersWarnings()
115,
116,
174,
202,
203,
];
$this->assertSame($expectedWarnings, $lines);
}
Expand Down
27 changes: 27 additions & 0 deletions Tests/VariableAnalysisSniff/fixtures/ClassWithMembersFixture.php
Expand Up @@ -195,3 +195,30 @@ public function getMessage(): string {
return $this->message;
}
}

class ClassWithNullableConstructorPromotion {
public function __construct(
public ?string $name = 'Brent',
$unused, // Unused variable $unused
?string $unused2, // Unused variable $unused2
public ?string $role,
private ?string $role2,
protected ?string $role3,
public $nickname,
private $nickname2,
protected $nickname3
) {
}
}

class ClassWithReadonlyNullableConstructorPromotion {
public function __construct(
private readonly ?string $message,
private readonly $name,
public readonly ?bool $key
) {}

public function getMessage(): string {
return $this->message;
}
}
9 changes: 9 additions & 0 deletions VariableAnalysis/Lib/Helpers.php
Expand Up @@ -1561,6 +1561,15 @@ public static function isConstructorPromotion(File $phpcsFile, $stackPtr)
return false;
}
$prev2Token = $tokens[$prev2Index];
// If the token that might be a visibility keyword is a nullable typehint,
// ignore it and move back one token further eg: `public ?boolean $foobar`.
if ($prev2Token['code'] === 'PHPCS_T_NULLABLE') {
$prev2Index = $phpcsFile->findPrevious(Tokens::$emptyTokens, ($prev2Index - 1), $functionIndex, true);
if (! is_int($prev2Index)) {
return false;
}
}
$prev2Token = $tokens[$prev2Index];
if (in_array($prev2Token['code'], Tokens::$scopeModifiers, true)) {
return true;
}
Expand Down

0 comments on commit ca242a0

Please sign in to comment.