1<?php
2/**
3 * PSR2_Sniffs_ControlStructures_ElseIfDeclarationSniff.
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 * PSR2_Sniffs_ControlStructures_ElseIfDeclarationSniff.
17 *
18 * Verifies that there are no else if statements. Elseif should be used instead.
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 PSR2_Sniffs_ControlStructures_ElseIfDeclarationSniff implements PHP_CodeSniffer_Sniff
29{
30
31
32    /**
33     * Returns an array of tokens this test wants to listen for.
34     *
35     * @return array
36     */
37    public function register()
38    {
39        return array(
40                T_ELSE,
41                T_ELSEIF,
42               );
43
44    }//end register()
45
46
47    /**
48     * Processes this test, when one of its tokens is encountered.
49     *
50     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
51     * @param int                  $stackPtr  The position of the current token in the
52     *                                        stack passed in $tokens.
53     *
54     * @return void
55     */
56    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
57    {
58        $tokens = $phpcsFile->getTokens();
59
60        if ($tokens[$stackPtr]['code'] === T_ELSEIF) {
61            $phpcsFile->recordMetric($stackPtr, 'Use of ELSE IF or ELSEIF', 'elseif');
62            return;
63        }
64
65        $next = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
66        if ($tokens[$next]['code'] === T_IF) {
67            $phpcsFile->recordMetric($stackPtr, 'Use of ELSE IF or ELSEIF', 'else if');
68            $error = 'Usage of ELSE IF is discouraged; use ELSEIF instead';
69            $fix   = $phpcsFile->addFixableWarning($error, $stackPtr, 'NotAllowed');
70
71            if ($fix === true) {
72                $phpcsFile->fixer->beginChangeset();
73                $phpcsFile->fixer->replaceToken($stackPtr, 'elseif');
74                for ($i = ($stackPtr + 1); $i <= $next; $i++) {
75                    $phpcsFile->fixer->replaceToken($i, '');
76                }
77
78                $phpcsFile->fixer->endChangeset();
79            }
80        }
81
82    }//end process()
83
84
85}//end class
86