|
9 | 9 |
|
10 | 10 | use PHP_CodeSniffer\Files\File; |
11 | 11 | use PHP_CodeSniffer\Sniffs\Sniff; |
| 12 | +use PHP_CodeSniffer\Util\Tokens; |
12 | 13 |
|
13 | 14 | /** |
14 | 15 | * Sniff to check if functions have a return type. |
@@ -45,10 +46,26 @@ public function process( File $phpcsFile, $stackPtr ): void |
45 | 46 | return; |
46 | 47 | } |
47 | 48 |
|
48 | | - // Get return type. |
49 | | - $next_return_type = $phpcsFile->findNext( [ T_COLON ], $stackPtr ); |
| 49 | + // Find the closing parenthesis of the function parameters. |
| 50 | + $open_parenthesis = $phpcsFile->findNext( [ T_OPEN_PARENTHESIS ], $stackPtr ); |
50 | 51 |
|
51 | | - if ( ! is_int( $next_return_type ) || $tokens[ $next_return_type ]['line'] !== $tokens[ $stackPtr ]['line'] ) { |
| 52 | + if ( false === $open_parenthesis || ! isset( $tokens[ $open_parenthesis ]['parenthesis_closer'] ) ) { |
| 53 | + return; |
| 54 | + } |
| 55 | + |
| 56 | + $close_parenthesis = $tokens[ $open_parenthesis ]['parenthesis_closer']; |
| 57 | + |
| 58 | + // Find the opening brace of the function body (or semicolon for abstract/interface methods). |
| 59 | + $scope_opener = $phpcsFile->findNext( array_merge( Tokens::$scopeOpeners, [ T_SEMICOLON ] ), $close_parenthesis ); |
| 60 | + |
| 61 | + if ( false === $scope_opener ) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + // Check if there's a colon between the closing parenthesis and the scope opener. |
| 66 | + $return_type_colon = $phpcsFile->findNext( [ T_COLON ], $close_parenthesis, $scope_opener ); |
| 67 | + |
| 68 | + if ( false === $return_type_colon ) { |
52 | 69 | $phpcsFile->addWarningOnLine( |
53 | 70 | 'Functions must have a return type.', |
54 | 71 | $tokens[ $stackPtr ]['line'], |
|
0 commit comments