Completed
Pull Request — master (#526)
by Juliette
03:21 queued 01:43
created

Sniff::getHashAlgorithmParameter()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 33
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 33
rs 8.439
c 0
b 0
f 0
cc 5
eloc 16
nc 5
nop 2
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
        $default     = array(null, null);
109
        $testVersion = trim(PHPCSHelper::getConfigData('testVersion'));
110
111
        if (empty($testVersion) === false && isset($arrTestVersions[$testVersion]) === false) {
112
113
            $arrTestVersions[$testVersion] = $default;
114
115
            if (preg_match('`^\d+\.\d+$`', $testVersion)) {
116
                $arrTestVersions[$testVersion] = array($testVersion, $testVersion);
117
                return $arrTestVersions[$testVersion];
118
            }
119
120
            if (preg_match('`^(\d+\.\d+)?\s*-\s*(\d+\.\d+)?$`', $testVersion, $matches)) {
121
                if (empty($matches[1]) === false || empty($matches[2]) === false) {
122
                    // If no lower-limit is set, we set the min version to 4.0.
123
                    // Whilst development focuses on PHP 5 and above, we also accept
124
                    // sniffs for PHP 4, so we include that as the minimum.
125
                    // (It makes no sense to support PHP 3 as this was effectively a
126
                    // different language).
127
                    $min = empty($matches[1]) ? '4.0' : $matches[1];
128
129
                    // If no upper-limit is set, we set the max version to 99.9.
130
                    $max = empty($matches[2]) ? '99.9' : $matches[2];
131
132
                    if (version_compare($min, $max, '>')) {
133
                        trigger_error(
134
                            "Invalid range in testVersion setting: '" . $testVersion . "'",
135
                            E_USER_WARNING
136
                        );
137
                        return $default;
138
                    }
139
                    else {
140
                        $arrTestVersions[$testVersion] = array($min, $max);
141
                        return $arrTestVersions[$testVersion];
142
                    }
143
                }
144
            }
145
146
            trigger_error(
147
                "Invalid testVersion setting: '" . $testVersion . "'",
148
                E_USER_WARNING
149
            );
150
            return $default;
151
        }
152
153
        if (isset($arrTestVersions[$testVersion])) {
154
            return $arrTestVersions[$testVersion];
155
        }
156
157
        return $default;
158
    }
159
160
161
    /**
162
     * Check whether a specific PHP version is equal to or higher than the maximum
163
     * supported PHP version as provided by the user in `testVersion`.
164
     *
165
     * Should be used when sniffing for *old* PHP features (deprecated/removed).
166
     *
167
     * @param string $phpVersion A PHP version number in 'major.minor' format.
168
     *
169
     * @return bool True if testVersion has not been provided or if the PHP version
170
     *              is equal to or higher than the highest supported PHP version
171
     *              in testVersion. False otherwise.
172
     */
173 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...
174
    {
175
        $testVersion = $this->getTestVersion();
176
        $testVersion = $testVersion[1];
177
178
        if (is_null($testVersion)
179
            || version_compare($testVersion, $phpVersion) >= 0
180
        ) {
181
            return true;
182
        } else {
183
            return false;
184
        }
185
    }//end supportsAbove()
186
187
188
    /**
189
     * Check whether a specific PHP version is equal to or lower than the minimum
190
     * supported PHP version as provided by the user in `testVersion`.
191
     *
192
     * Should be used when sniffing for *new* PHP features.
193
     *
194
     * @param string $phpVersion A PHP version number in 'major.minor' format.
195
     *
196
     * @return bool True if the PHP version is equal to or lower than the lowest
197
     *              supported PHP version in testVersion.
198
     *              False otherwise or if no testVersion is provided.
199
     */
200 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...
201
    {
202
        $testVersion = $this->getTestVersion();
203
        $testVersion = $testVersion[0];
204
205
        if (is_null($testVersion) === false
206
            && version_compare($testVersion, $phpVersion) <= 0
207
        ) {
208
            return true;
209
        } else {
210
            return false;
211
        }
212
    }//end supportsBelow()
213
214
215
    /**
216
     * Add a PHPCS message to the output stack as either a warning or an error.
217
     *
218
     * @param \PHP_CodeSniffer_File $phpcsFile The file the message applies to.
219
     * @param string                $message   The message.
220
     * @param int                   $stackPtr  The position of the token
221
     *                                         the message relates to.
222
     * @param bool                  $isError   Whether to report the message as an
223
     *                                         'error' or 'warning'.
224
     *                                         Defaults to true (error).
225
     * @param string                $code      The error code for the message.
226
     *                                         Defaults to 'Found'.
227
     * @param array                 $data      Optional input for the data replacements.
228
     *
229
     * @return void
230
     */
231
    public function addMessage(\PHP_CodeSniffer_File $phpcsFile, $message, $stackPtr, $isError, $code = 'Found', $data = array())
232
    {
233
        if ($isError === true) {
234
            $phpcsFile->addError($message, $stackPtr, $code, $data);
235
        } else {
236
            $phpcsFile->addWarning($message, $stackPtr, $code, $data);
237
        }
238
    }
239
240
241
    /**
242
     * Convert an arbitrary string to an alphanumeric string with underscores.
243
     *
244
     * Pre-empt issues with arbitrary strings being used as error codes in XML and PHP.
245
     *
246
     * @param string $baseString Arbitrary string.
247
     *
248
     * @return string
249
     */
250
    public function stringToErrorCode($baseString)
251
    {
252
        return preg_replace('`[^a-z0-9_]`i', '_', strtolower($baseString));
253
    }
254
255
256
    /**
257
     * Strip quotes surrounding an arbitrary string.
258
     *
259
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING / T_DOUBLE_QUOTED_STRING.
260
     *
261
     * @param string $string The raw string.
262
     *
263
     * @return string String without quotes around it.
264
     */
265
    public function stripQuotes($string)
266
    {
267
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
268
    }
269
270
271
    /**
272
     * Strip variables from an arbitrary double quoted string.
273
     *
274
     * Intended for use with the content of a T_DOUBLE_QUOTED_STRING.
275
     *
276
     * @param string $string The raw string.
277
     *
278
     * @return string String without variables in it.
279
     */
280
    public function stripVariables($string)
281
    {
282
        if (strpos($string, '$') === false) {
283
            return $string;
284
        }
285
286
        return preg_replace(self::REGEX_COMPLEX_VARS, '', $string);
287
    }
288
289
290
    /**
291
     * Make all top level array keys in an array lowercase.
292
     *
293
     * @param array $array Initial array.
294
     *
295
     * @return array Same array, but with all lowercase top level keys.
296
     */
