Completed
Pull Request — master (#526)
by Juliette
04:34 queued 03:04
created

Sniff::isUseOfGlobalConstant()   D

Complexity

Conditions 30
Paths 59

Size

Total Lines 116
Code Lines 69

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 116
rs 4.425
c 0
b 0
f 0
cc 30
eloc 69
nc 59
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * \PHPCompatibility\Sniff.
4
 *
5
 * @category  PHP
6
 * @package   PHPCompatibility
7
 * @author    Wim Godden <[email protected]>
8
 * @copyright 2014 Cu.be Solutions bvba
9
 */
10
11
namespace PHPCompatibility;
12
13
use PHPCompatibility\PHPCSHelper;
14
15
/**
16
 * \PHPCompatibility\Sniff.
17
 *
18
 * @category  PHP
19
 * @package   PHPCompatibility
20
 * @author    Wim Godden <[email protected]>
21
 * @copyright 2014 Cu.be Solutions bvba
22
 */
23
abstract class Sniff implements \PHP_CodeSniffer_Sniff
24
{
25
26
    const REGEX_COMPLEX_VARS = '`(?:(\{)?(?<!\\\\)\$)?(\{)?(?<!\\\\)\$(\{)?(?P<varname>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?:->\$?(?P>varname)|\[[^\]]+\]|::\$?(?P>varname)|\([^\)]*\))*(?(3)\}|)(?(2)\}|)(?(1)\}|)`';
27
28
    /**
29
     * List of superglobals as an array of strings.
30
     *
31
     * Used by the ParameterShadowSuperGlobals and ForbiddenClosureUseVariableNames sniffs.
32
     *
33
     * @var array
34
     */
35
    protected $superglobals = array(
36
        '$GLOBALS',
37
        '$_SERVER',
38
        '$_GET',
39
        '$_POST',
40
        '$_FILES',
41
        '$_COOKIE',
42
        '$_SESSION',
43
        '$_REQUEST',
44
        '$_ENV',
45
    );
46
47
    /**
48
     * List of functions using hash algorithm as parameter (always the first parameter).
49
     *
50
     * Used by the new/removed hash algorithm sniffs.
51
     * Key is the function name, value is the 1-based parameter position in the function call.
52
     *
53
     * @var array
54
     */
55
    protected $hashAlgoFunctions = array(
56
        'hash_file'      => 1,
57
        'hash_hmac_file' => 1,
58
        'hash_hmac'      => 1,
59
        'hash_init'      => 1,
60
        'hash_pbkdf2'    => 1,
61
        'hash'           => 1,
62
    );
63
64
65
    /**
66
     * List of functions which take an ini directive as parameter (always the first parameter).
67
     *
68
     * Used by the new/removed ini directives sniffs.
69
     * Key is the function name, value is the 1-based parameter position in the function call.
70
     *
71
     * @var array
72
     */
73
    protected $iniFunctions = array(
74
        'ini_get' => 1,
75
        'ini_set' => 1,
76
    );
77
78
79
    /**
80
     * Get the testVersion configuration variable.
81
     *
82
     * The testVersion configuration variable may be in any of the following formats:
83
     * 1) Omitted/empty, in which case no version is specified. This effectively
84
     *    disables all the checks for new PHP features provided by this standard.
85
     * 2) A single PHP version number, e.g. "5.4" in which case the standard checks that
86
     *    the code will run on that version of PHP (no deprecated features or newer
87
     *    features being used).
88
     * 3) A range, e.g. "5.0-5.5", in which case the standard checks the code will run
89
     *    on all PHP versions in that range, and that it doesn't use any features that
90
     *    were deprecated by the final version in the list, or which were not available
91
     *    for the first version in the list.
92
     *    We accept ranges where one of the components is missing, e.g. "-5.6" means
93
     *    all versions up to PHP 5.6, and "7.0-" means all versions above PHP 7.0.
94
     * PHP version numbers should always be in Major.Minor format.  Both "5", "5.3.2"
95
     * would be treated as invalid, and ignored.
96
     *
97
     * @return array $arrTestVersions will hold an array containing min/max version
98
     *               of PHP that we are checking against (see above).  If only a
99
     *               single version number is specified, then this is used as
100
     *               both the min and max.
101
     *
102
     * @throws \PHP_CodeSniffer_Exception If testVersion is invalid.
103
     */
104
    private function getTestVersion()
105
    {
106
        static $arrTestVersions = array();
107
108
        $testVersion = trim(PHPCSHelper::getConfigData('testVersion'));
109
110
        if (isset($arrTestVersions[$testVersion]) === false && empty($testVersion) === false) {
111
112
            $arrTestVersions[$testVersion] = array(null, null);
113
            if (preg_match('/^\d+\.\d+$/', $testVersion)) {
114
                $arrTestVersions[$testVersion] = array($testVersion, $testVersion);
115
116
            } elseif (preg_match('/^(\d+\.\d+)\s*-\s*(\d+\.\d+)$/', $testVersion, $matches)) {
117
                if (version_compare($matches[1], $matches[2], '>')) {
118
                    trigger_error(
119
                        "Invalid range in testVersion setting: '" . $testVersion . "'",
120
                        E_USER_WARNING
121
                    );
122
123
                } else {
124
                    $arrTestVersions[$testVersion] = array($matches[1], $matches[2]);
125
                }
126
127
            } elseif (preg_match('/^\d+\.\d+-$/', $testVersion)) {
128
                // If no upper-limit is set, we set the max version to 99.9.
129
                // This is *probably* safe... :-)
130
                $arrTestVersions[$testVersion] = array(substr($testVersion, 0, -1), '99.9');
131
132
            } elseif (preg_match('/^-\d+\.\d+$/', $testVersion)) {
133
                // If no lower-limit is set, we set the min version to 4.0.
134
                // Whilst development focuses on PHP 5 and above, we also accept
135
                // sniffs for PHP 4, so we include that as the minimum.
136
                // (It makes no sense to support PHP 3 as this was effectively a
137
                // different language).
138
                $arrTestVersions[$testVersion] = array('4.0', substr($testVersion, 1));
139
140
            } elseif ($testVersion !== '') {
141
                trigger_error(
142
                    "Invalid testVersion setting: '" . $testVersion . "'",
143
                    E_USER_WARNING
144
                );
145
            }
146
        }
147
148
        if (isset($arrTestVersions[$testVersion])) {
149
            return $arrTestVersions[$testVersion];
150
        } else {
151
            return array(null, null);
152
        }
153
    }
154
155
156
    /**
157
     * Check whether a specific PHP version is equal to or higher than the maximum
158
     * supported PHP version as provided by the user in `testVersion`.
159
     *
160
     * Should be used when sniffing for *old* PHP features (deprecated/removed).
161
     *
162
     * @param string $phpVersion A PHP version number in 'major.minor' format.
163
     *
164
     * @return bool True if testVersion has not been provided or if the PHP version
165
     *              is equal to or higher than the highest supported PHP version
166
     *              in testVersion. False otherwise.
167
     */
168 View Code Duplication
    public function supportsAbove($phpVersion)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
169
    {
170
        $testVersion = $this->getTestVersion();
171
        $testVersion = $testVersion[1];
172
173
        if (is_null($testVersion)
174
            || version_compare($testVersion, $phpVersion) >= 0
175
        ) {
176
            return true;
177
        } else {
178
            return false;
179
        }
180
    }//end supportsAbove()
181
182
183
    /**
184
     * Check whether a specific PHP version is equal to or lower than the minimum
185
     * supported PHP version as provided by the user in `testVersion`.
186
     *
187
     * Should be used when sniffing for *new* PHP features.
188
     *
189
     * @param string $phpVersion A PHP version number in 'major.minor' format.
190
     *
191
     * @return bool True if the PHP version is equal to or lower than the lowest
192
     *              supported PHP version in testVersion.
193
     *              False otherwise or if no testVersion is provided.
194
     */
195 View Code Duplication
    public function supportsBelow($phpVersion)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
    {
197
        $testVersion = $this->getTestVersion();
198
        $testVersion = $testVersion[0];
199
200
        if (is_null($testVersion) === false
201
            && version_compare($testVersion, $phpVersion) <= 0
202
        ) {
203
            return true;
204
        } else {
205
            return false;
206
        }
207
    }//end supportsBelow()
208
209
210
    /**
211
     * Add a PHPCS message to the output stack as either a warning or an error.
212
     *
213
     * @param \PHP_CodeSniffer_File $phpcsFile The file the message applies to.
214
     * @param string                $message   The message.
215
     * @param int                   $stackPtr  The position of the token
216
     *                                         the message relates to.
217
     * @param bool                  $isError   Whether to report the message as an
218
     *                                         'error' or 'warning'.
219
     *                                         Defaults to true (error).
220
     * @param string                $code      The error code for the message.
221
     *                                         Defaults to 'Found'.
222
     * @param array                 $data      Optional input for the data replacements.
223
     *
224
     * @return void
225
     */
226
    public function addMessage(\PHP_CodeSniffer_File $phpcsFile, $message, $stackPtr, $isError, $code = 'Found', $data = array())
227
    {
228
        if ($isError === true) {
229
            $phpcsFile->addError($message, $stackPtr, $code, $data);
230
        } else {
231
            $phpcsFile->addWarning($message, $stackPtr, $code, $data);
232
        }
233
    }
234
235
236
    /**
237
     * Convert an arbitrary string to an alphanumeric string with underscores.
238
     *
239
     * Pre-empt issues with arbitrary strings being used as error codes in XML and PHP.
240
     *
241
     * @param string $baseString Arbitrary string.
242
     *
243
     * @return string
244
     */
245
    public function stringToErrorCode($baseString)
246
    {
247
        return preg_replace('`[^a-z0-9_]`i', '_', strtolower($baseString));
248
    }
249
250
251
    /**
252
     * Strip quotes surrounding an arbitrary string.
253
     *
254
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING / T_DOUBLE_QUOTED_STRING.
255
     *
256
     * @param string $string The raw string.
257
     *
258
     * @return string String without quotes around it.
259
     */
260
    public function stripQuotes($string)
261
    {
262
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
263
    }
264
265
266
    /**
267
     * Strip variables from an arbitrary double quoted string.
268
     *
269
     * Intended for use with the content of a T_DOUBLE_QUOTED_STRING.
270
     *
271
     * @param string $string The raw string.
272
     *
273
     * @return string String without variables in it.
274
     */
275
    public function stripVariables($string)
276
    {
277
        if (strpos($string, '$') === false) {
278
            return $string;
279
        }
280
281
        return preg_replace(self::REGEX_COMPLEX_VARS, '', $string);
282
    }
283
284
285
    /**
286
     * Make all top level array keys in an array lowercase.
287
     *
288
     * @param array $array Initial array.
289
     *
290
     * @return array Same array, but with all lowercase top level keys.
291
     */
292
    public function arrayKeysToLowercase($array)
293
    {
294
        $keys = array_keys($array);
295
        $keys = array_map('strtolower', $keys);
296
        return array_combine($keys, $array);
297
    }
298
299
300
    /**
301
     * Returns the name(s) of the interface(s) that the specified class implements.
302
     *
303
     * Returns FALSE on error or if there are no implemented interface names.
304
     *
305
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
306
     * This method also includes an improvement we use which was only introduced
307
     * in PHPCS 2.8.0, so only defer to upstream for higher versions.
308
     * Once the minimum supported PHPCS version for this sniff library goes beyond
309
     * that, this method can be removed and calls to it replaced with
310
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
311
     *
312
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
313
     * @param int                   $stackPtr  The position of the class token.
314
     *
315
     * @return array|false
316
     */
317
    public function findImplementedInterfaceNames(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
318
    {
319
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
320
            return $phpcsFile->findImplementedInterfaceNames($stackPtr);
321
        }
322
323
        $tokens = $phpcsFile->getTokens();
324
325
        // Check for the existence of the token.
326
        if (isset($tokens[$stackPtr]) === false) {
327
            return false;
328
        }
329
330
        if ($tokens[$stackPtr]['code'] !== T_CLASS
331
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
332
        ) {
333
            return false;
334
        }
335
336
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
337
            return false;
338
        }
339
340
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
341
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
342
        if ($implementsIndex === false) {
343
            return false;
344
        }
345
346
        $find = array(
347
            T_NS_SEPARATOR,
348
            T_STRING,
349
            T_WHITESPACE,
350
            T_COMMA,
351
        );
352
353
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
354
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
355
        $name = trim($name);
356
357
        if ($name === '') {
358
            return false;
359
        } else {
360
            $names = explode(',', $name);
361
            $names = array_map('trim', $names);
362
            return $names;
363
        }
364
365
    }//end findImplementedInterfaceNames()
366
367
368
    /**
369
     * Checks if a function call has parameters.
370
     *
371
     * Expects to be passed the T_STRING stack pointer for the function call.
372
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
373
     *
374
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer, it
375
     * will detect whether the array has values or is empty.
376
     *
377
     * @link https://github.com/wimg/PHPCompatibility/issues/120
378
     * @link https://github.com/wimg/PHPCompatibility/issues/152
379
     *
380
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
381
     * @param int                   $stackPtr  The position of the function call token.
382
     *
383
     * @return bool
384
     */
385
    public function doesFunctionCallHaveParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
386
    {
387
        $tokens = $phpcsFile->getTokens();
388
389
        // Check for the existence of the token.
390
        if (isset($tokens[$stackPtr]) === false) {
391
            return false;
392
        }
393
394
        // Is this one of the tokens this function handles ?
395
        if (in_array($tokens[$stackPtr]['code'], array(T_STRING, T_ARRAY, T_OPEN_SHORT_ARRAY), true) === false) {
396
            return false;
397
        }
398
399
        $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
400
401
        // Deal with short array syntax.
402
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
403
            if (isset($tokens[$stackPtr]['bracket_closer']) === false) {
404
                return false;
405
            }
406
407
            if ($nextNonEmpty === $tokens[$stackPtr]['bracket_closer']) {
408
                // No parameters.
409
                return false;
410
            } else {
411
                return true;
412
            }
413
        }
414
415
        // Deal with function calls & long arrays.
416
        // Next non-empty token should be the open parenthesis.
417
        if ($nextNonEmpty === false && $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS) {
418
            return false;
419
        }
420
421
        if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
422
            return false;
423
        }
