Skip to content

Opening brace sniff #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 26, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions DatacodeStandard/Sniffs/Classes/OpeningBraceSniff.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<?php

declare(strict_types=1);

namespace DatacodeStandard\Sniffs\Classes;

use PHP_CodeSniffer\Sniffs\Sniff;
use PHP_CodeSniffer\Files\File;

/**
* Ensures no blank line after class open closure
*/
class OpeningBraceSniff implements Sniff {

public function register() {
return [
T_CLASS,
];
}

/**
* Processes this test, when one of its tokens is encountered.
*
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
* @param integer $stackPtr The position of the current token in the stack passed in $tokens.
*
* @return int
*/
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile->getTokens();
$opener = $tokens[$stackPtr]['scope_opener'];
$nextAfterOpen = $phpcsFile->findNext(T_WHITESPACE, ($opener + 1), null, true);

if ($tokens[$nextAfterOpen]['line'] > ($tokens[$opener]['line'] + 1)) {
// Opening brace is on a new line, so there must be no blank line after it.
$error = 'Opening brace must not be succeeded by a blank line';
$fix = $phpcsFile->addFixableError($error, $opener, 'OpenBraceFollowedByBlankLine');

if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
for ($x = ($opener + 1); $x < $nextAfterOpen; $x++) {
if ($tokens[$x]['line'] === $tokens[$opener]['line']) {
// Maintain existing newline.
continue;
}

if ($tokens[$x]['line'] === $tokens[$nextAfterOpen]['line']) {
// Maintain existing indent.
break;
}

$phpcsFile->fixer->replaceToken($x, '');
}

$phpcsFile->fixer->endChangeset();
}
}

return ($phpcsFile->numTokens + 1);
}

}
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "datacodetech/phpcs-ruleset",
"version": "2.0.0",
"version": "2.1.0",
"type": "library",
"license": "MIT",
"description": "phpcs ruleset used for all PHP projects",
Expand Down