297
    public function arrayKeysToLowercase($array)
298
    {
299
        $keys = array_keys($array);
300
        $keys = array_map('strtolower', $keys);
301
        return array_combine($keys, $array);
302
    }
303
304
305
    /**
306
     * Returns the name(s) of the interface(s) that the specified class implements.
307
     *
308
     * Returns FALSE on error or if there are no implemented interface names.
309
     *
310
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
311
     * This method also includes an improvement we use which was only introduced
312
     * in PHPCS 2.8.0, so only defer to upstream for higher versions.
313
     * Once the minimum supported PHPCS version for this sniff library goes beyond
314
     * that, this method can be removed and calls to it replaced with
315
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
316
     *
317
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
318
     * @param int                   $stackPtr  The position of the class token.
319
     *
320
     * @return array|false
321
     */
322
    public function findImplementedInterfaceNames(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
323
    {
324
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
325
            return $phpcsFile->findImplementedInterfaceNames($stackPtr);
326
        }
327
328
        $tokens = $phpcsFile->getTokens();
329
330
        // Check for the existence of the token.
331
        if (isset($tokens[$stackPtr]) === false) {
332
            return false;
333
        }
334
335
        if ($tokens[$stackPtr]['code'] !== T_CLASS
336
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
337
        ) {
338
            return false;
339
        }
340
341
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
342
            return false;
343
        }
344
345
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
346
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
347
        if ($implementsIndex === false) {
348
            return false;
349
        }
350
351
        $find = array(
352
            T_NS_SEPARATOR,
353
            T_STRING,
354
            T_WHITESPACE,
355
            T_COMMA,
356
        );
357
358
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
359
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
360
        $name = trim($name);
361
362
        if ($name === '') {
363
            return false;
364
        } else {
365
            $names = explode(',', $name);
366
            $names = array_map('trim', $names);
367
            return $names;
368
        }
369
370
    }//end findImplementedInterfaceNames()
371
372
373
    /**
374
     * Checks if a function call has parameters.
375
     *
376
     * Expects to be passed the T_STRING stack pointer for the function call.
377
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
378
     *
379
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer, it
380
     * will detect whether the array has values or is empty.
381
     *
382
     * @link https://github.com/wimg/PHPCompatibility/issues/120
383
     * @link https://github.com/wimg/PHPCompatibility/issues/152
384
     *
385
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
386
     * @param int                   $stackPtr  The position of the function call token.
387
     *
388
     * @return bool
389
     */
390
    public function doesFunctionCallHaveParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
391
    {
392
        $tokens = $phpcsFile->getTokens();
393
394
        // Check for the existence of the token.
395
        if (isset($tokens[$stackPtr]) === false) {
396
            return false;
397
        }
398
399
        // Is this one of the tokens this function handles ?
400
        if (in_array($tokens[$stackPtr]['code'], array(T_STRING, T_ARRAY, T_OPEN_SHORT_ARRAY), true) === false) {
401
            return false;
402
        }
403
404
        $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
405
406
        // Deal with short array syntax.
407
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
408
            if (isset($tokens[$stackPtr]['bracket_closer']) === false) {
409
                return false;
410
            }
411
412
            if ($nextNonEmpty === $tokens[$stackPtr]['bracket_closer']) {
413
                // No parameters.
414
                return false;
415
            } else {
416
                return true;
417
            }
418
        }
419
420
        // Deal with function calls & long arrays.
421
        // Next non-empty token should be the open parenthesis.
422
        if ($nextNonEmpty === false && $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS) {
423
            return false;
424
        }
425
426
        if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
427
            return false;
428
        }
429
430
        $closeParenthesis = $tokens[$nextNonEmpty]['parenthesis_closer'];
431
        $nextNextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextNonEmpty + 1, $closeParenthesis + 1, true);
432
433
        if ($nextNextNonEmpty === $closeParenthesis) {
434
            // No parameters.
435
            return false;
436
        }
437
438
        return true;
439
    }
440
441
442
    /**
443
     * Count the number of parameters a function call has been passed.
444
     *
445
     * Expects to be passed the T_STRING stack pointer for the function call.
446
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
447
     *
448
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
449
     * it will return the number of values in the array.
450
     *
451
     * @link https://github.com/wimg/PHPCompatibility/issues/111
452
     * @link https://github.com/wimg/PHPCompatibility/issues/114
453
     * @link https://github.com/wimg/PHPCompatibility/issues/151
454
     *
455
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
456
     * @param int                   $stackPtr  The position of the function call token.
457
     *
458
     * @return int
459
     */
460
    public function getFunctionCallParameterCount(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
461
    {
462
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
463
            return 0;
464
        }
465
466
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
467
    }
468
469
470
    /**
471
     * Get information on all parameters passed to a function call.
472
     *
473
     * Expects to be passed the T_STRING stack pointer for the function call.
474
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
475
     *
476
     * Will return an multi-dimentional array with the start token pointer, end token
477
     * pointer and raw parameter value for all parameters. Index will be 1-based.
478
     * If no parameters are found, will return an empty array.
479
     *
480
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
481
     * it will tokenize the values / key/value pairs contained in the array call.
482
     *
483
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
484
     * @param int                   $stackPtr  The position of the function call token.
485
     *
486
     * @return array
487
     */
488
    public function getFunctionCallParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
489
    {
490
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
491
            return array();
492
        }
493
494
        // Ok, we know we have a T_STRING, T_ARRAY or T_OPEN_SHORT_ARRAY with parameters
495
        // and valid open & close brackets/parenthesis.
496
        $tokens = $phpcsFile->getTokens();
497
498
        // Mark the beginning and end tokens.
499
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
500
            $opener = $stackPtr;
501
            $closer = $tokens[$stackPtr]['bracket_closer'];
502
503
            $nestedParenthesisCount = 0;
504
505
        } else {
506
            $opener = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
507
            $closer = $tokens[$opener]['parenthesis_closer'];
508
509
            $nestedParenthesisCount = 1;
510
        }
511
512
        // Which nesting level is the one we are interested in ?
513 View Code Duplication
        if (isset($tokens[$opener]['nested_parenthesis'])) {
514
            $nestedParenthesisCount += count($tokens[$opener]['nested_parenthesis']);
515
        }
516
517
        $parameters = array();
518
        $nextComma  = $opener;
519
        $paramStart = $opener + 1;
520
        $cnt        = 1;