424
425
        $closeParenthesis = $tokens[$nextNonEmpty]['parenthesis_closer'];
426
        $nextNextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextNonEmpty + 1, $closeParenthesis + 1, true);
427
428
        if ($nextNextNonEmpty === $closeParenthesis) {
429
            // No parameters.
430
            return false;
431
        }
432
433
        return true;
434
    }
435
436
437
    /**
438
     * Count the number of parameters a function call has been passed.
439
     *
440
     * Expects to be passed the T_STRING stack pointer for the function call.
441
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
442
     *
443
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
444
     * it will return the number of values in the array.
445
     *
446
     * @link https://github.com/wimg/PHPCompatibility/issues/111
447
     * @link https://github.com/wimg/PHPCompatibility/issues/114
448
     * @link https://github.com/wimg/PHPCompatibility/issues/151
449
     *
450
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
451
     * @param int                   $stackPtr  The position of the function call token.
452
     *
453
     * @return int
454
     */
455
    public function getFunctionCallParameterCount(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
456
    {
457
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
458
            return 0;
459
        }
460
461
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
462
    }
463
464
465
    /**
466
     * Get information on all parameters passed to a function call.
467
     *
468
     * Expects to be passed the T_STRING stack pointer for the function call.
469
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
470
     *
471
     * Will return an multi-dimentional array with the start token pointer, end token
472
     * pointer and raw parameter value for all parameters. Index will be 1-based.
473
     * If no parameters are found, will return an empty array.
474
     *
475
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
476
     * it will tokenize the values / key/value pairs contained in the array call.
477
     *
478
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
479
     * @param int                   $stackPtr  The position of the function call token.
480
     *
481
     * @return array
482
     */
