Completed
Push — PR/feature/various-minor-fixes ( de881f )
by Juliette
02:23
created

Sniff.php (18 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
/**
12
 * PHPCompatibility_Sniff.
13
 *
14
 * @category  PHP
15
 * @package   PHPCompatibility
16
 * @author    Wim Godden <[email protected]>
17
 * @copyright 2014 Cu.be Solutions bvba
18
 */
19
abstract class PHPCompatibility_Sniff implements PHP_CodeSniffer_Sniff
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

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