Skip to content

Commit

Permalink
SlevomatCodingStandard.TypeHints.ParameterTypeHint: callable is not v…
Browse files Browse the repository at this point in the history
…alid type for property promotion
  • Loading branch information
kukulich committed Jun 23, 2023
1 parent 0ae2e35 commit 4166003
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
30 changes: 30 additions & 0 deletions SlevomatCodingStandard/Sniffs/TypeHints/ParameterTypeHintSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Util\Tokens;
use PHPStan\PhpDocParser\Ast\PhpDoc\ParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\TypelessParamTagValueNode;
use PHPStan\PhpDocParser\Ast\PhpDoc\VarTagValueNode;
Expand Down Expand Up @@ -44,11 +45,13 @@
use function sprintf;
use function strtolower;
use const T_BITWISE_AND;
use const T_COMMA;
use const T_DOC_COMMENT_CLOSE_TAG;
use const T_DOC_COMMENT_OPEN_TAG;
use const T_DOC_COMMENT_STAR;
use const T_ELLIPSIS;
use const T_FUNCTION;
use const T_OPEN_PARENTHESIS;
use const T_VARIABLE;

class ParameterTypeHintSniff implements Sniff
Expand Down Expand Up @@ -162,7 +165,30 @@ private function checkTypeHints(
})
);

$tokens = $phpcsFile->getTokens();

$isConstructor = FunctionHelper::isMethod($phpcsFile, $functionPointer)
&& strtolower(FunctionHelper::getName($phpcsFile, $functionPointer)) === '__construct';

foreach ($parametersWithoutTypeHint as $parameterName) {
$isPropertyPromotion = false;

if ($isConstructor) {
$parameterPointer = TokenHelper::findNextContent(
$phpcsFile,
T_VARIABLE,
$parameterName,
$tokens[$functionPointer]['parenthesis_opener'],
$tokens[$functionPointer]['parenthesis_closer']
);

$pointerBeforeParameter = TokenHelper::findPrevious($phpcsFile, [T_COMMA, T_OPEN_PARENTHESIS], $parameterPointer - 1);

$visibilityPointer = TokenHelper::findNextEffective($phpcsFile, $pointerBeforeParameter + 1);

$isPropertyPromotion = in_array($tokens[$visibilityPointer]['code'], Tokens::$scopeModifiers, true);
}

if (
!array_key_exists($parameterName, $parametersAnnotations)
|| $parametersAnnotations[$parameterName]->getValue() instanceof TypelessParamTagValueNode
Expand Down Expand Up @@ -313,6 +339,10 @@ private function checkTypeHints(
continue;
}

if ($isPropertyPromotion && $typeHint === 'callable') {
continue 2;
}

if (!TypeHintHelper::isValidTypeHint(
$typeHint,
$this->enableObjectTypeHint,
Expand Down
4 changes: 3 additions & 1 deletion tests/Sniffs/TypeHints/data/parameterTypeHintNoErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,9 @@ public function __construct(
/** @var array<int, string> */
public array $promoted,
/** @phpstan-var array<int, string> */
public array $promoted2
public array $promoted2,
/** @var callable */
private $callable,
)
{

Expand Down

0 comments on commit 4166003

Please sign in to comment.