521
        while (($nextComma = $phpcsFile->findNext(array(T_COMMA, $tokens[$closer]['code'], T_OPEN_SHORT_ARRAY), $nextComma + 1, $closer + 1)) !== false) {
522
            // Ignore anything within short array definition brackets.
523
            if ($tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
524
                && (isset($tokens[$nextComma]['bracket_opener'])
525
                    && $tokens[$nextComma]['bracket_opener'] === $nextComma)
526
                && isset($tokens[$nextComma]['bracket_closer'])
527
            ) {
528
                // Skip forward to the end of the short array definition.
529
                $nextComma = $tokens[$nextComma]['bracket_closer'];
530
                continue;
531
            }
532
533
            // Ignore comma's at a lower nesting level.
534
            if ($tokens[$nextComma]['type'] === 'T_COMMA'
535
                && isset($tokens[$nextComma]['nested_parenthesis'])
536
                && count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
537
            ) {
538
                continue;
539
            }
540
541
            // Ignore closing parenthesis/bracket if not 'ours'.
542
            if ($tokens[$nextComma]['type'] === $tokens[$closer]['type'] && $nextComma !== $closer) {
543
                continue;
544
            }
545
546
            // Ok, we've reached the end of the parameter.
547
            $parameters[$cnt]['start'] = $paramStart;
548
            $parameters[$cnt]['end']   = $nextComma - 1;
549
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
550
551
            // Check if there are more tokens before the closing parenthesis.
552
            // Prevents code like the following from setting a third parameter:
553
            // 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...
554
            $hasNextParam = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closer, true, null, true);
555
            if ($hasNextParam === false) {
556
                break;
557
            }
558
559
            // Prepare for the next parameter.
560
            $paramStart = $nextComma + 1;
561
            $cnt++;
562
        }
563
564
        return $parameters;
565
    }
566
567
568
    /**
569
     * Get information on a specific parameter passed to a function call.
570
     *
571
     * Expects to be passed the T_STRING stack pointer for the function call.
572
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
573
     *
574
     * Will return a array with the start token pointer, end token pointer and the raw value
575
     * of the parameter at a specific offset.
576
     * If the specified parameter is not found, will return false.
577
     *
578
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
579
     * @param int                   $stackPtr    The position of the function call token.
580
     * @param int                   $paramOffset The 1-based index position of the parameter to retrieve.
581
     *
582
     * @return array|false
583
     */
584
    public function getFunctionCallParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
585
    {
586
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
587
588
        if (isset($parameters[$paramOffset]) === false) {
589
            return false;
590
        } else {
591
            return $parameters[$paramOffset];
592
        }
593
    }
594
595
596
    /**
597
     * Verify whether a token is within a scoped condition.
598
     *
599
     * If the optional $validScopes parameter has been passed, the function
600
     * will check that the token has at least one condition which is of a
601
     * type defined in $validScopes.
602
     *
603
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
604
     * @param int                   $stackPtr    The position of the token.
605
     * @param array|int             $validScopes Optional. Array of valid scopes
606
     *                                           or int value of a valid scope.
607
     *                                           Pass the T_.. constant(s) for the
608
     *                                           desired scope to this parameter.
609
     *
610
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
611
     *              If the $scopeTypes are set: True if *one* of the conditions is a
612
     *              valid scope, false otherwise.
613
     */
614
    public function tokenHasScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
615
    {
616
        $tokens = $phpcsFile->getTokens();
617
618
        // Check for the existence of the token.
619
        if (isset($tokens[$stackPtr]) === false) {
620
            return false;
621
        }
622
623
        // No conditions = no scope.
624
        if (empty($tokens[$stackPtr]['conditions'])) {
625
            return false;
626
        }
627
628
        // Ok, there are conditions, do we have to check for specific ones ?
629
        if (isset($validScopes) === false) {
630
            return true;
631
        }
632
633
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
634
    }
635
636
637
    /**
638
     * Verify whether a token is within a class scope.
639
     *
640
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
641
     * @param int                   $stackPtr  The position of the token.
642
     * @param bool                  $strict    Whether to strictly check for the T_CLASS
643
     *                                         scope or also accept interfaces and traits
644
     *                                         as scope.
645
     *
646
     * @return bool True if within class scope, false otherwise.
647
     */
648
    public function inClassScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
649
    {
650
        $validScopes = array(T_CLASS);
651
        if (defined('T_ANON_CLASS') === true) {
652
            $validScopes[] = T_ANON_CLASS;
653
        }
654
655
        if ($strict === false) {
656
            $validScopes[] = T_INTERFACE;
657
658
            if (defined('T_TRAIT')) {
659
                $validScopes[] = constant('T_TRAIT');
660
            }
661
        }
662
663
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
664
    }
665
666
667
    /**
668
     * Verify whether a token is within a scoped use statement.
669
     *
670
     * PHPCS cross-version compatibility method.
671
     *
672
     * In PHPCS 1.x no conditions are set for a scoped use statement.
673
     * This method works around that limitation.
674
     *
675
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
676
     * @param int                   $stackPtr  The position of the token.
677
     *
678
     * @return bool True if within use scope, false otherwise.
679
     */
680
    public function inUseScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
681
    {
682
        static $isLowPHPCS, $ignoreTokens;
683
684
        if (isset($isLowPHPCS) === false) {
685
            $isLowPHPCS = version_compare(PHPCSHelper::getVersion(), '2.3.0', '<');
686
        }
687
        if (isset($ignoreTokens) === false) {
688
            $ignoreTokens              = \PHP_CodeSniffer_Tokens::$emptyTokens;
689
            $ignoreTokens[T_STRING]    = T_STRING;
690
            $ignoreTokens[T_AS]        = T_AS;
691
            $ignoreTokens[T_PUBLIC]    = T_PUBLIC;
692
            $ignoreTokens[T_PROTECTED] = T_PROTECTED;
693
            $ignoreTokens[T_PRIVATE]   = T_PRIVATE;
694
        }
695
696
        // PHPCS 2.0.
697
        if ($isLowPHPCS === false) {
698
            return $phpcsFile->hasCondition($stackPtr, T_USE);
699
        } else {
700
            // PHPCS 1.x.
701
            $tokens         = $phpcsFile->getTokens();
702
            $maybeCurlyOpen = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
703
            if ($tokens[$maybeCurlyOpen]['code'] === T_OPEN_CURLY_BRACKET) {
704
                $maybeUseStatement = $phpcsFile->findPrevious($ignoreTokens, ($maybeCurlyOpen - 1), null, true);
705
                if ($tokens[$maybeUseStatement]['code'] === T_USE) {
706
                    return true;
707
                }
708
            }
709
            return false;
710
        }
711
    }
