From 35966896ac821f78f386676d0263794cdf086243 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kamil=20=C5=BD=C3=A1=C4=8Dek?= Date: Mon, 9 Sep 2024 13:07:44 +0200 Subject: [PATCH] DisallowMixedTypeHintSniff does not report error when attribute #[Override] is presented. --- .../TypeHints/DisallowMixedTypeHintSniff.php | 24 +++++++++++++++++++ .../data/disallowMixedTypeHintNoErrors.php | 23 ++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php b/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php index 2c29985ed..8f8984e71 100644 --- a/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php +++ b/SlevomatCodingStandard/Sniffs/TypeHints/DisallowMixedTypeHintSniff.php @@ -6,7 +6,10 @@ 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 sprintf; use function strtolower; use const T_DOC_COMMENT_OPEN_TAG; @@ -42,6 +45,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 +76,21 @@ 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 fn (Attribute $name): string => $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..3545efda9 100644 --- a/tests/Sniffs/TypeHints/data/disallowMixedTypeHintNoErrors.php +++ b/tests/Sniffs/TypeHints/data/disallowMixedTypeHintNoErrors.php @@ -22,4 +22,27 @@ class Whatever */ private $suppressed; + /** + * @phpcsSuppress SlevomatCodingStandard.TypeHints.DisallowMixedTypeHint + * @var array + */ + public function foo(array $mixed) + { + return $mixed === true; + } + +} + +class WhateverOverridden extends Whatever +{ + + /** + * @var array + */ + #[\Override] + public function foo(array $mixed) + { + return $mixed === false; + } + }