483
    public function getFunctionCallParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
484
    {
485
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
486
            return array();
487
        }
488
489
        // Ok, we know we have a T_STRING, T_ARRAY or T_OPEN_SHORT_ARRAY with parameters
490
        // and valid open & close brackets/parenthesis.
491
        $tokens = $phpcsFile->getTokens();
492
493
        // Mark the beginning and end tokens.
494
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
495
            $opener = $stackPtr;
496
            $closer = $tokens[$stackPtr]['bracket_closer'];
497
498
            $nestedParenthesisCount = 0;
499
500
        } else {
501
            $opener = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
502
            $closer = $tokens[$opener]['parenthesis_closer'];
503
504
            $nestedParenthesisCount = 1;
505
        }
506
507
        // Which nesting level is the one we are interested in ?
508 View Code Duplication
        if (isset($tokens[$opener]['nested_parenthesis'])) {
509
            $nestedParenthesisCount += count($tokens[$opener]['nested_parenthesis']);
510
        }
511
512
        $parameters = array();
513
        $nextComma  = $opener;
514
        $paramStart = $opener + 1;
515
        $cnt        = 1;
516
        while (($nextComma = $phpcsFile->findNext(array(T_COMMA, $tokens[$closer]['code'], T_OPEN_SHORT_ARRAY), $nextComma + 1, $closer + 1)) !== false) {
517
            // Ignore anything within short array definition brackets.
518
            if ($tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
519
                && (isset($tokens[$nextComma]['bracket_opener'])
520
                    && $tokens[$nextComma]['bracket_opener'] === $nextComma)
521
                && isset($tokens[$nextComma]['bracket_closer'])
522
            ) {
523
                // Skip forward to the end of the short array definition.
524
                $nextComma = $tokens[$nextComma]['bracket_closer'];
525
                continue;
526
            }
527
528
            // Ignore comma's at a lower nesting level.
529
            if ($tokens[$nextComma]['type'] === 'T_COMMA'
530
                && isset($tokens[$nextComma]['nested_parenthesis'])
531
                && count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
532
            ) {
533
                continue;
534
            }
535
536
            // Ignore closing parenthesis/bracket if not 'ours'.
537
            if ($tokens[$nextComma]['type'] === $tokens[$closer]['type'] && $nextComma !== $closer) {
538
                continue;
539
            }
540
541
            // Ok, we've reached the end of the parameter.
542
            $parameters[$cnt]['start'] = $paramStart;
543
            $parameters[$cnt]['end']   = $nextComma - 1;
544
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
545
546
            // Check if there are more tokens before the closing parenthesis.
547
            // Prevents code like the following from setting a third parameter:
548
            // functionCall( $param1, $param2, );
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
549
            $hasNextParam = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closer, true, null, true);
550
            if ($hasNextParam === false) {
551
                break;
552
            }
553
554
            // Prepare for the next parameter.
555
            $paramStart = $nextComma + 1;
556
            $cnt++;
557
        }
558
559
        return $parameters;
560
    }
561
562
563
    /**
564
     * Get information on a specific parameter passed to a function call.
565
     *
566
     * Expects to be passed the T_STRING stack pointer for the function call.
567
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
568
     *
569
     * Will return a array with the start token pointer, end token pointer and the raw value
570
     * of the parameter at a specific offset.
571
     * If the specified parameter is not found, will return false.
572
     *
573
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
574
     * @param int                   $stackPtr    The position of the function call token.
575
     * @param int                   $paramOffset The 1-based index position of the parameter to retrieve.
576
     *
577
     * @return array|false
578
     */
579
    public function getFunctionCallParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
580
    {
581
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
582
583
        if (isset($parameters[$paramOffset]) === false) {
584
            return false;
585
        } else {
586
            return $parameters[$paramOffset];
587
        }
588
    }
589
590
591
    /**
592
     * Verify whether a token is within a scoped condition.
593
     *
594
     * If the optional $validScopes parameter has been passed, the function
595
     * will check that the token has at least one condition which is of a
596
     * type defined in $validScopes.
597
     *
598
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
599
     * @param int                   $stackPtr    The position of the token.
600
     * @param array|int             $validScopes Optional. Array of valid scopes
601
     *                                           or int value of a valid scope.
602
     *                                           Pass the T_.. constant(s) for the
603
     *                                           desired scope to this parameter.
604
     *
605
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
606
     *              If the $scopeTypes are set: True if *one* of the conditions is a
607
     *              valid scope, false otherwise.
608
     */
609
    public function tokenHasScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
610
    {
611
        $tokens = $phpcsFile->getTokens();
612
613
        // Check for the existence of the token.
614
        if (isset($tokens[$stackPtr]) === false) {
615
            return false;
616
        }
617
618
        // No conditions = no scope.
619
        if (empty($tokens[$stackPtr]['conditions'])) {
620
            return false;
621
        }
622
623
        // Ok, there are conditions, do we have to check for specific ones ?
624
        if (isset($validScopes) === false) {
625
            return true;
626
        }
627
628
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
629
    }
630
631
632
    /**
633
     * Verify whether a token is within a class scope.
634
     *
635
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
636
     * @param int                   $stackPtr  The position of the token.
637
     * @param bool                  $strict    Whether to strictly check for the T_CLASS
638
     *                                         scope or also accept interfaces and traits
639
     *                                         as scope.
640
     *
641
     * @return bool True if within class scope, false otherwise.
642
     */
