Completed
Push — feature/new-constants-sniff ( 425a81 )
by Juliette
01:44
created

Sniff::isUseOfGlobalConstant()   D

Complexity

Conditions 30
Paths 59

Size

Total Lines 116
Code Lines 69

Duplication

Lines 7
Ratio 6.03 %

Importance

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