Skip to content

Commit 0a517c6

Browse files
committed
Fix method spacing.
1 parent fc7eab6 commit 0a517c6

File tree

1 file changed

+41
-6
lines changed

1 file changed

+41
-6
lines changed

PSR2R/Sniffs/WhiteSpace/MethodSpacingSniff.php

Lines changed: 41 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -44,22 +44,57 @@ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) {
4444
}
4545
}
4646

47-
if (empty($tokens[$parenthesisIndex]['parenthesis_closer'])) {
48-
return;
49-
}
50-
5147
$parenthesisEndIndex = $tokens[$parenthesisIndex]['parenthesis_closer'];
5248

5349
$braceStartIndex = $phpcsFile->findNext(T_WHITESPACE, ($parenthesisEndIndex + 1), null, true);
5450
if ($tokens[$braceStartIndex]['code'] !== T_OPEN_CURLY_BRACKET) {
5551
return;
5652
}
5753

58-
if ($braceStartIndex - $parenthesisEndIndex === 2 && $tokens[$braceStartIndex - 1]['content'] === ' ') {
54+
$braceEndIndex = $tokens[$braceStartIndex]['bracket_closer'];
55+
$nextContentIndex = $phpcsFile->findNext(T_WHITESPACE, ($braceStartIndex + 1), null, true);
56+
if ($nextContentIndex === $braceEndIndex) {
57+
$this->assertNoAdditionalNewlinesForEmptyBody($phpcsFile, $braceStartIndex, $braceEndIndex);
5958
return;
6059
}
6160

62-
//TODO: beginning and end of method: no newlines
61+
if ($tokens[$nextContentIndex]['line'] - $tokens[$braceStartIndex]['line'] > 1) {
62+
$error = 'There should be no extra newline at beginning of a method';
63+
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentAfterOpen');
64+
if ($fix === true) {
65+
$phpcsFile->fixer->replaceToken($braceStartIndex + 1, '');
66+
}
67+
}
68+
69+
$lastContentIndex = $phpcsFile->findPrevious(T_WHITESPACE, $braceEndIndex - 1, null, true);
70+
71+
if ($tokens[$braceEndIndex]['line'] - $tokens[$lastContentIndex]['line'] > 1) {
72+
$error = 'There should be no extra newline at the end of a method';
73+
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'ContentBeforeClose');
74+
if ($fix === true) {
75+
$phpcsFile->fixer->replaceToken($lastContentIndex + 1, '');
76+
}
77+
}
78+
}
79+
80+
/**
81+
* @param \PHP_CodeSniffer_File $phpcsFile
82+
* @param int $from
83+
* @param int $to
84+
*
85+
* @return void
86+
*/
87+
protected function assertNoAdditionalNewlinesForEmptyBody(PHP_CodeSniffer_File $phpcsFile, $from, $to) {
88+
$tokens = $phpcsFile->getTokens();
89+
90+
$startLine = $tokens[$from]['line'];
91+
$endLine = $tokens[$to]['line'];
92+
if ($endLine === $startLine + 2) {
93+
$error = 'There should be no extra newline in empty methods';
94+
if ($phpcsFile->addFixableError($error, $from, 'ContentEmpty')) {
95+
$phpcsFile->fixer->replaceToken($from + 1, '');
96+
}
97+
}
6398
}
6499

65100
}

0 commit comments

Comments
 (0)