643
    public function inClassScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
644
    {
645
        $validScopes = array(T_CLASS);
646
        if (defined('T_ANON_CLASS') === true) {
647
            $validScopes[] = T_ANON_CLASS;
648
        }
649
650
        if ($strict === false) {
651
            $validScopes[] = T_INTERFACE;
652
653
            if (defined('T_TRAIT')) {
654
                $validScopes[] = constant('T_TRAIT');
655
            }
656
        }
657
658
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
659
    }
660
661
662
    /**
663
     * Verify whether a token is within a scoped use statement.
664
     *
665
     * PHPCS cross-version compatibility method.
666
     *
667
     * In PHPCS 1.x no conditions are set for a scoped use statement.
668
     * This method works around that limitation.
669
     *
670
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
671
     * @param int                   $stackPtr  The position of the token.
672
     *
673
     * @return bool True if within use scope, false otherwise.
674
     */
675
    public function inUseScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
676
    {
677
        static $isLowPHPCS, $ignoreTokens;
678
679
        if (isset($isLowPHPCS) === false) {
680
            $isLowPHPCS = version_compare(PHPCSHelper::getVersion(), '2.3.0', '<');
681
        }
682
        if (isset($ignoreTokens) === false) {
683
            $ignoreTokens              = \PHP_CodeSniffer_Tokens::$emptyTokens;
684
            $ignoreTokens[T_STRING]    = T_STRING;
685
            $ignoreTokens[T_AS]        = T_AS;
686
            $ignoreTokens[T_PUBLIC]    = T_PUBLIC;
687
            $ignoreTokens[T_PROTECTED] = T_PROTECTED;
688
            $ignoreTokens[T_PRIVATE]   = T_PRIVATE;
689
        }
690
691
        // PHPCS 2.0.
692
        if ($isLowPHPCS === false) {
693
            return $phpcsFile->hasCondition($stackPtr, T_USE);
694
        } else {
695
            // PHPCS 1.x.
696
            $tokens         = $phpcsFile->getTokens();
697
            $maybeCurlyOpen = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
698
            if ($tokens[$maybeCurlyOpen]['code'] === T_OPEN_CURLY_BRACKET) {
699
                $maybeUseStatement = $phpcsFile->findPrevious($ignoreTokens, ($maybeCurlyOpen - 1), null, true);
700
                if ($tokens[$maybeUseStatement]['code'] === T_USE) {
701
                    return true;
702
                }
703
            }
704
            return false;
705
        }
706
    }
707
708
709
    /**
710
     * Returns the fully qualified class name for a new class instantiation.
711
     *
712
     * Returns an empty string if the class name could not be reliably inferred.
713
     *
714
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
715
     * @param int                   $stackPtr  The position of a T_NEW token.
716
     *
717
     * @return string
718
     */
719
    public function getFQClassNameFromNewToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
720
    {
721
        $tokens = $phpcsFile->getTokens();
722
723
        // Check for the existence of the token.
724
        if (isset($tokens[$stackPtr]) === false) {
725
            return '';
726
        }
727
728
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
729
            return '';
730
        }
731
732
        $start = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
733
        if ($start === false) {
734
            return '';
735
        }
736
737
        // Bow out if the next token is a variable as we don't know where it was defined.
738
        if ($tokens[$start]['code'] === T_VARIABLE) {
739
            return '';
740
        }
741
742
        // Bow out if the next token is the class keyword.
743
        if ($tokens[$start]['type'] === 'T_ANON_CLASS' || $tokens[$start]['code'] === T_CLASS) {
744
            return '';
745
        }
746
747
        $find = array(
748
            T_NS_SEPARATOR,
749
            T_STRING,
750
            T_NAMESPACE,
751
            T_WHITESPACE,
752
        );
753
754
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
755
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
756
        $className = trim($className);
757
758
        return $this->getFQName($phpcsFile, $stackPtr, $className);
759
    }
760
761
762
    /**
763
     * Returns the fully qualified name of the class that the specified class extends.
764
     *
765
     * Returns an empty string if the class does not extend another class or if
766
     * the class name could not be reliably inferred.
767
     *
768
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
769
     * @param int                   $stackPtr  The position of a T_CLASS token.
770
     *
771
     * @return string
772
     */
773
    public function getFQExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
774
    {
775
        $tokens = $phpcsFile->getTokens();
776
777
        // Check for the existence of the token.
778
        if (isset($tokens[$stackPtr]) === false) {
779
            return '';
780
        }
781
782 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
783
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
784
            && $tokens[$stackPtr]['type'] !== 'T_INTERFACE'
785
        ) {
786
            return '';
787
        }
788
789
        $extends = $this->findExtendedClassName($phpcsFile, $stackPtr);
790
        if (empty($extends) || is_string($extends) === false) {
791
            return '';
792
        }
793
794
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
795
    }
796
797
798
    /**
799
     * Returns the class name for the static usage of a class.
800
     * This can be a call to a method, the use of a property or constant.
801
     *
802
     * Returns an empty string if the class name could not be reliably inferred.
803
     *
804
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
805
     * @param int                   $stackPtr  The position of a T_NEW token.
806
     *
807
     * @return string
808
     */
809
    public function getFQClassNameFromDoubleColonToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
810
    {
811
        $tokens = $phpcsFile->getTokens();
812
813
        // Check for the existence of the token.
814
        if (isset($tokens[$stackPtr]) === false) {
815
            return '';
816
        }
817
818
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
819
            return '';
820
        }
821
822
        // Nothing to do if previous token is a variable as we don't know where it was defined.
823
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
824
            return '';
825
        }
826
827
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
828
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
829
            return '';
830
        }
831
832
        // Get the classname from the class declaration if self is used.
833
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
834
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
835
            if ($classDeclarationPtr === false) {
836
                return '';
837
            }
838
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
839
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
840
        }
841
842
        $find = array(
843
            T_NS_SEPARATOR,
844
            T_STRING,
845
            T_NAMESPACE,
846
            T_WHITESPACE,
847
        );
848
849
        $start = $phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true);
850
        if ($start === false || isset($tokens[($start + 1)]) === false) {
851
            return '';
852
        }
853
854
        $start     = ($start + 1);
855
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
856
        $className = trim($className);
857
858
        return $this->getFQName($phpcsFile, $stackPtr, $className);
859
    }
860
861
862
    /**
863
     * Get the Fully Qualified name for a class/function/constant etc.
864
     *
865
     * Checks if a class/function/constant name is already fully qualified and
866
     * if not, enrich it with the relevant namespace information.
867
     *
868
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
869
     * @param int                   $stackPtr  The position of the token.
870
     * @param string                $name      The class / function / constant name.
871
     *
872
     * @return string
873
     */
874
    public function getFQName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
