Skip to content

Commit 7171f41

Browse files
authored
Merge pull request #2 from KelvinJardin/OpeningBraceSniff
Opening brace sniff
2 parents b2b5acc + 2abf435 commit 7171f41

File tree

2 files changed

+63
-1
lines changed

2 files changed

+63
-1
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
namespace DatacodeStandard\Sniffs\Classes;
6+
7+
use PHP_CodeSniffer\Sniffs\Sniff;
8+
use PHP_CodeSniffer\Files\File;
9+
10+
/**
11+
* Ensures no blank line after class open closure
12+
*/
13+
class OpeningBraceSniff implements Sniff {
14+
15+
public function register() {
16+
return [
17+
T_CLASS,
18+
];
19+
}
20+
21+
/**
22+
* Processes this test, when one of its tokens is encountered.
23+
*
24+
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
25+
* @param integer $stackPtr The position of the current token in the stack passed in $tokens.
26+
*
27+
* @return int
28+
*/
29+
public function process(File $phpcsFile, $stackPtr) {
30+
$tokens = $phpcsFile->getTokens();
31+
$opener = $tokens[$stackPtr]['scope_opener'];
32+
$nextAfterOpen = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), null, true);
33+
34+
if ($tokens[$nextAfterOpen]['line'] > ($tokens[$opener]['line'] + 1)) {
35+
// Opening brace is on a new line, so there must be no blank line after it.
36+
$error = 'Opening brace must not be succeeded by a blank line';
37+
$fix = $phpcsFile->addFixableError($error, $opener, 'OpenBraceFollowedByBlankLine');
38+
39+
if ($fix === true) {
40+
$phpcsFile->fixer->beginChangeset();
41+
for ($x = ($opener + 1); $x < $nextAfterOpen; $x++) {
42+
if ($tokens[$x]['line'] === $tokens[$opener]['line']) {
43+
// Maintain existing newline.
44+
continue;
45+
}
46+
47+
if ($tokens[$x]['line'] === $tokens[$nextAfterOpen]['line']) {
48+
// Maintain existing indent.
49+
break;
50+
}
51+
52+
$phpcsFile->fixer->replaceToken($x, '');
53+
}
54+
55+
$phpcsFile->fixer->endChangeset();
56+
}
57+
}
58+
59+
return ($phpcsFile->numTokens + 1);
60+
}
61+
62+
}

composer.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "datacodetech/phpcs-ruleset",
3-
"version": "2.0.0",
3+
"version": "2.1.0",
44
"type": "library",
55
"license": "MIT",
66
"description": "phpcs ruleset used for all PHP projects",

0 commit comments

Comments
 (0)