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