875
    {
876
        if (strpos($name, '\\') === 0) {
877
            // Already fully qualified.
878
            return $name;
879
        }
880
881
        // Remove the namespace keyword if used.
882
        if (strpos($name, 'namespace\\') === 0) {
883
            $name = substr($name, 10);
884
        }
885
886
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
887
888
        if ($namespace === '') {
889
            return '\\' . $name;
890
        } else {
891
            return '\\' . $namespace . '\\' . $name;
892
        }
893
    }
894
895
896
    /**
897
     * Is the class/function/constant name namespaced or global ?
898
     *
899
     * @param string $FQName Fully Qualified name of a class, function etc.
900
     *                       I.e. should always start with a `\`.
901
     *
902
     * @return bool True if namespaced, false if global.
903
     */
904
    public function isNamespaced($FQName)
905
    {
906
        if (strpos($FQName, '\\') !== 0) {
907
            throw new \PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
908
        }
909
910
        return (strpos(substr($FQName, 1), '\\') !== false);
911
    }
912
913
914
    /**
915
     * Determine the namespace name an arbitrary token lives in.
916
     *
917
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
918
     * @param int                   $stackPtr  The token position for which to determine the namespace.
919
     *
920
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
921
     */
922
    public function determineNamespace(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
923
    {
924
        $tokens = $phpcsFile->getTokens();
925
926
        // Check for the existence of the token.
927
        if (isset($tokens[$stackPtr]) === false) {
928
            return '';
929
        }
930
931
        // Check for scoped namespace {}.
932
        if (empty($tokens[$stackPtr]['conditions']) === false) {
933
            $namespacePtr = $phpcsFile->getCondition($stackPtr, T_NAMESPACE);
934
            if ($namespacePtr !== false) {
935
                $namespace = $this->getDeclaredNamespaceName($phpcsFile, $namespacePtr);
936
                if ($namespace !== false) {
937
                    return $namespace;
938
                }
939
940
                // We are in a scoped namespace, but couldn't determine the name. Searching for a global namespace is futile.
941
                return '';
942
            }
943
        }
944
945
        /*
946
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
947
         * Keeping in mind that:
948
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
949
         * - the namespace keyword can also be used as part of a function/method call and such.
950
         * - that a non-named namespace resolves to the global namespace.
951
         */
952
        $previousNSToken = $stackPtr;
953
        $namespace       = false;
954
        do {
955
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, ($previousNSToken - 1));
956
957
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
958
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] === $previousNSToken) {
959
                break;
960
            }
961
962
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
963
964
        } while ($namespace === false && $previousNSToken !== false);
965
966
        // If we still haven't got a namespace, return an empty string.
967
        if ($namespace === false) {
968
            return '';
969
        } else {
970
            return $namespace;
971
        }
972
    }
973
974
    /**
975
     * Get the complete namespace name for a namespace declaration.
976
     *
977
     * For hierarchical namespaces, the name will be composed of several tokens,
978
     * i.e. MyProject\Sub\Level which will be returned together as one string.
979
     *
980
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
981
     * @param int|bool              $stackPtr  The position of a T_NAMESPACE token.
982
     *
983
     * @return string|false Namespace name or false if not a namespace declaration.
984
     *                      Namespace name can be an empty string for global namespace declaration.
985
     */
986
    public function getDeclaredNamespaceName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
987
    {
988
        $tokens = $phpcsFile->getTokens();
989
990
        // Check for the existence of the token.
991 View Code Duplication
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
992
            return false;
993
        }
994
995
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
996
            return false;
997
        }
998
999
        if ($tokens[($stackPtr + 1)]['code'] === T_NS_SEPARATOR) {
1000
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
1001
            return false;
1002
        }
1003
1004
        $nextToken = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
1005
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
1006
            // Declaration for global namespace when using multiple namespaces in a file.
1007
            // I.e.: namespace {}
1008
            return '';
1009
        }
1010
1011
        // Ok, this should be a namespace declaration, so get all the parts together.
1012
        $validTokens = array(
1013
            T_STRING       => true,
1014
            T_NS_SEPARATOR => true,
1015
            T_WHITESPACE   => true,
1016
        );
1017
1018
        $namespaceName = '';
1019
        while (isset($validTokens[$tokens[$nextToken]['code']]) === true) {
1020
            $namespaceName .= trim($tokens[$nextToken]['content']);
1021
            $nextToken++;
1022
        }
1023
1024
        return $namespaceName;
1025
    }
1026
1027
1028
    /**
1029
     * Get the stack pointer for a return type token for a given function.
1030
     *
1031
     * Compatible layer for older PHPCS versions which don't recognize
1032
     * return type hints correctly.
1033
     *
1034
     * Expects to be passed T_RETURN_TYPE, T_FUNCTION or T_CLOSURE token.
1035
     *
1036
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1037
     * @param int                   $stackPtr  The position of the token.
1038
     *
1039
     * @return int|false Stack pointer to the return type token or false if
1040
     *                   no return type was found or the passed token was
1041
     *                   not of the correct type.
1042
     */
1043
    public function getReturnTypeHintToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1044
    {
1045
        $tokens = $phpcsFile->getTokens();
1046
1047
        if (defined('T_RETURN_TYPE') && $tokens[$stackPtr]['code'] === T_RETURN_TYPE) {
1048
            return $tokens[$stackPtr]['code'];
1049
        }
1050
1051 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1052
            return false;
1053
        }
1054
1055
        if (isset($tokens[$stackPtr]['parenthesis_closer'], $tokens[$stackPtr]['scope_opener']) === false
1056
            || ($tokens[$stackPtr]['parenthesis_closer'] + 1) === $tokens[$stackPtr]['scope_opener']
1057
        ) {
1058
            return false;
1059
        }