712
713
714
    /**
715
     * Returns the fully qualified class name for a new class instantiation.
716
     *
717
     * Returns an empty string if the class name could not be reliably inferred.
718
     *
719
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
720
     * @param int                   $stackPtr  The position of a T_NEW token.
721
     *
722
     * @return string
723
     */
724
    public function getFQClassNameFromNewToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
725
    {
726
        $tokens = $phpcsFile->getTokens();
727
728
        // Check for the existence of the token.
729
        if (isset($tokens[$stackPtr]) === false) {
730
            return '';
731
        }
732
733
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
734
            return '';
735
        }
736
737
        $start = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
738
        if ($start === false) {
739
            return '';
740
        }
741
742
        // Bow out if the next token is a variable as we don't know where it was defined.
743
        if ($tokens[$start]['code'] === T_VARIABLE) {
744
            return '';
745
        }
746
747
        // Bow out if the next token is the class keyword.
748
        if ($tokens[$start]['type'] === 'T_ANON_CLASS' || $tokens[$start]['code'] === T_CLASS) {
749
            return '';
750
        }
751
752
        $find = array(
753
            T_NS_SEPARATOR,
754
            T_STRING,
755
            T_NAMESPACE,
756
            T_WHITESPACE,
757
        );
758
759
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
760
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
761
        $className = trim($className);
762
763
        return $this->getFQName($phpcsFile, $stackPtr, $className);
764
    }
765
766
767
    /**
768
     * Returns the fully qualified name of the class that the specified class extends.
769
     *
770
     * Returns an empty string if the class does not extend another class or if
771
     * the class name could not be reliably inferred.
772
     *
773
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
774
     * @param int                   $stackPtr  The position of a T_CLASS token.
775
     *
776
     * @return string
777
     */
778
    public function getFQExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
779
    {
780
        $tokens = $phpcsFile->getTokens();
781
782
        // Check for the existence of the token.
783
        if (isset($tokens[$stackPtr]) === false) {
784
            return '';
785
        }
786
787 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
788
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
789
            && $tokens[$stackPtr]['type'] !== 'T_INTERFACE'
790
        ) {
791
            return '';
792
        }
793
794
        $extends = $this->findExtendedClassName($phpcsFile, $stackPtr);
795
        if (empty($extends) || is_string($extends) === false) {
796
            return '';
797
        }
798
799
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
800
    }
801
802
803
    /**
804
     * Returns the class name for the static usage of a class.
805
     * This can be a call to a method, the use of a property or constant.
806
     *
807
     * Returns an empty string if the class name could not be reliably inferred.
808
     *
809
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
810
     * @param int                   $stackPtr  The position of a T_NEW token.
811
     *
812
     * @return string
813
     */
814
    public function getFQClassNameFromDoubleColonToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
815
    {
816
        $tokens = $phpcsFile->getTokens();
817
818
        // Check for the existence of the token.
819
        if (isset($tokens[$stackPtr]) === false) {
820
            return '';
821
        }
822
823
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
824
            return '';
825
        }
826
827
        // Nothing to do if previous token is a variable as we don't know where it was defined.
828
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
829
            return '';
830
        }
831
832
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
833
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
834
            return '';
835
        }
836
837
        // Get the classname from the class declaration if self is used.
838
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
839
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
840
            if ($classDeclarationPtr === false) {
841
                return '';
842
            }
843
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
844
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
845
        }
846
847
        $find = array(
848
            T_NS_SEPARATOR,
849
            T_STRING,
850
            T_NAMESPACE,
851
            T_WHITESPACE,
852
        );
853
854
        $start = $phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true);
855
        if ($start === false || isset($tokens[($start + 1)]) === false) {
856
            return '';
857
        }
858
859
        $start     = ($start + 1);
860
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
861
        $className = trim($className);
862
863
        return $this->getFQName($phpcsFile, $stackPtr, $className);
864
    }
865
866
867
    /**
868
     * Get the Fully Qualified name for a class/function/constant etc.
869
     *
870
     * Checks if a class/function/constant name is already fully qualified and
871
     * if not, enrich it with the relevant namespace information.
872
     *
873
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
874
     * @param int                   $stackPtr  The position of the token.
875
     * @param string                $name      The class / function / constant name.
876
     *
877
     * @return string
878
     */
879
    public function getFQName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
880
    {
881
        if (strpos($name, '\\') === 0) {
882
            // Already fully qualified.
883
            return $name;
884
        }
885
886
        // Remove the namespace keyword if used.
887
        if (strpos($name, 'namespace\\') === 0) {
888
            $name = substr($name, 10);
889
        }
890
891
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
892
893
        if ($namespace === '') {
894
            return '\\' . $name;
895
        } else {
896
            return '\\' . $namespace . '\\' . $name;
897
        }
898
    }
899
900
901
    /**
902
     * Is the class/function/constant name namespaced or global ?
903
     *
904
     * @param string $FQName Fully Qualified name of a class, function etc.
905
     *                       I.e. should always start with a `\`.
906
     *
907
     * @return bool True if namespaced, false if global.
908
     */
909
    public function isNamespaced($FQName)
910
    {
911
        if (strpos($FQName, '\\') !== 0) {
912
            throw new \PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
913
        }
914
915
        return (strpos(substr($FQName, 1), '\\') !== false);
916
    }
917
918
919
    /**
920
     * Determine the namespace name an arbitrary token lives in.
921
     *
922
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
923
     * @param int                   $stackPtr  The token position for which to determine the namespace.
924
     *
925
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
926
     */
927
    public function determineNamespace(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
928
    {
929
        $tokens = $phpcsFile->getTokens();
930
931
        // Check for the existence of the token.
932
        if (isset($tokens[$stackPtr]) === false) {
933
            return '';
934
        }
935
936
        // Check for scoped namespace {}.
937
        if (empty($tokens[$stackPtr]['conditions']) === false) {
938
            $namespacePtr = $phpcsFile->getCondition($stackPtr, T_NAMESPACE);
939
            if ($namespacePtr !== false) {
940
                $namespace = $this->getDeclaredNamespaceName($phpcsFile, $namespacePtr);
941
                if ($namespace !== false) {
942
                    return $namespace;
943
                }
944
945
                // We are in a scoped namespace, but couldn't determine the name. Searching for a global namespace is futile.
946
                return '';
947
            }
948
        }
949
950
        /*
951
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
952
         * Keeping in mind that:
953
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
954
         * - the namespace keyword can also be used as part of a function/method call and such.
955
         * - that a non-named namespace resolves to the global namespace.
956
         */
957
        $previousNSToken = $stackPtr;
958
        $namespace       = false;
959
        do {
960
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, ($previousNSToken - 1));
961
962
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
963
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] === $previousNSToken) {
964
                break;
965
            }
