diff --git a/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php b/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php index 2c29985ed..39ad48c23 100644 --- a/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php +++ b/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php @@ -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 @@ -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) { @@ -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); + } + } diff --git a/tests/Sniffs/TypeHints/data/disallowMixedTypeHintNoErrors.php b/tests/Sniffs/TypeHints/data/disallowMixedTypeHintNoErrors.php index 98ac42407..678c81db7 100644 --- a/tests/Sniffs/TypeHints/data/disallowMixedTypeHintNoErrors.php +++ b/tests/Sniffs/TypeHints/data/disallowMixedTypeHintNoErrors.php @@ -22,4 +22,28 @@ class Whatever */ private $suppressed; + /** + * @phpcsSuppress SlevomatCodingStandard.TypeHints.DisallowMixedTypeHint + * @var array + */ + #[Attribute1] + public function foo(array $mixed) + { + return $mixed === true; + } + +} + +class WhateverOverridden extends Whatever +{ + + /** + * @var array + */ + #[\Override] + public function foo(array $mixed) + { + return $mixed === false; + } + }