1<?php
2/**
3 * Generic_Sniffs_PHP_ForbiddenFunctionsSniff.
4 *
5 * PHP version 5
6 *
7 * @category  PHP
8 * @package   PHP_CodeSniffer
9 * @author    Greg Sherwood <gsherwood@squiz.net>
10 * @author    Marc McIntyre <mmcintyre@squiz.net>
11 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
12 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
13 * @link      http://pear.php.net/package/PHP_CodeSniffer
14 */
15
16/**
17 * Generic_Sniffs_PHP_ForbiddenFunctionsSniff.
18 *
19 * Discourages the use of alias functions that are kept in PHP for compatibility
20 * with older versions. Can be used to forbid the use of any function.
21 *
22 * @category  PHP
23 * @package   PHP_CodeSniffer
24 * @author    Greg Sherwood <gsherwood@squiz.net>
25 * @author    Marc McIntyre <mmcintyre@squiz.net>
26 * @copyright 2006-2014 Squiz Pty Ltd (ABN 77 084 670 600)
27 * @license   https://github.com/squizlabs/PHP_CodeSniffer/blob/master/licence.txt BSD Licence
28 * @version   Release: @package_version@
29 * @link      http://pear.php.net/package/PHP_CodeSniffer
30 */
31class Generic_Sniffs_PHP_ForbiddenFunctionsSniff implements PHP_CodeSniffer_Sniff
32{
33
34    /**
35     * A list of forbidden functions with their alternatives.
36     *
37     * The value is NULL if no alternative exists. IE, the
38     * function should just not be used.
39     *
40     * @var array(string => string|null)
41     */
42    public $forbiddenFunctions = array(
43                                  'sizeof' => 'count',
44                                  'delete' => 'unset',
45                                 );
46
47    /**
48     * A cache of forbidden function names, for faster lookups.
49     *
50     * @var array(string)
51     */
52    protected $forbiddenFunctionNames = array();
53
54    /**
55     * If true, forbidden functions will be considered regular expressions.
56     *
57     * @var bool
58     */
59    protected $patternMatch = false;
60
61    /**
62     * If true, an error will be thrown; otherwise a warning.
63     *
64     * @var bool
65     */
66    public $error = true;
67
68
69    /**
70     * Returns an array of tokens this test wants to listen for.
71     *
72     * @return array
73     */
74    public function register()
75    {
76        // Everyone has had a chance to figure out what forbidden functions
77        // they want to check for, so now we can cache out the list.
78        $this->forbiddenFunctionNames = array_keys($this->forbiddenFunctions);
79
80        if ($this->patternMatch === true) {
81            foreach ($this->forbiddenFunctionNames as $i => $name) {
82                $this->forbiddenFunctionNames[$i] = '/'.$name.'/i';
83            }
84
85            return array(T_STRING);
86        }
87
88        // If we are not pattern matching, we need to work out what
89        // tokens to listen for.
90        $string = '<?php ';
91        foreach ($this->forbiddenFunctionNames as $name) {
92            $string .= $name.'();';
93        }
94
95        $register = array();
96
97        $tokens = token_get_all($string);
98        array_shift($tokens);
99        foreach ($tokens as $token) {
100            if (is_array($token) === true) {
101                $register[] = $token[0];
102            }
103        }
104
105        $this->forbiddenFunctionNames = array_map('strtolower', $this->forbiddenFunctionNames);
106        $this->forbiddenFunctions     = array_combine($this->forbiddenFunctionNames, $this->forbiddenFunctions);
107
108        return array_unique($register);
109
110    }//end register()
111
112
113    /**
114     * Processes this test, when one of its tokens is encountered.
115     *
116     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
117     * @param int                  $stackPtr  The position of the current token in
118     *                                        the stack passed in $tokens.
119     *
120     * @return void
121     */
122    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
123    {
124        $tokens = $phpcsFile->getTokens();
125
126        $ignore = array(
127                   T_DOUBLE_COLON    => true,
128                   T_OBJECT_OPERATOR => true,
129                   T_FUNCTION        => true,
130                   T_CONST           => true,
131                   T_PUBLIC          => true,
132                   T_PRIVATE         => true,
133                   T_PROTECTED       => true,
134                   T_AS              => true,
135                   T_NEW             => true,
136                   T_INSTEADOF       => true,
137                   T_NS_SEPARATOR    => true,
138                   T_IMPLEMENTS      => true,
139                  );
140
141        $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($stackPtr - 1), null, true);
142
143        // If function call is directly preceded by a NS_SEPARATOR it points to the
144        // global namespace, so we should still catch it.
145        if ($tokens[$prevToken]['code'] === T_NS_SEPARATOR) {
146            $prevToken = $phpcsFile->findPrevious(T_WHITESPACE, ($prevToken - 1), null, true);
147            if ($tokens[$prevToken]['code'] === T_STRING) {
148                // Not in the global namespace.
149                return;
150            }
151        }
152
153        if (isset($ignore[$tokens[$prevToken]['code']]) === true) {
154            // Not a call to a PHP function.
155            return;
156        }
157
158        $nextToken = $phpcsFile->findNext(T_WHITESPACE, ($stackPtr + 1), null, true);
159        if (isset($ignore[$tokens[$nextToken]['code']]) === true) {
160            // Not a call to a PHP function.
161            return;
162        }
163
164        if ($tokens[$stackPtr]['code'] === T_STRING && $tokens[$nextToken]['code'] !== T_OPEN_PARENTHESIS) {
165            // Not a call to a PHP function.
166            return;
167        }
168
169        $function = strtolower($tokens[$stackPtr]['content']);
170        $pattern  = null;
171
172        if ($this->patternMatch === true) {
173            $count   = 0;
174            $pattern = preg_replace(
175                $this->forbiddenFunctionNames,
176                $this->forbiddenFunctionNames,
177                $function,
178                1,
179                $count
180            );
181
182            if ($count === 0) {
183                return;
184            }
185
186            // Remove the pattern delimiters and modifier.
187            $pattern = substr($pattern, 1, -2);
188        } else {
189            if (in_array($function, $this->forbiddenFunctionNames) === false) {
190                return;
191            }
192        }//end if
193
194        $this->addError($phpcsFile, $stackPtr, $tokens[$stackPtr]['content'], $pattern);
195
196    }//end process()
197
198
199    /**
200     * Generates the error or warning for this sniff.
201     *
202     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
203     * @param int                  $stackPtr  The position of the forbidden function
204     *                                        in the token array.
205     * @param string               $function  The name of the forbidden function.
206     * @param string               $pattern   The pattern used for the match.
207     *
208     * @return void
209     */
210    protected function addError($phpcsFile, $stackPtr, $function, $pattern=null)
211    {
212        $data  = array($function);
213        $error = 'The use of function %s() is ';
214        if ($this->error === true) {
215            $type   = 'Found';
216            $error .= 'forbidden';
217        } else {
218            $type   = 'Discouraged';
219            $error .= 'discouraged';
220        }
221
222        if ($pattern === null) {
223            $pattern = strtolower($function);
224        }
225
226        if ($this->forbiddenFunctions[$pattern] !== null
227            && $this->forbiddenFunctions[$pattern] !== 'null'
228        ) {
229            $type  .= 'WithAlternative';
230            $data[] = $this->forbiddenFunctions[$pattern];
231            $error .= '; use %s() instead';
232        }
233
234        if ($this->error === true) {
235            $phpcsFile->addError($error, $stackPtr, $type, $data);
236        } else {
237            $phpcsFile->addWarning($error, $stackPtr, $type, $data);
238        }
239
240    }//end addError()
241
242
243}//end class
244