1<?php
2/**
3 * Generic_Sniffs_Files_EndFileNewlineSniff.
4 *
5 * PHP version 5
6 *
7 * @category  PHP
8 * @package   PHP_CodeSniffer
9 * @author    Greg Sherwood <gsherwood@squiz.net>
10 * @copyright 2006-2014 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
13 */
14
15/**
16 * Generic_Sniffs_Files_EndFileNewlineSniff.
17 *
18 * Ensures the file ends with a newline character.
19 *
20 * @category  PHP
21 * @package   PHP_CodeSniffer
22 * @author    Greg Sherwood <gsherwood@squiz.net>
23 * @copyright 2006-2014 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: @package_version@
26 * @link      http://pear.php.net/package/PHP_CodeSniffer
27 */
28class Generic_Sniffs_Files_EndFileNewlineSniff implements PHP_CodeSniffer_Sniff
29{
30
31    /**
32     * A list of tokenizers this sniff supports.
33     *
34     * @var array
35     */
36    public $supportedTokenizers = array(
37                                   'PHP',
38                                   'JS',
39                                   'CSS',
40                                  );
41
42
43    /**
44     * Returns an array of tokens this test wants to listen for.
45     *
46     * @return array
47     */
48    public function register()
49    {
50        return array(T_OPEN_TAG);
51
52    }//end register()
53
54
55    /**
56     * Processes this sniff, when one of its tokens is encountered.
57     *
58     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
59     * @param int                  $stackPtr  The position of the current token in
60     *                                        the stack passed in $tokens.
61     *
62     * @return int
63     */
64    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
65    {
66        // Skip to the end of the file.
67        $tokens   = $phpcsFile->getTokens();
68        $stackPtr = ($phpcsFile->numTokens - 1);
69
70        if ($tokens[$stackPtr]['content'] === '') {
71            $stackPtr--;
72        }
73
74        $eolCharLen = strlen($phpcsFile->eolChar);
75        $lastChars  = substr($tokens[$stackPtr]['content'], ($eolCharLen * -1));
76        if ($lastChars !== $phpcsFile->eolChar) {
77            $phpcsFile->recordMetric($stackPtr, 'Newline at EOF', 'no');
78
79            $error = 'File must end with a newline character';
80            $fix   = $phpcsFile->addFixableError($error, $stackPtr, 'NotFound');
81            if ($fix === true) {
82                $phpcsFile->fixer->addNewline($stackPtr);
83            }
84        } else {
85            $phpcsFile->recordMetric($stackPtr, 'Newline at EOF', 'yes');
86        }
87
88        // Ignore the rest of the file.
89        return ($phpcsFile->numTokens + 1);
90
91    }//end process()
92
93
94}//end class
95