966
967
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
968
969
        } while ($namespace === false && $previousNSToken !== false);
970
971
        // If we still haven't got a namespace, return an empty string.
972
        if ($namespace === false) {
973
            return '';
974
        } else {
975
            return $namespace;
976
        }
977
    }
978
979
    /**
980
     * Get the complete namespace name for a namespace declaration.
981
     *
982
     * For hierarchical namespaces, the name will be composed of several tokens,
983
     * i.e. MyProject\Sub\Level which will be returned together as one string.
984
     *
985
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
986
     * @param int|bool              $stackPtr  The position of a T_NAMESPACE token.
987
     *
988
     * @return string|false Namespace name or false if not a namespace declaration.
989
     *                      Namespace name can be an empty string for global namespace declaration.
990
     */
991
    public function getDeclaredNamespaceName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
992
    {
993
        $tokens = $phpcsFile->getTokens();
994
995
        // Check for the existence of the token.
996 View Code Duplication
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
997
            return false;
998
        }
999
1000
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
1001
            return false;
1002
        }
1003
1004
        if ($tokens[($stackPtr + 1)]['code'] === T_NS_SEPARATOR) {
1005
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
1006
            return false;
1007
        }
1008
1009
        $nextToken = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
1010
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
1011
            // Declaration for global namespace when using multiple namespaces in a file.
1012
            // I.e.: namespace {}
1013
            return '';
1014
        }
1015
1016
        // Ok, this should be a namespace declaration, so get all the parts together.
1017
        $validTokens = array(
1018
            T_STRING       => true,
1019
            T_NS_SEPARATOR => true,
1020
            T_WHITESPACE   => true,
1021
        );
1022
1023
        $namespaceName = '';
1024
        while (isset($validTokens[$tokens[$nextToken]['code']]) === true) {
1025
            $namespaceName .= trim($tokens[$nextToken]['content']);
1026
            $nextToken++;
1027
        }
1028
1029
        return $namespaceName;
1030
    }
1031
1032
1033
    /**
1034
     * Get the stack pointer for a return type token for a given function.
1035
     *
1036
     * Compatible layer for older PHPCS versions which don't recognize
1037
     * return type hints correctly.
1038
     *
1039
     * Expects to be passed T_RETURN_TYPE, T_FUNCTION or T_CLOSURE token.
1040
     *
1041
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1042
     * @param int                   $stackPtr  The position of the token.
1043
     *
1044
     * @return int|false Stack pointer to the return type token or false if
1045
     *                   no return type was found or the passed token was
1046
     *                   not of the correct type.
1047
     */
1048
    public function getReturnTypeHintToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1049
    {
1050
        $tokens = $phpcsFile->getTokens();
1051
1052
        if (defined('T_RETURN_TYPE') && $tokens[$stackPtr]['code'] === T_RETURN_TYPE) {
1053
            return $tokens[$stackPtr]['code'];
1054
        }
1055
1056 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1057
            return false;
1058
        }
1059
1060
        if (isset($tokens[$stackPtr]['parenthesis_closer'], $tokens[$stackPtr]['scope_opener']) === false
1061
            || ($tokens[$stackPtr]['parenthesis_closer'] + 1) === $tokens[$stackPtr]['scope_opener']
1062
        ) {
1063
            return false;
1064
        }
1065
1066
        $hasColon = $phpcsFile->findNext(array(T_COLON, T_INLINE_ELSE), ($tokens[$stackPtr]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']);
1067
        if ($hasColon === false) {
1068
            return false;
1069
        }
1070
1071
        // `self`, `parent` and `callable` are not being recognized as return types in PHPCS < 2.6.0.
1072
        $unrecognizedTypes = array(
1073
            T_CALLABLE,
1074
            T_SELF,
1075
            T_PARENT,
1076
        );
1077
1078
        // Return types are not recognized at all in PHPCS < 2.4.0.
1079
        if (defined('T_RETURN_TYPE') === false) {
1080
            $unrecognizedTypes[] = T_ARRAY;
1081
            $unrecognizedTypes[] = T_STRING;
1082
        }
1083
1084
        return $phpcsFile->findNext($unrecognizedTypes, ($hasColon + 1), $tokens[$stackPtr]['scope_opener']);
1085
    }
1086
1087
1088
    /**
1089
     * Check whether a T_VARIABLE token is a class property declaration.
1090
     *
1091
     * Compatibility layer for PHPCS cross-version compatibility
1092
     * as PHPCS 2.4.0 - 2.7.1 does not have good enough support for
1093
     * anonymous classes. Along the same lines, the`getMemberProperties()`
1094
     * method does not support the `var` prefix.
1095
     *
1096
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1097
     * @param int                   $stackPtr  The position in the stack of the
1098
     *                                         T_VARIABLE token to verify.
1099
     *
1100
     * @return bool
1101
     */
1102
    public function isClassProperty(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1103
    {
1104
        $tokens = $phpcsFile->getTokens();
1105
1106 View Code Duplication
        if (isset($tokens[$stackPtr]) === false || $tokens[$stackPtr]['code'] !== T_VARIABLE) {
1107
            return false;
1108
        }
1109
1110
        // Note: interfaces can not declare properties.
1111
        $validScopes = array(
1112
            'T_CLASS'      => true,
1113
            'T_ANON_CLASS' => true,
1114
            'T_TRAIT'      => true,
1115
        );
1116
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1117
            // Make sure it's not a method parameter.
1118
            if (empty($tokens[$stackPtr]['nested_parenthesis']) === true) {
1119
                return true;
1120
            }
1121
        }
1122
1123
        return false;
1124
    }
1125
1126
1127
    /**
1128
     * Check whether a T_CONST token is a class constant declaration.
1129
     *
1130
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1131
     * @param int                   $stackPtr  The position in the stack of the
1132
     *                                         T_CONST token to verify.
1133
     *
1134
     * @return bool
1135
     */
1136
    public function isClassConstant(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1137
    {
1138
        $tokens = $phpcsFile->getTokens();
1139
1140 View Code Duplication
        if (isset($tokens[$stackPtr]) === false || $tokens[$stackPtr]['code'] !== T_CONST) {
1141
            return false;
1142
        }
1143
1144
        // Note: traits can not declare constants.
1145
        $validScopes = array(
1146
            'T_CLASS'      => true,
1147
            'T_ANON_CLASS' => true,
1148
            'T_INTERFACE'  => true,
1149
        );
1150
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1151
            return true;
1152
        }
1153
1154
        return false;
1155
    }
1156
1157
1158
    /**
1159
     * Check whether the direct wrapping scope of a token is within a limited set of
1160
     * acceptable tokens.
1161
     *
1162
     * Used to check, for instance, if a T_CONST is a class constant.
1163
     *
1164
     * @param \PHP_CodeSniffer_File $phpcsFile   Instance of phpcsFile.
1165
     * @param int                   $stackPtr    The position in the stack of the
1166
     *                                           T_CONST token to verify.
1167
     * @param array                 $validScopes Array of token types.
1168
     *                                           Keys should be the token types in string
1169
     *                                           format to allow for newer token types.
1170
     *                                           Value is irrelevant.
1171
     *
1172
     * @return bool
1173
     */
1174
    protected function validDirectScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes)