1060
1061
        $hasColon = $phpcsFile->findNext(array(T_COLON, T_INLINE_ELSE), ($tokens[$stackPtr]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']);
1062
        if ($hasColon === false) {
1063
            return false;
1064
        }
1065
1066
        // `self`, `parent` and `callable` are not being recognized as return types in PHPCS < 2.6.0.
1067
        $unrecognizedTypes = array(
1068
            T_CALLABLE,
1069
            T_SELF,
1070
            T_PARENT,
1071
        );
1072
1073
        // Return types are not recognized at all in PHPCS < 2.4.0.
1074
        if (defined('T_RETURN_TYPE') === false) {
1075
            $unrecognizedTypes[] = T_ARRAY;
1076
            $unrecognizedTypes[] = T_STRING;
1077
        }
1078
1079
        return $phpcsFile->findNext($unrecognizedTypes, ($hasColon + 1), $tokens[$stackPtr]['scope_opener']);
1080
    }
1081
1082
1083
    /**
1084
     * Check whether a T_VARIABLE token is a class property declaration.
1085
     *
1086
     * Compatibility layer for PHPCS cross-version compatibility
1087
     * as PHPCS 2.4.0 - 2.7.1 does not have good enough support for
1088
     * anonymous classes. Along the same lines, the`getMemberProperties()`
1089
     * method does not support the `var` prefix.
1090
     *
1091
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1092
     * @param int                   $stackPtr  The position in the stack of the
1093
     *                                         T_VARIABLE token to verify.
1094
     *
1095
     * @return bool
1096
     */
1097
    public function isClassProperty(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1098
    {
1099
        $tokens = $phpcsFile->getTokens();
1100
1101 View Code Duplication
        if (isset($tokens[$stackPtr]) === false || $tokens[$stackPtr]['code'] !== T_VARIABLE) {
1102
            return false;
1103
        }
1104
1105
        // Note: interfaces can not declare properties.
1106
        $validScopes = array(
1107
            'T_CLASS'      => true,
1108
            'T_ANON_CLASS' => true,
1109
            'T_TRAIT'      => true,
1110
        );
1111
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1112
            // Make sure it's not a method parameter.
1113
            if (empty($tokens[$stackPtr]['nested_parenthesis']) === true) {
1114
                return true;
1115
            }
1116
        }
1117
1118
        return false;
1119
    }
1120
1121
1122
    /**
1123
     * Check whether a T_CONST token is a class constant declaration.
1124
     *
1125
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1126
     * @param int                   $stackPtr  The position in the stack of the
1127
     *                                         T_CONST token to verify.
1128
     *
1129
     * @return bool
1130
     */
1131
    public function isClassConstant(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1132
    {
1133
        $tokens = $phpcsFile->getTokens();
1134
1135 View Code Duplication
        if (isset($tokens[$stackPtr]) === false || $tokens[$stackPtr]['code'] !== T_CONST) {
1136
            return false;
1137
        }
1138
1139
        // Note: traits can not declare constants.
1140
        $validScopes = array(
1141
            'T_CLASS'      => true,
1142
            'T_ANON_CLASS' => true,
1143
            'T_INTERFACE'  => true,
1144
        );
1145
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1146
            return true;
1147
        }
1148
1149
        return false;
1150
    }
1151
1152
1153
    /**
1154
     * Check whether the direct wrapping scope of a token is within a limited set of
1155
     * acceptable tokens.
1156
     *
1157
     * Used to check, for instance, if a T_CONST is a class constant.
1158
     *
1159
     * @param \PHP_CodeSniffer_File $phpcsFile   Instance of phpcsFile.
1160
     * @param int                   $stackPtr    The position in the stack of the
1161
     *                                           T_CONST token to verify.
1162
     * @param array                 $validScopes Array of token types.
1163
     *                                           Keys should be the token types in string
1164
     *                                           format to allow for newer token types.
1165
     *                                           Value is irrelevant.
1166
     *
1167
     * @return bool
1168
     */
1169
    protected function validDirectScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes)
1170
    {
1171
        $tokens = $phpcsFile->getTokens();
1172
1173
        if (empty($tokens[$stackPtr]['conditions']) === true) {
1174
            return false;
1175
        }
1176
1177
        /*
1178
         * Check only the direct wrapping scope of the token.
1179
         */
1180
        $conditions = array_keys($tokens[$stackPtr]['conditions']);
1181
        $ptr        = array_pop($conditions);
1182
1183
        if (isset($tokens[$ptr]) === false) {
1184
            return false;
1185
        }
1186
1187
        if (isset($validScopes[$tokens[$ptr]['type']]) === true) {
1188
            return true;
1189
        }
1190
1191
        return false;
1192
    }
1193
1194
1195
    /**
1196
     * Get an array of just the type hints from a function declaration.
1197
     *
1198
     * Expects to be passed T_FUNCTION or T_CLOSURE token.
1199
     *
1200
     * Strips potential nullable indicator and potential global namespace
1201
     * indicator from the type hints before returning them.
1202
     *
1203
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1204
     * @param int                   $stackPtr  The position of the token.
1205
     *
1206
     * @return array Array with type hints or an empty array if
1207
     *               - the function does not have any parameters
1208
     *               - no type hints were found
1209
     *               - or the passed token was not of the correct type.
1210
     */
1211
    public function getTypeHintsFromFunctionDeclaration(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1212
    {
1213
        $tokens = $phpcsFile->getTokens();
1214
1215 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1216
            return array();
1217
        }
1218
1219
        $parameters = $this->getMethodParameters($phpcsFile, $stackPtr);
1220
        if (empty($parameters) || is_array($parameters) === false) {
1221
            return array();
1222
        }
1223
1224
        $typeHints = array();
1225
1226
        foreach ($parameters as $param) {
1227
            if ($param['type_hint'] === '') {
1228
                continue;
1229
            }
1230
1231
            // Strip off potential nullable indication.
1232
            $typeHint = ltrim($param['type_hint'], '?');
1233
1234
            // Strip off potential (global) namespace indication.
1235
            $typeHint = ltrim($typeHint, '\\');
1236
1237
            if ($typeHint !== '') {
1238
                $typeHints[] = $typeHint;
1239
            }
1240
        }
1241
1242
        return $typeHints;
1243
    }
1244
1245
1246
    /**
1247
     * Returns the method parameters for the specified function token.
1248
     *
1249
     * Each parameter is in the following format:
1250
     *
1251
     * <code>
1252
     *   0 => array(
1253
     *         'token'             => int,     // The position of the var in the token stack.
1254
     *         'name'              => '$var',  // The variable name.
1255
     *         'content'           => string,  // The full content of the variable definition.
1256
     *         'pass_by_reference' => boolean, // Is the variable passed by reference?
1257
     *         'variable_length'   => boolean, // Is the param of variable length through use of `...` ?
1258
     *         'type_hint'         => string,  // The type hint for the variable.
1259
     *         'nullable_type'     => boolean, // Is the variable using a nullable type?
1260
     *        )
1261
     * </code>
1262
     *
1263
     * Parameters with default values have an additional array index of
1264
     * 'default' with the value of the default as a string.
1265
     *
1266
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1267
     * class, but with some improvements which have been introduced in
1268
     * PHPCS 2.8.0.
1269
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1117},
1270
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1193} and
1271
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1293}.
1272
     *
1273
     * Once the minimum supported PHPCS version for this standard goes beyond
1274
     * that, this method can be removed and calls to it replaced with
1275
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.
1276
     *
1277
     * NOTE: This version does not deal with the new T_NULLABLE token type.
1278
     * This token is included upstream only in 2.8.0+ and as we defer to upstream
1279
     * in that case, no need to deal with it here.
1280
     *
1281
     * Last synced with PHPCS version: PHPCS 2.9.0-alpha at commit f1511adad043edfd6d2e595e77385c32577eb2bc}}
1282
     *
1283
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1284
     * @param int                   $stackPtr  The position in the stack of the
1285
     *                                         function token to acquire the
1286
     *                                         parameters for.
1287
     *
1288
     * @return array|false
1289
     * @throws \PHP_CodeSniffer_Exception If the specified $stackPtr is not of
1290
     *                                    type T_FUNCTION or T_CLOSURE.
1291
     */
1292
    public function getMethodParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1293
    {
1294
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
1295
            return $phpcsFile->getMethodParameters($stackPtr);
1296
        }
1297
1298
        $tokens = $phpcsFile->getTokens();
1299
1300
        // Check for the existence of the token.
1301
        if (isset($tokens[$stackPtr]) === false) {
1302
            return false;
1303
        }
1304
1305 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1306
            throw new \PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION or T_CLOSURE');
1307
        }
1308
1309
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
1310
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
1311
1312
        $vars            = array();
