3
* Generic_Sniffs_Files_EndFileNewlineSniff.
8
* @package PHP_CodeSniffer
9
* @author Greg Sherwood <gsherwood@squiz.net>
10
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
11
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
12
* @link http://pear.php.net/package/PHP_CodeSniffer
16
* Generic_Sniffs_Files_EndFileNewlineSniff.
18
* Ensures the file ends with a newline character.
21
* @package PHP_CodeSniffer
22
* @author Greg Sherwood <gsherwood@squiz.net>
23
* @copyright 2006-2012 Squiz Pty Ltd (ABN 77 084 670 600)
24
* @license https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
25
* @version Release: 1.5.0RC2
26
* @link http://pear.php.net/package/PHP_CodeSniffer
28
class PSR2_Sniffs_Files_EndFileNewlineSniff implements PHP_CodeSniffer_Sniff
32
* Returns an array of tokens this test wants to listen for.
36
public function register()
38
return array(T_OPEN_TAG);
44
* Processes this sniff, when one of its tokens is encountered.
46
* @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
47
* @param int $stackPtr The position of the current token in
48
* the stack passed in $tokens.
52
public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
54
// We are only interested if this is the first open tag and in a file
55
// that only contains PHP code.
56
if ($stackPtr !== 0) {
57
if ($phpcsFile->findPrevious(array(T_OPEN_TAG, T_INLINE_HTML), ($stackPtr - 1)) !== false) {
62
if ($phpcsFile->findNext(T_INLINE_HTML, ($stackPtr + 1)) !== false) {
66
// Skip to the end of the file.
67
$tokens = $phpcsFile->getTokens();
68
$stackPtr = ($phpcsFile->numTokens - 1);
70
// Hard-coding the expected \n in this sniff as it is PSR-2 specific and
71
// PSR-2 enforces the use of unix style newlines.
72
if (substr($tokens[$stackPtr]['content'], -1) !== "\n") {
73
$error = 'Expected 1 newline at end of file; 0 found';
74
$phpcsFile->addError($error, $stackPtr, 'NoneFound');
78
// Go looking for the last non-empty line.
79
$lastLine = $tokens[$stackPtr]['line'];
80
while ($tokens[$stackPtr]['code'] === T_WHITESPACE) {
84
$lastCodeLine = $tokens[$stackPtr]['line'];
85
$blankLines = ($lastLine - $lastCodeLine);
86
if ($blankLines > 0) {
87
$error = 'Expected 1 blank line at end of file; %s found';
88
$data = array($blankLines + 1);
89
$phpcsFile->addError($error, $stackPtr, 'TooMany', $data);