55use PHP_CodeSniffer \Files \File ;
66use PHP_CodeSniffer \Sniffs \Sniff ;
77use SlevomatCodingStandard \Helpers \FixerHelper ;
8+ use SlevomatCodingStandard \Helpers \FunctionHelper ;
89use SlevomatCodingStandard \Helpers \SniffSettingsHelper ;
910use SlevomatCodingStandard \Helpers \TokenHelper ;
1011use function preg_match ;
@@ -21,6 +22,7 @@ class ArrowFunctionDeclarationSniff implements Sniff
2122 public const CODE_INCORRECT_SPACES_AFTER_KEYWORD = 'IncorrectSpacesAfterKeyword ' ;
2223 public const CODE_INCORRECT_SPACES_BEFORE_ARROW = 'IncorrectSpacesBeforeArrow ' ;
2324 public const CODE_INCORRECT_SPACES_AFTER_ARROW = 'IncorrectSpacesAfterArrow ' ;
25+ public const CODE_DISALLOWED_RETURN_TYPE_HINT = 'DisallowedReturnTypeHint ' ;
2426
2527 public int $ spacesCountAfterKeyword = 1 ;
2628
@@ -30,6 +32,8 @@ class ArrowFunctionDeclarationSniff implements Sniff
3032
3133 public bool $ allowMultiLine = false ;
3234
35+ public bool $ disallowReturnTypeHint = false ;
36+
3337 /**
3438 * @return array<int, (int|string)>
3539 */
@@ -50,10 +54,46 @@ public function process(File $phpcsFile, int $arrowFunctionPointer): void
5054
5155 $ arrowPointer = TokenHelper::findNext ($ phpcsFile , T_FN_ARROW , $ arrowFunctionPointer );
5256
57+ $ this ->checkReturnTypeHint ($ phpcsFile , $ arrowFunctionPointer , $ arrowPointer );
58+
5359 $ this ->checkSpacesBeforeArrow ($ phpcsFile , $ arrowPointer );
5460 $ this ->checkSpacesAfterArrow ($ phpcsFile , $ arrowPointer );
5561 }
5662
63+ private function checkReturnTypeHint (File $ phpcsFile , int $ arrowFunctionPointer , int $ arrowPointer ): void
64+ {
65+ if (!$ this ->disallowReturnTypeHint ) {
66+ return ;
67+ }
68+
69+ $ returnTypeHint = FunctionHelper::findReturnTypeHint ($ phpcsFile , $ arrowFunctionPointer );
70+ if ($ returnTypeHint === null ) {
71+ return ;
72+ }
73+
74+ $ fix = $ phpcsFile ->addFixableError (
75+ 'Arrow function must not have return type hint. ' ,
76+ $ returnTypeHint ->getStartPointer (),
77+ self ::CODE_DISALLOWED_RETURN_TYPE_HINT ,
78+ );
79+ if (!$ fix ) {
80+ return ;
81+ }
82+
83+ $ colonPointer = TokenHelper::findPreviousEffective ($ phpcsFile , $ returnTypeHint ->getStartPointer () - 1 );
84+
85+ $ pointerBeforeColon = TokenHelper::findPreviousEffective ($ phpcsFile , $ colonPointer - 1 );
86+
87+ $ phpcsFile ->fixer ->beginChangeset ();
88+ FixerHelper::removeBetween ($ phpcsFile , $ pointerBeforeColon , $ arrowPointer );
89+
90+ if ($ this ->spacesCountBeforeArrow > 0 ) {
91+ FixerHelper::addBefore ($ phpcsFile , $ arrowPointer , str_repeat (' ' , $ this ->spacesCountBeforeArrow ));
92+ }
93+
94+ $ phpcsFile ->fixer ->endChangeset ();
95+ }
96+
5797 private function checkSpacesAfterKeyword (File $ phpcsFile , int $ arrowFunctionPointer ): void
5898 {
5999 $ pointerAfter = TokenHelper::findNextNonWhitespace ($ phpcsFile , $ arrowFunctionPointer + 1 );
0 commit comments