1313
        $currVar         = null;
1314
        $paramStart      = ($opener + 1);
1315
        $defaultStart    = null;
1316
        $paramCount      = 0;
1317
        $passByReference = false;
1318
        $variableLength  = false;
1319
        $typeHint        = '';
1320
        $nullableType    = false;
1321
1322
        for ($i = $paramStart; $i <= $closer; $i++) {
1323
            // Check to see if this token has a parenthesis or bracket opener. If it does
1324
            // it's likely to be an array which might have arguments in it. This
1325
            // could cause problems in our parsing below, so lets just skip to the
1326
            // end of it.
1327 View Code Duplication
            if (isset($tokens[$i]['parenthesis_opener']) === true) {
1328
                // Don't do this if it's the close parenthesis for the method.
1329
                if ($i !== $tokens[$i]['parenthesis_closer']) {
1330
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
1331
                }
1332
            }
1333
1334 View Code Duplication
            if (isset($tokens[$i]['bracket_opener']) === true) {
1335
                // Don't do this if it's the close parenthesis for the method.
1336
                if ($i !== $tokens[$i]['bracket_closer']) {
1337
                    $i = ($tokens[$i]['bracket_closer'] + 1);
1338
                }
1339
            }
1340
1341
            switch ($tokens[$i]['type']) {
1342
                case 'T_BITWISE_AND':
1343
                    $passByReference = true;
1344
                    break;
1345
                case 'T_VARIABLE':
1346
                    $currVar = $i;
1347
                    break;
1348
                case 'T_ELLIPSIS':
1349
                    $variableLength = true;
1350
                    break;
1351
                case 'T_ARRAY_HINT':
1352
                case 'T_CALLABLE':
1353
                    $typeHint .= $tokens[$i]['content'];
1354
                    break;
1355
                case 'T_SELF':
1356
                case 'T_PARENT':
1357
                case 'T_STATIC':
1358
                    // Self is valid, the others invalid, but were probably intended as type hints.
1359
                    if (isset($defaultStart) === false) {
1360
                        $typeHint .= $tokens[$i]['content'];
1361
                    }
1362
                    break;
1363
                case 'T_STRING':
1364
                    // This is a string, so it may be a type hint, but it could
1365
                    // also be a constant used as a default value.
1366
                    $prevComma = false;
1367 View Code Duplication
                    for ($t = $i; $t >= $opener; $t--) {
1368
                        if ($tokens[$t]['code'] === T_COMMA) {
1369
                            $prevComma = $t;
1370
                            break;
1371
                        }
1372
                    }
1373
1374
                    if ($prevComma !== false) {
1375
                        $nextEquals = false;
1376 View Code Duplication
                        for ($t = $prevComma; $t < $i; $t++) {
1377
                            if ($tokens[$t]['code'] === T_EQUAL) {
1378
                                $nextEquals = $t;
1379
                                break;
1380
                            }
1381
                        }
1382
1383
                        if ($nextEquals !== false) {
1384
                            break;
1385
                        }
1386
                    }
1387
1388
                    if ($defaultStart === null) {
1389
                        $typeHint .= $tokens[$i]['content'];
1390
                    }
1391
                    break;
1392
                case 'T_NS_SEPARATOR':
1393
                    // Part of a type hint or default value.
1394
                    if ($defaultStart === null) {
1395
                        $typeHint .= $tokens[$i]['content'];
1396
                    }
1397
                    break;
1398
                case 'T_INLINE_THEN':
1399
                    if ($defaultStart === null) {
1400
                        $nullableType = true;
1401
                        $typeHint    .= $tokens[$i]['content'];
1402
                    }
1403
                    break;
1404
                case 'T_CLOSE_PARENTHESIS':
1405
                case 'T_COMMA':
1406
                    // If it's null, then there must be no parameters for this
1407
                    // method.
1408
                    if ($currVar === null) {
1409
                        continue;
1410
                    }
1411
1412
                    $vars[$paramCount]            = array();
1413
                    $vars[$paramCount]['token']   = $currVar;
1414
                    $vars[$paramCount]['name']    = $tokens[$currVar]['content'];
1415
                    $vars[$paramCount]['content'] = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
1416
1417
                    if ($defaultStart !== null) {
1418
                        $vars[$paramCount]['default']
1419
                            = trim($phpcsFile->getTokensAsString(
1420
                                $defaultStart,
1421
                                ($i - $defaultStart)
1422
                            ));
1423
                    }
1424
1425
                    $vars[$paramCount]['pass_by_reference'] = $passByReference;
1426
                    $vars[$paramCount]['variable_length']   = $variableLength;
1427
                    $vars[$paramCount]['type_hint']         = $typeHint;
1428
                    $vars[$paramCount]['nullable_type']     = $nullableType;
1429
1430
                    // Reset the vars, as we are about to process the next parameter.
1431
                    $defaultStart    = null;
1432
                    $paramStart      = ($i + 1);
1433
                    $passByReference = false;
1434
                    $variableLength  = false;
1435
                    $typeHint        = '';
1436
                    $nullableType    = false;
1437
1438
                    $paramCount++;
1439
                    break;
1440
                case 'T_EQUAL':
1441
                    $defaultStart = ($i + 1);
1442
                    break;
1443
            }//end switch
1444
        }//end for
1445
1446
        return $vars;
1447
1448
    }//end getMethodParameters()
1449
1450
1451
    /**
1452
     * Returns the name of the class that the specified class extends
1453
     * (works for classes, anonymous classes and interfaces).
1454
     *
1455
     * Returns FALSE on error or if there is no extended class name.
1456
     *
1457
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1458
     * class, but with some improvements which have been introduced in
1459
     * PHPCS 2.8.0.
1460
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/commit/0011d448119d4c568e3ac1f825ae78815bf2cc34}.
1461
     *
1462
     * Once the minimum supported PHPCS version for this standard goes beyond
1463
     * that, this method can be removed and calls to it replaced with
1464
     * `$phpcsFile->findExtendedClassName($stackPtr)` calls.
1465
     *
1466
     * Last synced with PHPCS version: PHPCS 3.1.0-alpha at commit a9efcc9b0703f3f9f4a900623d4e97128a6aafc6}}
1467
     *
1468
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1469
     * @param int                   $stackPtr  The position of the class token in the stack.
1470
     *
1471
     * @return string|false
1472
     */
1473
    public function findExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1474
    {
1475
        if (version_compare(PHPCSHelper::getVersion(), '3.1.0', '>=') === true) {
1476
            return $phpcsFile->findExtendedClassName($stackPtr);
1477
        }
1478
1479
        $tokens = $phpcsFile->getTokens();
1480
1481
        // Check for the existence of the token.
1482
        if (isset($tokens[$stackPtr]) === false) {
1483
            return false;
1484
        }
1485
1486 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
1487
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
1488
            && $tokens[$stackPtr]['type'] !== 'T_INTERFACE'
1489
        ) {
1490
            return false;
1491
        }
1492
1493
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
1494
            return false;
1495
        }
1496
1497
        $classCloserIndex = $tokens[$stackPtr]['scope_closer'];
