Completed
Push — feature/changelog-7.1.5 ( 9999e8...6b426c )
by Juliette
02:15
created

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