1175
    {
1176
        $tokens = $phpcsFile->getTokens();
1177
1178
        if (empty($tokens[$stackPtr]['conditions']) === true) {
1179
            return false;
1180
        }
1181
1182
        /*
1183
         * Check only the direct wrapping scope of the token.
1184
         */
1185
        $conditions = array_keys($tokens[$stackPtr]['conditions']);
1186
        $ptr        = array_pop($conditions);
1187
1188
        if (isset($tokens[$ptr]) === false) {
1189
            return false;
1190
        }
1191
1192
        if (isset($validScopes[$tokens[$ptr]['type']]) === true) {
1193
            return true;
1194
        }
1195
1196
        return false;
1197
    }
1198
1199
1200
    /**
1201
     * Get an array of just the type hints from a function declaration.
1202
     *
1203
     * Expects to be passed T_FUNCTION or T_CLOSURE token.
1204
     *
1205
     * Strips potential nullable indicator and potential global namespace
1206
     * indicator from the type hints before returning them.
1207
     *
1208
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1209
     * @param int                   $stackPtr  The position of the token.
1210
     *
1211
     * @return array Array with type hints or an empty array if
1212
     *               - the function does not have any parameters
1213
     *               - no type hints were found
1214
     *               - or the passed token was not of the correct type.
1215
     */
1216
    public function getTypeHintsFromFunctionDeclaration(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1217
    {
1218
        $tokens = $phpcsFile->getTokens();
1219
1220 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1221
            return array();
1222
        }
1223
1224
        $parameters = $this->getMethodParameters($phpcsFile, $stackPtr);
1225
        if (empty($parameters) || is_array($parameters) === false) {
1226
            return array();
1227
        }
1228
1229
        $typeHints = array();
1230
1231
        foreach ($parameters as $param) {
1232
            if ($param['type_hint'] === '') {
1233
                continue;
1234
            }
1235
1236
            // Strip off potential nullable indication.
1237
            $typeHint = ltrim($param['type_hint'], '?');
1238
1239
            // Strip off potential (global) namespace indication.
1240
            $typeHint = ltrim($typeHint, '\\');
1241
1242
            if ($typeHint !== '') {
1243
                $typeHints[] = $typeHint;
1244
            }
1245
        }
1246
1247
        return $typeHints;
1248
    }
1249
1250
1251
    /**
1252
     * Returns the method parameters for the specified function token.
1253
     *
1254
     * Each parameter is in the following format:
1255
     *
1256
     * <code>
1257
     *   0 => array(
1258
     *         'token'             => int,     // The position of the var in the token stack.
1259
     *         'name'              => '$var',  // The variable name.
1260
     *         'content'           => string,  // The full content of the variable definition.
1261
     *         'pass_by_reference' => boolean, // Is the variable passed by reference?
1262
     *         'variable_length'   => boolean, // Is the param of variable length through use of `...` ?
1263
     *         'type_hint'         => string,  // The type hint for the variable.
1264
     *         'nullable_type'     => boolean, // Is the variable using a nullable type?
1265
     *        )
1266
     * </code>
1267
     *
1268
     * Parameters with default values have an additional array index of
1269
     * 'default' with the value of the default as a string.
1270
     *
1271
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1272
     * class, but with some improvements which have been introduced in
1273
     * PHPCS 2.8.0.
1274
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1117},
1275
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1193} and
1276
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1293}.
1277
     *
1278
     * Once the minimum supported PHPCS version for this standard goes beyond
1279
     * that, this method can be removed and calls to it replaced with
1280
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.
1281
     *
1282
     * NOTE: This version does not deal with the new T_NULLABLE token type.
1283
     * This token is included upstream only in 2.8.0+ and as we defer to upstream
1284
     * in that case, no need to deal with it here.
1285
     *
1286
     * Last synced with PHPCS version: PHPCS 2.9.0-alpha at commit f1511adad043edfd6d2e595e77385c32577eb2bc}}
1287
     *
1288
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1289
     * @param int                   $stackPtr  The position in the stack of the
1290
     *                                         function token to acquire the
1291
     *                                         parameters for.
1292
     *
1293
     * @return array|false
1294
     * @throws \PHP_CodeSniffer_Exception If the specified $stackPtr is not of
1295
     *                                    type T_FUNCTION or T_CLOSURE.
1296
     */
1297
    public function getMethodParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1298
    {
1299
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
1300
            return $phpcsFile->getMethodParameters($stackPtr);
1301
        }
1302
1303
        $tokens = $phpcsFile->getTokens();
1304
1305
        // Check for the existence of the token.
1306
        if (isset($tokens[$stackPtr]) === false) {
1307
            return false;
1308
        }
1309
1310 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1311
            throw new \PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION or T_CLOSURE');
1312
        }
1313
1314
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
1315
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
1316
1317
        $vars            = array();
1318
        $currVar         = null;
1319
        $paramStart      = ($opener + 1);
1320
        $defaultStart    = null;
1321
        $paramCount      = 0;
1322
        $passByReference = false;
1323
        $variableLength  = false;
1324
        $typeHint        = '';
1325
        $nullableType    = false;
