EndFileNewlineSniff.php in Coder 8.2
File
coder_sniffer/Drupal/Sniffs/Files/EndFileNewlineSniff.php
View source
<?php
namespace Drupal\Sniffs\Files;
use PHP_CodeSniffer\Files\File;
use PHP_CodeSniffer\Sniffs\Sniff;
class EndFileNewlineSniff implements Sniff {
public $supportedTokenizers = array(
'PHP',
'JS',
'CSS',
);
public function register() {
return array(
T_OPEN_TAG,
T_INLINE_HTML,
);
}
public function process(File $phpcsFile, $stackPtr) {
$tokens = $phpcsFile
->getTokens();
if ($phpcsFile->tokenizerType === 'PHP') {
$lastToken = $phpcsFile->numTokens - 1;
}
else {
$lastToken = $phpcsFile->numTokens - 2;
}
if (substr($tokens[$lastToken]['content'], -1) !== "\n") {
$error = 'Expected 1 newline at end of file; 0 found';
$fix = $phpcsFile
->addFixableError($error, $lastToken, 'NoneFound');
if ($fix === true) {
$phpcsFile->fixer
->addNewline($lastToken);
}
$phpcsFile
->recordMetric($stackPtr, 'Number of newlines at EOF', '0');
return $phpcsFile->numTokens + 1;
}
$lastLine = $tokens[$lastToken]['line'];
if ($tokens[$lastToken]['code'] === T_WHITESPACE) {
$lastCode = $phpcsFile
->findPrevious(T_WHITESPACE, $lastToken - 1, null, true);
}
else {
if ($tokens[$lastToken]['code'] === T_INLINE_HTML) {
$lastCode = $lastToken;
while ($lastCode > 0 && trim($tokens[$lastCode]['content']) === '') {
$lastCode--;
}
}
else {
$lastCode = $lastToken;
}
}
$lastCodeLine = $tokens[$lastCode]['line'];
$blankLines = $lastLine - $lastCodeLine + 1;
$phpcsFile
->recordMetric($stackPtr, 'Number of newlines at EOF', $blankLines);
if ($blankLines > 1) {
$error = 'Expected 1 newline at end of file; %s found';
$data = array(
$blankLines,
);
$fix = $phpcsFile
->addFixableError($error, $lastCode, 'TooMany', $data);
if ($fix === true) {
$phpcsFile->fixer
->beginChangeset();
$phpcsFile->fixer
->replaceToken($lastCode, rtrim($tokens[$lastCode]['content']));
for ($i = $lastCode + 1; $i < $lastToken; $i++) {
$phpcsFile->fixer
->replaceToken($i, '');
}
$phpcsFile->fixer
->replaceToken($lastToken, $phpcsFile->eolChar);
$phpcsFile->fixer
->endChangeset();
}
}
return $phpcsFile->numTokens + 1;
}
}