Skip to content

Commit

Permalink
Fix nullable constructor promotion detection
Browse files Browse the repository at this point in the history
  • Loading branch information
sirbrillig committed Apr 13, 2024
1 parent c019db0 commit b96d59d
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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 b96d59d

Please sign in to comment.