1326
1327
        for ($i = $paramStart; $i <= $closer; $i++) {
1328
            // Check to see if this token has a parenthesis or bracket opener. If it does
1329
            // it's likely to be an array which might have arguments in it. This
1330
            // could cause problems in our parsing below, so lets just skip to the
1331
            // end of it.
1332 View Code Duplication
            if (isset($tokens[$i]['parenthesis_opener']) === true) {
1333
                // Don't do this if it's the close parenthesis for the method.
1334
                if ($i !== $tokens[$i]['parenthesis_closer']) {
1335
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
1336
                }
1337
            }
1338
1339 View Code Duplication
            if (isset($tokens[$i]['bracket_opener']) === true) {
1340
                // Don't do this if it's the close parenthesis for the method.
1341
                if ($i !== $tokens[$i]['bracket_closer']) {
1342
                    $i = ($tokens[$i]['bracket_closer'] + 1);
1343
                }
1344
            }
1345
1346
            switch ($tokens[$i]['type']) {
1347
                case 'T_BITWISE_AND':
1348
                    $passByReference = true;
1349
                    break;
1350
                case 'T_VARIABLE':
1351
                    $currVar = $i;
1352
                    break;
1353
                case 'T_ELLIPSIS':
1354
                    $variableLength = true;
1355
                    break;
1356
                case 'T_ARRAY_HINT':
1357
                case 'T_CALLABLE':
1358
                    $typeHint .= $tokens[$i]['content'];
1359
                    break;
1360
                case 'T_SELF':
1361
                case 'T_PARENT':
1362
                case 'T_STATIC':
1363
                    // Self is valid, the others invalid, but were probably intended as type hints.
1364
                    if (isset($defaultStart) === false) {
1365
                        $typeHint .= $tokens[$i]['content'];
1366
                    }
1367
                    break;
1368
                case 'T_STRING':
1369
                    // This is a string, so it may be a type hint, but it could
1370
                    // also be a constant used as a default value.
1371
                    $prevComma = false;
1372 View Code Duplication
                    for ($t = $i; $t >= $opener; $t--) {
1373
                        if ($tokens[$t]['code'] === T_COMMA) {
1374
                            $prevComma = $t;
1375
                            break;
1376
                        }
1377
                    }
1378
1379
                    if ($prevComma !== false) {
1380
                        $nextEquals = false;
1381 View Code Duplication
                        for ($t = $prevComma; $t < $i; $t++) {
1382
                            if ($tokens[$t]['code'] === T_EQUAL) {
1383
                                $nextEquals = $t;
1384
                                break;
1385
                            }
1386
                        }
1387
1388
                        if ($nextEquals !== false) {
1389
                            break;
1390
                        }
1391
                    }
1392
1393
                    if ($defaultStart === null) {
1394
                        $typeHint .= $tokens[$i]['content'];
1395
                    }
1396
                    break;
1397
                case 'T_NS_SEPARATOR':
1398
                    // Part of a type hint or default value.
1399
                    if ($defaultStart === null) {
1400
                        $typeHint .= $tokens[$i]['content'];
1401
                    }
1402
                    break;
1403
                case 'T_INLINE_THEN':
1404
                    if ($defaultStart === null) {
1405
                        $nullableType = true;
1406
                        $typeHint    .= $tokens[$i]['content'];
1407
                    }
1408
                    break;
1409
                case 'T_CLOSE_PARENTHESIS':
1410
                case 'T_COMMA':
1411
                    // If it's null, then there must be no parameters for this
1412
                    // method.
1413
                    if ($currVar === null) {
1414
                        continue;
1415
                    }
1416
1417
                    $vars[$paramCount]            = array();
1418
                    $vars[$paramCount]['token']   = $currVar;
1419
                    $vars[$paramCount]['name']    = $tokens[$currVar]['content'];
1420
                    $vars[$paramCount]['content'] = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
1421
1422
                    if ($defaultStart !== null) {
1423
                        $vars[$paramCount]['default']
1424
                            = trim($phpcsFile->getTokensAsString(
1425
                                $defaultStart,
1426
                                ($i - $defaultStart)
1427
                            ));
1428
                    }
1429
1430
                    $vars[$paramCount]['pass_by_reference'] = $passByReference;
1431
                    $vars[$paramCount]['variable_length']   = $variableLength;
1432
                    $vars[$paramCount]['type_hint']         = $typeHint;
1433
                    $vars[$paramCount]['nullable_type']     = $nullableType;
1434
1435
                    // Reset the vars, as we are about to process the next parameter.
1436
                    $defaultStart    = null;
1437
                    $paramStart      = ($i + 1);
1438
                    $passByReference = false;
1439
                    $variableLength  = false;
1440
                    $typeHint        = '';
1441
                    $nullableType    = false;
1442
1443
                    $paramCount++;
1444
                    break;
1445
                case 'T_EQUAL':
1446
                    $defaultStart = ($i + 1);
1447
                    break;
1448
            }//end switch
1449
        }//end for
1450
1451
        return $vars;
1452
1453
    }//end getMethodParameters()
1454
1455
1456
    /**
1457
     * Returns the name of the class that the specified class extends
1458
     * (works for classes, anonymous classes and interfaces).
1459
     *
1460
     * Returns FALSE on error or if there is no extended class name.
1461
     *
1462
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1463
     * class, but with some improvements which have been introduced in
1464
     * PHPCS 2.8.0.
1465
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/commit/0011d448119d4c568e3ac1f825ae78815bf2cc34}.
1466
     *
1467
     * Once the minimum supported PHPCS version for this standard goes beyond
1468
     * that, this method can be removed and calls to it replaced with
1469
     * `$phpcsFile->findExtendedClassName($stackPtr)` calls.
1470
     *
1471
     * Last synced with PHPCS version: PHPCS 3.1.0-alpha at commit a9efcc9b0703f3f9f4a900623d4e97128a6aafc6}}
1472
     *
1473
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1474
     * @param int                   $stackPtr  The position of the class token in the stack.
1475
     *
1476
     * @return string|false
1477
     */
1478
    public function findExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1479
    {
1480
        if (version_compare(PHPCSHelper::getVersion(), '3.1.0', '>=') === true) {
1481
            return $phpcsFile->findExtendedClassName($stackPtr);
1482
        }
1483
1484
        $tokens = $phpcsFile->getTokens();
1485
1486
        // Check for the existence of the token.
1487
        if (isset($tokens[$stackPtr]) === false) {
1488
            return false;
1489
        }
1490
1491 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
1492
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
1493
            && $tokens[$stackPtr]['type'] !== 'T_INTERFACE'
1494
        ) {
1495
            return false;
1496
        }
1497
1498
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
1499
            return false;
1500
        }
1501
1502
        $classCloserIndex = $tokens[$stackPtr]['scope_closer'];
1503
        $extendsIndex     = $phpcsFile->findNext(T_EXTENDS, $stackPtr, $classCloserIndex);
1504
        if (false === $extendsIndex) {
1505
            return false;
1506
        }
1507
1508
        $find = array(
1509
                 T_NS_SEPARATOR,
1510
                 T_STRING,
1511
                 T_WHITESPACE,
1512
                );
1513
1514
        $end  = $phpcsFile->findNext($find, ($extendsIndex + 1), $classCloserIndex, true);
1515
        $name = $phpcsFile->getTokensAsString(($extendsIndex + 1), ($end - $extendsIndex - 1));