1498
        $extendsIndex     = $phpcsFile->findNext(T_EXTENDS, $stackPtr, $classCloserIndex);
1499
        if (false === $extendsIndex) {
1500
            return false;
1501
        }
1502
1503
        $find = array(
1504
                 T_NS_SEPARATOR,
1505
                 T_STRING,
1506
                 T_WHITESPACE,
1507
                );
1508
1509
        $end  = $phpcsFile->findNext($find, ($extendsIndex + 1), $classCloserIndex, true);
1510
        $name = $phpcsFile->getTokensAsString(($extendsIndex + 1), ($end - $extendsIndex - 1));
1511
        $name = trim($name);
1512
1513
        if ($name === '') {
1514
            return false;
1515
        }
1516
1517
        return $name;
1518
1519
    }//end findExtendedClassName()
1520
1521
1522
    /**
1523
     * Get the hash algorithm name from the parameter in a hash function call.
1524
     *
1525
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1526
     * @param int                   $stackPtr  The position of the T_STRING function token.
1527
     *
1528
     * @return string|false The algorithm name without quotes if this was a relevant hash
1529
     *                      function call or false if it was not.
1530
     */
1531
    public function getHashAlgorithmParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1532
    {
1533
        $tokens = $phpcsFile->getTokens();
1534
1535
        // Check for the existence of the token.
1536
        if (isset($tokens[$stackPtr]) === false) {
1537
            return false;
1538
        }
1539
1540
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1541
            return false;
1542
        }
1543
1544
        $functionName   = $tokens[$stackPtr]['content'];
1545
        $functionNameLc = strtolower($functionName);
1546
1547
        // Bow out if not one of the functions we're targetting.
1548
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
1549
            return false;
1550
        }
1551
1552
        // Get the parameter from the function call which should contain the algorithm name.
1553
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
1554
        if ($algoParam === false) {
1555
            return false;
1556
        }
1557
1558
        // Algorithm is a text string, so we need to remove the quotes.
1559
        $algo = strtolower(trim($algoParam['raw']));
1560
        $algo = $this->stripQuotes($algo);
1561
1562
        return $algo;
1563
    }
1564
1565
1566
    /**
1567
     * Determine whether an arbitrary T_STRING token is the use of a global constant.
1568
     *
1569
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1570
     * @param int                   $stackPtr  The position of the function call token.
1571
     *
1572
     * @return bool
1573
     */
1574
    public function isUseOfGlobalConstant(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1575
    {
1576
        static $isLowPHPCS, $isLowPHP;
1577
1578
        $tokens = $phpcsFile->getTokens();
1579
1580
        // Check for the existence of the token.
1581
        if (isset($tokens[$stackPtr]) === false) {
1582
            return false;
1583
        }
1584
1585
        // Is this one of the tokens this function handles ?
1586
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1587
            return false;
1588
        }
1589
1590
        // Check for older PHP, PHPCS version so we can compensate for misidentified tokens.
1591
        if (isset($isLowPHPCS, $isLowPHP) === false) {
1592
            $isLowPHP   = false;
1593
            $isLowPHPCS = false;
1594
            if (version_compare(PHP_VERSION_ID, '50400', '<')) {
1595
                $isLowPHP   = true;
1596
                $isLowPHPCS = version_compare(PHPCSHelper::getVersion(), '2.4.0', '<');
1597
            }
1598
        }
1599
1600
        $next = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
1601
        if ($next !== false
1602
            && ($tokens[$next]['code'] === T_OPEN_PARENTHESIS
1603
                || $tokens[$next]['code'] === T_DOUBLE_COLON)
1604
        ) {
1605
            // Function call or declaration.
1606
            return false;
1607
        }
1608
1609
        // Array of tokens which if found preceding the $stackPtr indicate that a T_STRING is not a global constant.
1610
        $tokensToIgnore = array(
1611
            'T_NAMESPACE'       => true,
1612
            'T_USE'             => true,
1613
            'T_CLASS'           => true,
1614
            'T_TRAIT'           => true,
1615
            'T_INTERFACE'       => true,
1616
            'T_EXTENDS'         => true,
1617
            'T_IMPLEMENTS'      => true,
1618
            'T_NEW'             => true,
1619
            'T_FUNCTION'        => true,
1620
            'T_DOUBLE_COLON'    => true,
1621
            'T_OBJECT_OPERATOR' => true,
1622
            'T_INSTANCEOF'      => true,
1623
            'T_INSTEADOF'       => true,
1624
            'T_GOTO'            => true,
1625
            'T_AS'              => true,
1626
            'T_PUBLIC'          => true,
1627
            'T_PROTECTED'       => true,
1628
            'T_PRIVATE'         => true,
1629
        );
1630
1631
        $prev = $phpcsFile->findPrevious(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
1632
        if ($prev !== false
1633
            && (isset($tokensToIgnore[$tokens[$prev]['type']]) === true)
1634
                || ($tokens[$prev]['code'] === T_STRING
1635
                    && (($isLowPHPCS === true
1636
                        && $tokens[$prev]['content'] === 'trait')
1637
                    || ($isLowPHP === true
1638
                        && $tokens[$prev]['content'] === 'insteadof')))
1639
        ) {
1640
            // Not the use of a constant.
1641
            return false;
1642
        }
1643
1644
        if ($prev !== false
1645
            && $tokens[$prev]['code'] === T_NS_SEPARATOR
1646
            && $tokens[($prev - 1)]['code'] === T_STRING
1647
        ) {
1648
            // Namespaced constant of the same name.
1649
            return false;
1650
        }
1651
1652
        if ($prev !== false
1653
            && $tokens[$prev]['code'] === T_CONST
1654
            && $this->isClassConstant($phpcsFile, $prev) === true
1655
        ) {
1656
            // Class constant declaration of the same name.
1657
            return false;
1658
        }
1659
1660
        /*
1661
         * Deal with a number of variations of use statements.
1662
         */
1663
        for ($i = $stackPtr; $i > 0; $i--) {
1664
            if ($tokens[$i]['line'] !== $tokens[$stackPtr]['line']) {
1665
                break;
1666
            }
1667
        }
1668
1669
        $firstOnLine = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($i + 1), null, true);
1670
        if ($firstOnLine !== false && $tokens[$firstOnLine]['code'] === T_USE) {
1671
            $nextOnLine = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($firstOnLine + 1), null, true);
1672
            if ($nextOnLine !== false) {
1673
                if (($tokens[$nextOnLine]['code'] === T_STRING && $tokens[$nextOnLine]['content'] === 'const')
1674
                    || $tokens[$nextOnLine]['code'] === T_CONST // Happens in some PHPCS versions.
1675
                ) {
1676
                    $hasNsSep = $phpcsFile->findNext(T_NS_SEPARATOR, ($nextOnLine + 1), $stackPtr);
1677
                    if ($hasNsSep !== false) {
1678
                        // Namespaced const (group) use statement.
1679
                        return false;
1680
                    }
1681
                } else {
1682
                    // Not a const use statement.
1683
                    return false;
1684
                }
1685
            }
1686
        }
1687
1688
        return true;
1689
    }
1690
1691
}//end class
1692