Skip to content

Commit

Permalink
DisallowMixedTypeHintSniff does not report error when attribute #[Ove…
Browse files Browse the repository at this point in the history
…rride] is presented.
  • Loading branch information
kamil-zacek authored and kukulich committed Nov 5, 2024
1 parent c72b104 commit 7ed8496
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,15 @@
use PHP_CodeSniffer\Sniffs\Sniff;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use SlevomatCodingStandard\Helpers\AnnotationHelper;
use SlevomatCodingStandard\Helpers\Attribute;
use SlevomatCodingStandard\Helpers\AttributeHelper;
use SlevomatCodingStandard\Helpers\SuppressHelper;
use SlevomatCodingStandard\Helpers\TokenHelper;
use function array_map;
use function in_array;
use function sprintf;
use function strtolower;
use const T_ATTRIBUTE;
use const T_DOC_COMMENT_OPEN_TAG;

class DisallowMixedTypeHintSniff implements Sniff
Expand Down Expand Up @@ -42,6 +48,10 @@ public function process(File $phpcsFile, $docCommentOpenPointer): void
return;
}

if ($this->targetHasOverrideAttribute($phpcsFile, $docCommentOpenPointer)) {
return;
}

$annotations = AnnotationHelper::getAnnotations($phpcsFile, $docCommentOpenPointer);

foreach ($annotations as $annotation) {
Expand Down Expand Up @@ -69,4 +79,23 @@ private function getSniffName(string $sniffName): string
return sprintf('%s.%s', self::NAME, $sniffName);
}

private function targetHasOverrideAttribute(File $phpcsFile, int $docCommentOpenPointer): bool
{
$tokens = $phpcsFile->getTokens();
$nextPointer = TokenHelper::findNextEffective($phpcsFile, $docCommentOpenPointer + 1);

if ($tokens[$nextPointer]['code'] !== T_ATTRIBUTE) {
return false;
}

$attributeNames = array_map(
static function (Attribute $name): string {
return $name->getName();
},
AttributeHelper::getAttributes($phpcsFile, $nextPointer)
);

return in_array('Override', $attributeNames, true) || in_array('\Override', $attributeNames, true);
}

}
24 changes: 24 additions & 0 deletions tests/Sniffs/TypeHints/data/disallowMixedTypeHintNoErrors.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,28 @@ class Whatever
*/
private $suppressed;

/**
* @phpcsSuppress SlevomatCodingStandard.TypeHints.DisallowMixedTypeHint
* @var array<mixed>
*/
#[Attribute1]
public function foo(array $mixed)
{
return $mixed === true;
}

}

class WhateverOverridden extends Whatever
{

/**
* @var array<mixed>
*/
#[\Override]
public function foo(array $mixed)
{
return $mixed === false;
}

}

0 comments on commit 7ed8496

Please sign in to comment.