1516
        $name = trim($name);
1517
1518
        if ($name === '') {
1519
            return false;
1520
        }
1521
1522
        return $name;
1523
1524
    }//end findExtendedClassName()
1525
1526
1527
    /**
1528
     * Get the hash algorithm name from the parameter in a hash function call.
1529
     *
1530
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1531
     * @param int                   $stackPtr  The position of the T_STRING function token.
1532
     *
1533
     * @return string|false The algorithm name without quotes if this was a relevant hash
1534
     *                      function call or false if it was not.
1535
     */
1536
    public function getHashAlgorithmParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1537
    {
1538
        $tokens = $phpcsFile->getTokens();
1539
1540
        // Check for the existence of the token.
1541
        if (isset($tokens[$stackPtr]) === false) {
1542
            return false;
1543
        }
1544
1545
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1546
            return false;
1547
        }
1548
1549
        $functionName   = $tokens[$stackPtr]['content'];
1550
        $functionNameLc = strtolower($functionName);
1551
1552
        // Bow out if not one of the functions we're targetting.
1553
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
1554
            return false;
1555
        }
1556
1557
        // Get the parameter from the function call which should contain the algorithm name.
1558
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
1559
        if ($algoParam === false) {
1560
            return false;
1561
        }
1562
1563
        // Algorithm is a text string, so we need to remove the quotes.
1564
        $algo = strtolower(trim($algoParam['raw']));
1565
        $algo = $this->stripQuotes($algo);
1566
1567
        return $algo;
1568
    }
1569
1570
1571
    /**
1572
     * Determine whether an arbitrary T_STRING token is the use of a global constant.
1573
     *
1574
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1575
     * @param int                   $stackPtr  The position of the function call token.
1576
     *
1577
     * @return bool
1578
     */
1579
    public function isUseOfGlobalConstant(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1580
    {
1581
        static $isLowPHPCS, $isLowPHP;
1582
1583
        $tokens = $phpcsFile->getTokens();
1584
1585
        // Check for the existence of the token.
1586
        if (isset($tokens[$stackPtr]) === false) {
1587
            return false;
1588
        }
1589
1590
        // Is this one of the tokens this function handles ?
1591
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1592
            return false;
1593
        }
1594
1595
        // Check for older PHP, PHPCS version so we can compensate for misidentified tokens.
1596
        if (isset($isLowPHPCS, $isLowPHP) === false) {
1597
            $isLowPHP   = false;
1598
            $isLowPHPCS = false;
1599
            if (version_compare(PHP_VERSION_ID, '50400', '<')) {
1600
                $isLowPHP   = true;
1601
                $isLowPHPCS = version_compare(PHPCSHelper::getVersion(), '2.4.0', '<');
1602
            }
1603
        }
1604
1605
        $next = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
1606
        if ($next !== false
1607
            && ($tokens[$next]['code'] === T_OPEN_PARENTHESIS
1608
                || $tokens[$next]['code'] === T_DOUBLE_COLON)
1609
        ) {
1610
            // Function call or declaration.
1611
            return false;
1612
        }
1613
1614
        // Array of tokens which if found preceding the $stackPtr indicate that a T_STRING is not a global constant.
1615
        $tokensToIgnore = array(
1616
            'T_NAMESPACE'       => true,
1617
            'T_USE'             => true,
1618
            'T_CLASS'           => true,
1619
            'T_TRAIT'           => true,
1620
            'T_INTERFACE'       => true,
1621
            'T_EXTENDS'         => true,
1622
            'T_IMPLEMENTS'      => true,
1623
            'T_NEW'             => true,
1624
            'T_FUNCTION'        => true,
1625
            'T_DOUBLE_COLON'    => true,
1626
            'T_OBJECT_OPERATOR' => true,
1627
            'T_INSTANCEOF'      => true,
1628
            'T_INSTEADOF'       => true,
1629
            'T_GOTO'            => true,
1630
            'T_AS'              => true,
1631
            'T_PUBLIC'          => true,
1632
            'T_PROTECTED'       => true,
1633
            'T_PRIVATE'         => true,
1634
        );
1635
1636
        $prev = $phpcsFile->findPrevious(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
1637
        if ($prev !== false
1638
            && (isset($tokensToIgnore[$tokens[$prev]['type']]) === true)
1639
                || ($tokens[$prev]['code'] === T_STRING
1640
                    && (($isLowPHPCS === true
1641
                        && $tokens[$prev]['content'] === 'trait')
1642
                    || ($isLowPHP === true
1643
                        && $tokens[$prev]['content'] === 'insteadof')))
1644
        ) {
1645
            // Not the use of a constant.
1646
            return false;
1647
        }
1648
1649
        if ($prev !== false
1650
            && $tokens[$prev]['code'] === T_NS_SEPARATOR
1651
            && $tokens[($prev - 1)]['code'] === T_STRING
1652
        ) {
1653
            // Namespaced constant of the same name.
1654
            return false;
1655
        }
1656
1657
        if ($prev !== false
1658
            && $tokens[$prev]['code'] === T_CONST
1659
            && $this->isClassConstant($phpcsFile, $prev) === true
1660
        ) {
1661
            // Class constant declaration of the same name.
1662
            return false;
1663
        }
1664
1665
        /*
1666
         * Deal with a number of variations of use statements.
1667
         */
1668
        for ($i = $stackPtr; $i > 0; $i--) {
1669
            if ($tokens[$i]['line'] !== $tokens[$stackPtr]['line']) {
1670
                break;
1671
            }
1672
        }
1673
1674
        $firstOnLine = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($i + 1), null, true);
1675
        if ($firstOnLine !== false && $tokens[$firstOnLine]['code'] === T_USE) {
1676
            $nextOnLine = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($firstOnLine + 1), null, true);
1677
            if ($nextOnLine !== false) {
1678
                if (($tokens[$nextOnLine]['code'] === T_STRING && $tokens[$nextOnLine]['content'] === 'const')
1679
                    || $tokens[$nextOnLine]['code'] === T_CONST // Happens in some PHPCS versions.
1680
                ) {
1681
                    $hasNsSep = $phpcsFile->findNext(T_NS_SEPARATOR, ($nextOnLine + 1), $stackPtr);
1682
                    if ($hasNsSep !== false) {
1683
                        // Namespaced const (group) use statement.
1684
                        return false;
1685
                    }
1686
                } else {
1687
                    // Not a const use statement.
1688
                    return false;
1689
                }
1690
            }
1691
        }
1692
1693
        return true;
1694
    }
1695
1696
}//end class
1697