Completed
Push — master ( f197b0...583757 )
by Wim
03:02
created

Sniff.php (15 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
                $testVersion = substr($testVersion, 0, -1);
128
                // If no upper-limit is set, we set the max version to 99.9.
129
                // This is *probably* safe... :-)
130
                $arrTestVersions[$testVersion] = array($testVersion, '99.9');
131
            }
132 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...
133
                $testVersion = substr($testVersion, 1);
134
                // If no lower-limit is set, we set the min version to 4.0.
135
                // Whilst development focuses on PHP 5 and above, we also accept
136
                // sniffs for PHP 4, so we include that as the minimum.
137
                // (It makes no sense to support PHP 3 as this was effectively a
138
                // different language).
139
                $arrTestVersions[$testVersion] = array('4.0', $testVersion);
140
            }
141
            elseif (!$testVersion == '') {
142
                trigger_error("Invalid testVersion setting: '" . $testVersion
143
                              . "'", E_USER_WARNING);
144
            }
145
        }
146
147
        if (isset($arrTestVersions[$testVersion])) {
148
            return $arrTestVersions[$testVersion];
149
        }
150
        else {
151
            return array(null, null);
152
        }
153
    }
154
155
156
    /**
157
     * Check whether a specific PHP version is equal to or higher than the maximum
158
     * supported PHP version as provided by the user in `testVersion`.
159
     *
160
     * Should be used when sniffing for *old* PHP features (deprecated/removed).
161
     *
162
     * @param string $phpVersion A PHP version number in 'major.minor' format.
163
     *
164
     * @return bool True if testVersion has not been provided or if the PHP version
165
     *              is equal to or higher than the highest supported PHP version
166
     *              in testVersion. False otherwise.
167
     */
168 View Code Duplication
    public function supportsAbove($phpVersion)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
169
    {
170
        $testVersion = $this->getTestVersion();
171
        $testVersion = $testVersion[1];
172
173
        if (is_null($testVersion)
174
            || version_compare($testVersion, $phpVersion) >= 0
175
        ) {
176
            return true;
177
        } else {
178
            return false;
179
        }
180
    }//end supportsAbove()
181
182
183
    /**
184
     * Check whether a specific PHP version is equal to or lower than the minimum
185
     * supported PHP version as provided by the user in `testVersion`.
186
     *
187
     * Should be used when sniffing for *new* PHP features.
188
     *
189
     * @param string $phpVersion A PHP version number in 'major.minor' format.
190
     *
191
     * @return bool True if the PHP version is equal to or lower than the lowest
192
     *              supported PHP version in testVersion.
193
     *              False otherwise or if no testVersion is provided.
194
     */
195 View Code Duplication
    public function supportsBelow($phpVersion)
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
196
    {
197
        $testVersion = $this->getTestVersion();
198
        $testVersion = $testVersion[0];
199
200
        if (!is_null($testVersion)
201
            && version_compare($testVersion, $phpVersion) <= 0
202
        ) {
203
            return true;
204
        } else {
205
            return false;
206
        }
207
    }//end supportsBelow()
208
209
210
    /**
211
     * Add a PHPCS message to the output stack as either a warning or an error.
212
     *
213
     * @param PHP_CodeSniffer_File $phpcsFile The file the message applies to.
214
     * @param string               $message   The message.
215
     * @param int                  $stackPtr  The position of the token
216
     *                                        the message relates to.
217
     * @param bool                 $isError   Whether to report the message as an
218
     *                                        'error' or 'warning'.
219
     *                                        Defaults to true (error).
220
     * @param string               $code      The error code for the message.
221
     *                                        Defaults to 'Found'.
222
     * @param array                $data      Optional input for the data replacements.
223
     *
224
     * @return void
225
     */
226
    public function addMessage($phpcsFile, $message, $stackPtr, $isError, $code = 'Found', $data = array())
227
    {
228
        if ($isError === true) {
229
            $phpcsFile->addError($message, $stackPtr, $code, $data);
230
        } else {
231
            $phpcsFile->addWarning($message, $stackPtr, $code, $data);
232
        }
233
    }
234
235
236
    /**
237
     * Convert an arbitrary string to an alphanumeric string with underscores.
238
     *
239
     * Pre-empt issues with arbitrary strings being used as error codes in XML and PHP.
240
     *
241
     * @param string $baseString Arbitrary string.
242
     *
243
     * @return string
244
     */
245
    public function stringToErrorCode($baseString)
246
    {
247
        return preg_replace('`[^a-z0-9_]`i', '_', strtolower($baseString));
248
    }
249
250
251
    /**
252
     * Strip quotes surrounding an arbitrary string.
253
     *
254
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING / T_DOUBLE_QUOTED_STRING.
255
     *
256
     * @param string $string The raw string.
257
     *
258
     * @return string String without quotes around it.
259
     */
260
    public function stripQuotes($string) {
261
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
262
    }
263
264
265
    /**
266
     * Strip variables from an arbitrary double quoted string.
267
     *
268
     * Intended for use with the content of a T_DOUBLE_QUOTED_STRING.
269
     *
270
     * @param string $string The raw string.
271
     *
272
     * @return string String without variables in it.
273
     */
274
    public function stripVariables($string) {
275
        if (strpos($string, '$') === false) {
276
            return $string;
277
        }
278
279
        return preg_replace( self::REGEX_COMPLEX_VARS, '', $string );
280
    }
281
282
283
    /**
284
     * Make all top level array keys in an array lowercase.
285
     *
286
     * @param array $array Initial array.
287
     *
288
     * @return array Same array, but with all lowercase top level keys.
289
     */
290
    public function arrayKeysToLowercase($array)
291
    {
292
        $keys = array_keys($array);
293
        $keys = array_map('strtolower', $keys);
294
        return array_combine($keys, $array);
295
    }
296
297
298
    /**
299
     * Returns the name(s) of the interface(s) that the specified class implements.
300
     *
301
     * Returns FALSE on error or if there are no implemented interface names.
302
     *
303
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
304
     * This method also includes an improvement we use which was only introduced
305
     * in PHPCS 2.8.0, so only defer to upstream for higher versions.
306
     * Once the minimum supported PHPCS version for this sniff library goes beyond
307
     * that, this method can be removed and calls to it replaced with
308
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
309
     *
310
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
311
     * @param int                  $stackPtr  The position of the class token.
312
     *
313
     * @return array|false
314
     */
315
    public function findImplementedInterfaceNames(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
316
    {
317
        if (version_compare(PHP_CodeSniffer::VERSION, '2.7.1', '>') === true) {
318
            return $phpcsFile->findImplementedInterfaceNames($stackPtr);
319
        }
320
321
        $tokens = $phpcsFile->getTokens();
322
323
        // Check for the existence of the token.
324
        if (isset($tokens[$stackPtr]) === false) {
325
            return false;
326
        }
327
328
        if ($tokens[$stackPtr]['code'] !== T_CLASS
329
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
330
        ) {
331
            return false;
332
        }
333
334
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
335
            return false;
336
        }
337
338
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
339
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
340
        if ($implementsIndex === false) {
341
            return false;
342
        }
343
344
        $find = array(
345
                 T_NS_SEPARATOR,
346
                 T_STRING,
347
                 T_WHITESPACE,
348
                 T_COMMA,
349
                );
350
351
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
352
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
353
        $name = trim($name);
354
355
        if ($name === '') {
356
            return false;
357
        } else {
358
            $names = explode(',', $name);
359
            $names = array_map('trim', $names);
360
            return $names;
361
        }
362
363
    }//end findImplementedInterfaceNames()
364
365
366
    /**
367
     * Checks if a function call has parameters.
368
     *
369
     * Expects to be passed the T_STRING stack pointer for the function call.
370
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
371
     *
372
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer, it
373
     * will detect whether the array has values or is empty.
374
     *
375
     * @link https://github.com/wimg/PHPCompatibility/issues/120
376
     * @link https://github.com/wimg/PHPCompatibility/issues/152
377
     *
378
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
379
     * @param int                  $stackPtr  The position of the function call token.
380
     *
381
     * @return bool
382
     */
383
    public function doesFunctionCallHaveParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
384
    {
385
        $tokens = $phpcsFile->getTokens();
386
387
        // Check for the existence of the token.
388
        if (isset($tokens[$stackPtr]) === false) {
389
            return false;
390
        }
391
392
        // Is this one of the tokens this function handles ?
393
        if (in_array($tokens[$stackPtr]['code'], array(T_STRING, T_ARRAY, T_OPEN_SHORT_ARRAY), true) === false) {
394
            return false;
395
        }
396
397
        $nextNonEmpty = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
398
399
        // Deal with short array syntax.
400
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
401
            if (isset($tokens[$stackPtr]['bracket_closer']) === false) {
402
                return false;
403
            }
404
405
            if ($nextNonEmpty === $tokens[$stackPtr]['bracket_closer']) {
406
                // No parameters.
407
                return false;
408
            }
409
            else {
410
                return true;
411
            }
412
        }
413
414
        // Deal with function calls & long arrays.
415
        // Next non-empty token should be the open parenthesis.
416
        if ($nextNonEmpty === false && $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS) {
417
            return false;
418
        }
419
420
        if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
421
            return false;
422
        }
423
424
        $closeParenthesis = $tokens[$nextNonEmpty]['parenthesis_closer'];
425
        $nextNextNonEmpty = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $nextNonEmpty + 1, $closeParenthesis + 1, true);
426
427
        if ($nextNextNonEmpty === $closeParenthesis) {
428
            // No parameters.
429
            return false;
430
        }
431
432
        return true;
433
    }
434
435
436
    /**
437
     * Count the number of parameters a function call has been passed.
438
     *
439
     * Expects to be passed the T_STRING stack pointer for the function call.
440
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
441
     *
442
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
443
     * it will return the number of values in the array.
444
     *
445
     * @link https://github.com/wimg/PHPCompatibility/issues/111
446
     * @link https://github.com/wimg/PHPCompatibility/issues/114
447
     * @link https://github.com/wimg/PHPCompatibility/issues/151
448
     *
449
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
450
     * @param int                  $stackPtr  The position of the function call token.
451
     *
452
     * @return int
453
     */
454
    public function getFunctionCallParameterCount(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
455
    {
456
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
457
            return 0;
458
        }
459
460
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
461
    }
462
463
464
    /**
465
     * Get information on all parameters passed to a function call.
466
     *
467
     * Expects to be passed the T_STRING stack pointer for the function call.
468
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
469
     *
470
     * Will return an multi-dimentional array with the start token pointer, end token
471
     * pointer and raw parameter value for all parameters. Index will be 1-based.
472
     * If no parameters are found, will return an empty array.
473
     *
474
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
475
     * it will tokenize the values / key/value pairs contained in the array call.
476
     *
477
     * @param PHP_CodeSniffer_File $phpcsFile     The file being scanned.
478
     * @param int                  $stackPtr      The position of the function call token.
479
     *
480
     * @return array
481
     */
482
    public function getFunctionCallParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
483
    {
484
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
485
            return array();
486
        }
487
488
        // Ok, we know we have a T_STRING, T_ARRAY or T_OPEN_SHORT_ARRAY with parameters
489
        // and valid open & close brackets/parenthesis.
490
        $tokens = $phpcsFile->getTokens();
491
492
        // Mark the beginning and end tokens.
493
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
494
            $opener = $stackPtr;
495
            $closer = $tokens[$stackPtr]['bracket_closer'];
496
497
            $nestedParenthesisCount = 0;
498
        }
499
        else {
500
            $opener = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
501
            $closer = $tokens[$opener]['parenthesis_closer'];
502
503
            $nestedParenthesisCount = 1;
504
        }
505
506
        // Which nesting level is the one we are interested in ?
507 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...
508
            $nestedParenthesisCount += count($tokens[$opener]['nested_parenthesis']);
509
        }
510
511
        $parameters = array();
512
        $nextComma  = $opener;
513
        $paramStart = $opener + 1;
514
        $cnt        = 1;
515
        while ($nextComma = $phpcsFile->findNext(array(T_COMMA, $tokens[$closer]['code'], T_OPEN_SHORT_ARRAY), $nextComma + 1, $closer + 1)) {
516
            // Ignore anything within short array definition brackets.
517
            if (
518
                $tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
519
                &&
520
                ( isset($tokens[$nextComma]['bracket_opener']) && $tokens[$nextComma]['bracket_opener'] === $nextComma )
521
                &&
522
                isset($tokens[$nextComma]['bracket_closer'])
523
            ) {
524
                // Skip forward to the end of the short array definition.
525
                $nextComma = $tokens[$nextComma]['bracket_closer'];
526
                continue;
527
            }
528
529
            // Ignore comma's at a lower nesting level.
530
            if (
531
                $tokens[$nextComma]['type'] === 'T_COMMA'
532
                &&
533
                isset($tokens[$nextComma]['nested_parenthesis'])
534
                &&
535
                count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
536
            ) {
537
                continue;
538
            }
539
540
            // Ignore closing parenthesis/bracket if not 'ours'.
541
            if ($tokens[$nextComma]['type'] === $tokens[$closer]['type'] && $nextComma !== $closer) {
542
                continue;
543
            }
544
545
            // Ok, we've reached the end of the parameter.
546
            $parameters[$cnt]['start'] = $paramStart;
547
            $parameters[$cnt]['end']   = $nextComma - 1;
548
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
549
550
            // Check if there are more tokens before the closing parenthesis.
551
            // Prevents code like the following from setting a third parameter:
552
            // 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...
553
            $hasNextParam = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closer, true, null, true);
554
            if ($hasNextParam === false) {
555
                break;
556
            }
557
558
            // Prepare for the next parameter.
559
            $paramStart = $nextComma + 1;
560
            $cnt++;
561
        }
562
563
        return $parameters;
564
    }
565
566
567
    /**
568
     * Get information on a specific parameter passed to a function call.
569
     *
570
     * Expects to be passed the T_STRING stack pointer for the function call.
571
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
572
     *
573
     * Will return a array with the start token pointer, end token pointer and the raw value
574
     * of the parameter at a specific offset.
575
     * If the specified parameter is not found, will return false.
576
     *
577
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
578
     * @param int                  $stackPtr    The position of the function call token.
579
     * @param int                  $paramOffset The 1-based index position of the parameter to retrieve.
580
     *
581
     * @return array|false
582
     */
583
    public function getFunctionCallParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
584
    {
585
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
586
587
        if (isset($parameters[$paramOffset]) === false) {
588
            return false;
589
        }
590
        else {
591
            return $parameters[$paramOffset];
592
        }
593
    }
594
595
596
    /**
597
     * Verify whether a token is within a scoped condition.
598
     *
599
     * If the optional $validScopes parameter has been passed, the function
600
     * will check that the token has at least one condition which is of a
601
     * type defined in $validScopes.
602
     *
603
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
604
     * @param int                  $stackPtr    The position of the token.
605
     * @param array|int            $validScopes Optional. Array of valid scopes
606
     *                                          or int value of a valid scope.
607
     *                                          Pass the T_.. constant(s) for the
608
     *                                          desired scope to this parameter.
609
     *
610
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
611
     *              If the $scopeTypes are set: True if *one* of the conditions is a
612
     *              valid scope, false otherwise.
613
     */
614
    public function tokenHasScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
615
    {
616
        $tokens = $phpcsFile->getTokens();
617
618
        // Check for the existence of the token.
619
        if (isset($tokens[$stackPtr]) === false) {
620
            return false;
621
        }
622
623
        // No conditions = no scope.
624
        if (empty($tokens[$stackPtr]['conditions'])) {
625
            return false;
626
        }
627
628
        // Ok, there are conditions, do we have to check for specific ones ?
629
        if (isset($validScopes) === false) {
630
            return true;
631
        }
632
633
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
634
    }
635
636
637
    /**
638
     * Verify whether a token is within a class scope.
639
     *
640
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
641
     * @param int                  $stackPtr  The position of the token.
642
     * @param bool                 $strict    Whether to strictly check for the T_CLASS
643
     *                                        scope or also accept interfaces and traits
644
     *                                        as scope.
645
     *
646
     * @return bool True if within class scope, false otherwise.
647
     */
648
    public function inClassScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
649
    {
650
        $validScopes = array(T_CLASS);
651
        if (defined('T_ANON_CLASS') === true) {
652
            $validScopes[] = T_ANON_CLASS;
653
        }
654
655
        if ($strict === false) {
656
            $validScopes[] = T_INTERFACE;
657
            $validScopes[] = T_TRAIT;
658
        }
659
660
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
661
    }
662
663
664
    /**
665
     * Verify whether a token is within a scoped use statement.
666
     *
667
     * PHPCS cross-version compatibility method.
668
     *
669
     * In PHPCS 1.x no conditions are set for a scoped use statement.
670
     * This method works around that limitation.
671
     *
672
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
673
     * @param int                  $stackPtr  The position of the token.
674
     *
675
     * @return bool True if within use scope, false otherwise.
676
     */
677
    public function inUseScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
678
    {
679
        static $isLowPHPCS, $ignoreTokens;
680
681
        if (isset($isLowPHPCS) === false) {
682
            $isLowPHPCS = version_compare(PHP_CodeSniffer::VERSION, '2.0', '<');
683
        }
684
        if (isset($ignoreTokens) === false) {
685
            $ignoreTokens              = PHP_CodeSniffer_Tokens::$emptyTokens;
686
            $ignoreTokens[T_STRING]    = T_STRING;
687
            $ignoreTokens[T_AS]        = T_AS;
688
            $ignoreTokens[T_PUBLIC]    = T_PUBLIC;
689
            $ignoreTokens[T_PROTECTED] = T_PROTECTED;
690
            $ignoreTokens[T_PRIVATE]   = T_PRIVATE;
691
        }
692
693
        // PHPCS 2.0.
694
        if ($isLowPHPCS === false) {
695
            return $phpcsFile->hasCondition($stackPtr, T_USE);
696
        } else {
697
            // PHPCS 1.x.
698
            $tokens         = $phpcsFile->getTokens();
699
            $maybeCurlyOpen = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
700
            if ($tokens[$maybeCurlyOpen]['code'] === T_OPEN_CURLY_BRACKET) {
701
                $maybeUseStatement = $phpcsFile->findPrevious($ignoreTokens, ($maybeCurlyOpen - 1), null, true);
702
                if ($tokens[$maybeUseStatement]['code'] === T_USE) {
703
                    return true;
704
                }
705
            }
706
            return false;
707
        }
708
    }
709
710
711
    /**
712
     * Returns the fully qualified class name for a new class instantiation.
713
     *
714
     * Returns an empty string if the class name could not be reliably inferred.
715
     *
716
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
717
     * @param int                  $stackPtr  The position of a T_NEW token.
718
     *
719
     * @return string
720
     */
721
    public function getFQClassNameFromNewToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
722
    {
723
        $tokens = $phpcsFile->getTokens();
724
725
        // Check for the existence of the token.
726
        if (isset($tokens[$stackPtr]) === false) {
727
            return '';
728
        }
729
730
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
731
            return '';
732
        }
733
734
        $find = array(
735
                 T_NS_SEPARATOR,
736
                 T_STRING,
737
                 T_NAMESPACE,
738
                 T_WHITESPACE,
739
                );
740
741
        $start = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
742
743
        if ($start === false) {
744
            return '';
745
        }
746
747
        // Bow out if the next token is a variable as we don't know where it was defined.
748
        if ($tokens[$start]['code'] === T_VARIABLE) {
749
            return '';
750
        }
751
752
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
753
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
754
        $className = trim($className);
755
756
        return $this->getFQName($phpcsFile, $stackPtr, $className);
757
    }
758
759
760
    /**
761
     * Returns the fully qualified name of the class that the specified class extends.
762
     *
763
     * Returns an empty string if the class does not extend another class or if
764
     * the class name could not be reliably inferred.
765
     *
766
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
767
     * @param int                  $stackPtr  The position of a T_CLASS token.
768
     *
769
     * @return string
770
     */
771
    public function getFQExtendedClassName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
772
    {
773
        $tokens = $phpcsFile->getTokens();
774
775
        // Check for the existence of the token.
776
        if (isset($tokens[$stackPtr]) === false) {
777
            return '';
778
        }
779
780
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
781
            return '';
782
        }
783
784
        $extends = $phpcsFile->findExtendedClassName($stackPtr);
785
        if (empty($extends) || is_string($extends) === false) {
786
            return '';
787
        }
788
789
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
790
    }
791
792
793
    /**
794
     * Returns the class name for the static usage of a class.
795
     * This can be a call to a method, the use of a property or constant.
796
     *
797
     * Returns an empty string if the class name could not be reliably inferred.
798
     *
799
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
800
     * @param int                  $stackPtr  The position of a T_NEW token.
801
     *
802
     * @return string
803
     */
804
    public function getFQClassNameFromDoubleColonToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
805
    {
806
        $tokens = $phpcsFile->getTokens();
807
808
        // Check for the existence of the token.
809
        if (isset($tokens[$stackPtr]) === false) {
810
            return '';
811
        }
812
813
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
814
            return '';
815
        }
816
817
        // Nothing to do if previous token is a variable as we don't know where it was defined.
818
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
819
            return '';
820
        }
821
822
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
823
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
824
            return '';
825
        }
826
827
        // Get the classname from the class declaration if self is used.
828
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
829
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
830
            if ($classDeclarationPtr === false) {
831
                return '';
832
            }
833
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
834
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
835
        }
836
837
        $find = array(
838
                 T_NS_SEPARATOR,
839
                 T_STRING,
840
                 T_NAMESPACE,
841
                 T_WHITESPACE,
842
                );
843
844
        $start     = ($phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true) + 1);
845
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
846
        $className = trim($className);
847
848
        return $this->getFQName($phpcsFile, $stackPtr, $className);
849
    }
850
851
852
    /**
853
     * Get the Fully Qualified name for a class/function/constant etc.
854
     *
855
     * Checks if a class/function/constant name is already fully qualified and
856
     * if not, enrich it with the relevant namespace information.
857
     *
858
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
859
     * @param int                  $stackPtr  The position of the token.
860
     * @param string               $name      The class / function / constant name.
861
     *
862
     * @return string
863
     */
864
    public function getFQName(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
865
    {
866
        if (strpos($name, '\\' ) === 0) {
867
            // Already fully qualified.
868
            return $name;
869
        }
870
871
        // Remove the namespace keyword if used.
872
        if (strpos($name, 'namespace\\') === 0) {
873
            $name = substr($name, 10);
874
        }
875
876
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
877
878
        if ($namespace === '') {
879
            return '\\' . $name;
880
        }
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
        if (strpos($FQName, '\\') !== 0) {
897
            throw new PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
898
        }
899
900
        return (strpos(substr($FQName, 1), '\\') !== false);
901
    }
902
903
904
    /**
905
     * Determine the namespace name an arbitrary token lives in.
906
     *
907
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
908
     * @param int                  $stackPtr  The token position for which to determine the namespace.
909
     *
910
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
911
     */
912
    public function determineNamespace(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
913
    {
914
        $tokens = $phpcsFile->getTokens();
915
916
        // Check for the existence of the token.
917
        if (isset($tokens[$stackPtr]) === false) {
918
            return '';
919
        }
920
921
        // Check for scoped namespace {}.
922
        if (empty($tokens[$stackPtr]['conditions']) === false) {
923
            $namespacePtr = $phpcsFile->getCondition($stackPtr, T_NAMESPACE);
924
            if ($namespacePtr !== false ) {
925
                $namespace = $this->getDeclaredNamespaceName($phpcsFile, $namespacePtr);
926
                if ($namespace !== false) {
927
                    return $namespace;
928
                }
929
930
                // We are in a scoped namespace, but couldn't determine the name. Searching for a global namespace is futile.
931
                return '';
932
            }
933
        }
934
935
        /*
936
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
937
         * Keeping in mind that:
938
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
939
         * - the namespace keyword can also be used as part of a function/method call and such.
940
         * - that a non-named namespace resolves to the global namespace.
941
         */
942
        $previousNSToken = $stackPtr;
943
        $namespace       = false;
944
        do {
945
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, ($previousNSToken - 1));
946
947
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
948
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] === $previousNSToken) {
949
                break;
950
            }
951
952
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
953
954
        } while ($namespace === false && $previousNSToken !== false);
955
956
        // If we still haven't got a namespace, return an empty string.
957
        if ($namespace === false) {
958
            return '';
959
        }
960
        else {
961
            return $namespace;
962
        }
963
    }
964
965
    /**
966
     * Get the complete namespace name for a namespace declaration.
967
     *
968
     * For hierarchical namespaces, the name will be composed of several tokens,
969
     * i.e. MyProject\Sub\Level which will be returned together as one string.
970
     *
971
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
972
     * @param int|bool             $stackPtr  The position of a T_NAMESPACE token.
973
     *
974
     * @return string|false Namespace name or false if not a namespace declaration.
975
     *                      Namespace name can be an empty string for global namespace declaration.
976
     */
977
    public function getDeclaredNamespaceName(PHP_CodeSniffer_File $phpcsFile, $stackPtr )
978
    {
979
        $tokens = $phpcsFile->getTokens();
980
981
        // Check for the existence of the token.
982 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...
983
            return false;
984
        }
985
986
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
987
            return false;
988
        }
989
990
        if ($tokens[($stackPtr + 1)]['code'] === T_NS_SEPARATOR) {
991
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
992
            return false;
993
        }
994
995
        $nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
996
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
997
            // Declaration for global namespace when using multiple namespaces in a file.
998
            // I.e.: namespace {}
999
            return '';
1000
        }
1001
1002
        // Ok, this should be a namespace declaration, so get all the parts together.
1003
        $validTokens = array(
1004
                        T_STRING       => true,
1005
                        T_NS_SEPARATOR => true,
1006
                        T_WHITESPACE   => true,
1007
                       );
1008
1009
        $namespaceName = '';
1010
        while(isset($validTokens[$tokens[$nextToken]['code']]) === true) {
1011
            $namespaceName .= trim($tokens[$nextToken]['content']);
1012
            $nextToken++;
1013
        }
1014
1015
        return $namespaceName;
1016
    }
1017
1018
1019
    /**
1020
     * Get the stack pointer for a return type token for a given function.
1021
     *
1022
     * Compatible layer for older PHPCS versions which don't recognize
1023
     * return type hints correctly.
1024
     *
1025
     * Expects to be passed T_RETURN_TYPE, T_FUNCTION or T_CLOSURE token.
1026
     *
1027
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
1028
     * @param int                  $stackPtr  The position of the token.
1029
     *
1030
     * @return int|false Stack pointer to the return type token or false if
1031
     *                   no return type was found or the passed token was
1032
     *                   not of the correct type.
1033
     */
1034
    public function getReturnTypeHintToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1035
    {
1036
        $tokens = $phpcsFile->getTokens();
1037
1038
        if (defined('T_RETURN_TYPE') && $tokens[$stackPtr]['code'] === T_RETURN_TYPE) {
1039
            return $tokens[$stackPtr]['code'];
1040
        }
1041
1042 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...
1043
            return false;
1044
        }
1045
1046
        if (isset($tokens[$stackPtr]['parenthesis_closer'], $tokens[$stackPtr]['scope_opener']) === false
1047
            || ($tokens[$stackPtr]['parenthesis_closer'] + 1) === $tokens[$stackPtr]['scope_opener']
1048
        ) {
1049
            return false;
1050
        }
1051
1052
        $hasColon = $phpcsFile->findNext(array(T_COLON, T_INLINE_ELSE), ($tokens[$stackPtr]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']);
1053
        if ($hasColon === false) {
1054
            return false;
1055
        }
1056
1057
        // `self` and `callable` are not being recognized as return types in PHPCS < 2.6.0.
1058
        $unrecognizedTypes = array(
1059
            T_CALLABLE,
1060
            T_SELF,
1061
        );
1062
1063
        // Return types are not recognized at all in PHPCS < 2.4.0.
1064
        if (defined('T_RETURN_TYPE') === false) {
1065
            $unrecognizedTypes[] = T_ARRAY;
1066
            $unrecognizedTypes[] = T_STRING;
1067
        }
1068
1069
        return $phpcsFile->findNext($unrecognizedTypes, ($hasColon + 1), $tokens[$stackPtr]['scope_opener']);
1070
    }
1071
1072
1073
    /**
1074
     * Check whether a T_VARIABLE token is a class property declaration.
1075
     *
1076
     * Compatibility layer for PHPCS cross-version compatibility
1077
     * as PHPCS 2.4.0 - 2.7.1 does not have good enough support for
1078
     * anonymous classes. Along the same lines, the`getMemberProperties()`
1079
     * method does not support the `var` prefix.
1080
     *
1081
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1082
     * @param int                  $stackPtr  The position in the stack of the
1083
     *                                        T_VARIABLE token to verify.
1084
     *
1085
     * @return bool
1086
     */
1087
    public function isClassProperty(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1088
    {
1089
        $tokens = $phpcsFile->getTokens();
1090
1091 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...
1092
            return false;
1093
        }
1094
1095
        if (empty($tokens[$stackPtr]['conditions']) === true) {
1096
            return false;
1097
        }
1098
1099
        /*
1100
         * Check to see if the variable is a property by checking if the
1101
         * direct wrapping scope is a class like structure.
1102
         */
1103
        $conditions = array_keys($tokens[$stackPtr]['conditions']);
1104
        $ptr        = array_pop($conditions);
1105
1106
        if (isset($tokens[$ptr]) === false) {
1107
            return false;
1108
        }
1109
1110
        // Note: interfaces can not declare properties.
1111
        if ($tokens[$ptr]['type'] === 'T_CLASS'
1112
            || $tokens[$ptr]['type'] === 'T_ANON_CLASS'
1113
            || $tokens[$ptr]['type'] === 'T_TRAIT'
1114
        ) {
1115
            // Make sure it's not a method parameter.
1116
            if (empty($tokens[$stackPtr]['nested_parenthesis']) === true) {
1117
                return true;
1118
            }
1119
        }
1120
1121
        return false;
1122
    }
1123
1124
1125
    /**
1126
     * Returns the method parameters for the specified function token.
1127
     *
1128
     * Each parameter is in the following format:
1129
     *
1130
     * <code>
1131
     *   0 => array(
1132
     *         'name'              => '$var',  // The variable name.
1133
     *         'content'           => string,  // The full content of the variable definition.
1134
     *         'pass_by_reference' => boolean, // Is the variable passed by reference?
1135
     *         'type_hint'         => string,  // The type hint for the variable.
1136
     *         'nullable_type'     => boolean, // Is the variable using a nullable type?
1137
     *        )
1138
     * </code>
1139
     *
1140
     * Parameters with default values have an additional array index of
1141
     * 'default' with the value of the default as a string.
1142
     *
1143
     * {@internal Duplicate of same method as contained in the `PHP_CodeSniffer_File`
1144
     * class, but with some improvements which have been introduced in
1145
     * PHPCS 2.8.0.
1146
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1117},
1147
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1193} and
1148
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1293}.
1149
     *
1150
     * Once the minimum supported PHPCS version for this standard goes beyond
1151
     * that, this method can be removed and calls to it replaced with
1152
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.
1153
     *
1154
     * NOTE: This version does not deal with the new T_NULLABLE token type.
1155
     * This token is included upstream only in 2.7.2+ and as we defer to upstream
1156
     * in that case, no need to deal with it here.
1157
     *
1158
     * Last synced with PHPCS version: PHPCS 2.7.2-alpha.}}
1159
     *
1160
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1161
     * @param int                  $stackPtr  The position in the stack of the
1162
     *                                        function token to acquire the
1163
     *                                        parameters for.
1164
     *
1165
     * @return array|false
1166
     * @throws PHP_CodeSniffer_Exception If the specified $stackPtr is not of
1167
     *                                   type T_FUNCTION or T_CLOSURE.
1168
     */
1169
    public function getMethodParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1170
    {
1171
        if (version_compare(PHP_CodeSniffer::VERSION, '2.7.1', '>') === true) {
1172
            return $phpcsFile->getMethodParameters($stackPtr);
1173
        }
1174
1175
        $tokens = $phpcsFile->getTokens();
1176
1177
        // Check for the existence of the token.
1178
        if (isset($tokens[$stackPtr]) === false) {
1179
            return false;
1180
        }
1181
1182 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...
1183
            throw new PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION or T_CLOSURE');
1184
        }
1185
1186
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
1187
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
1188
1189
        $vars            = array();
1190
        $currVar         = null;
1191
        $paramStart      = ($opener + 1);
1192
        $defaultStart    = null;
1193
        $paramCount      = 0;
1194
        $passByReference = false;
1195
        $variableLength  = false;
1196
        $typeHint        = '';
1197
        $nullableType    = false;
1198
1199
        for ($i = $paramStart; $i <= $closer; $i++) {
1200
            // Check to see if this token has a parenthesis or bracket opener. If it does
1201
            // it's likely to be an array which might have arguments in it. This
1202
            // could cause problems in our parsing below, so lets just skip to the
1203
            // end of it.
1204 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...
1205
                // Don't do this if it's the close parenthesis for the method.
1206
                if ($i !== $tokens[$i]['parenthesis_closer']) {
1207
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
1208
                }
1209
            }
1210
1211 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...
1212
                // Don't do this if it's the close parenthesis for the method.
1213
                if ($i !== $tokens[$i]['bracket_closer']) {
1214
                    $i = ($tokens[$i]['bracket_closer'] + 1);
1215
                }
1216
            }
1217
1218
            switch ($tokens[$i]['code']) {
1219
            case T_BITWISE_AND:
1220
                $passByReference = true;
1221
                break;
1222
            case T_VARIABLE:
1223
                $currVar = $i;
1224
                break;
1225
            case T_ELLIPSIS:
1226
                $variableLength = true;
1227
                break;
1228
            case T_ARRAY_HINT:
1229
            case T_CALLABLE:
1230
                $typeHint .= $tokens[$i]['content'];
1231
                break;
1232
            case T_SELF:
1233
            case T_PARENT:
1234
            case T_STATIC:
1235
                // Self is valid, the others invalid, but were probably intended as type hints.
1236
                if (isset($defaultStart) === false) {
1237
                    $typeHint .= $tokens[$i]['content'];
1238
                }
1239
                break;
1240
            case T_STRING:
1241
                // This is a string, so it may be a type hint, but it could
1242
                // also be a constant used as a default value.
1243
                $prevComma = false;
1244 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...
1245
                    if ($tokens[$t]['code'] === T_COMMA) {
1246
                        $prevComma = $t;
1247
                        break;
1248
                    }
1249
                }
1250
1251
                if ($prevComma !== false) {
1252
                    $nextEquals = false;
1253 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...
1254
                        if ($tokens[$t]['code'] === T_EQUAL) {
1255
                            $nextEquals = $t;
1256
                            break;
1257
                        }
1258
                    }
1259
1260
                    if ($nextEquals !== false) {
1261
                        break;
1262
                    }
1263
                }
1264
1265
                if ($defaultStart === null) {
1266
                    $typeHint .= $tokens[$i]['content'];
1267
                }
1268
                break;
1269
            case T_NS_SEPARATOR:
1270
                // Part of a type hint or default value.
1271
                if ($defaultStart === null) {
1272
                    $typeHint .= $tokens[$i]['content'];
1273
                }
1274
                break;
1275
            case T_INLINE_THEN:
1276
                if ($defaultStart === null) {
1277
                    $nullableType = true;
1278
                    $typeHint    .= $tokens[$i]['content'];
1279
                }
1280
                break;
1281
            case T_CLOSE_PARENTHESIS:
1282
            case T_COMMA:
1283
                // If it's null, then there must be no parameters for this
1284
                // method.
1285
                if ($currVar === null) {
1286
                    continue;
1287
                }
1288
1289
                $vars[$paramCount]            = array();
1290
                $vars[$paramCount]['name']    = $tokens[$currVar]['content'];
1291
                $vars[$paramCount]['content'] = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
1292
1293
                if ($defaultStart !== null) {
1294
                    $vars[$paramCount]['default']
1295
                        = $phpcsFile->getTokensAsString(
1296
                            $defaultStart,
1297
                            ($i - $defaultStart)
1298
                        );
1299
                }
1300
1301
                $vars[$paramCount]['pass_by_reference'] = $passByReference;
1302
                $vars[$paramCount]['variable_length']   = $variableLength;
1303
                $vars[$paramCount]['type_hint']         = $typeHint;
1304
                $vars[$paramCount]['nullable_type']     = $nullableType;
1305
1306
                // Reset the vars, as we are about to process the next parameter.
1307
                $defaultStart    = null;
1308
                $paramStart      = ($i + 1);
1309
                $passByReference = false;
1310
                $variableLength  = false;
1311
                $typeHint        = '';
1312
                $nullableType    = false;
1313
1314
                $paramCount++;
1315
                break;
1316
            case T_EQUAL:
1317
                $defaultStart = ($i + 1);
1318
                break;
1319
            }//end switch
1320
        }//end for
1321
1322
        return $vars;
1323
1324
    }//end getMethodParameters()
1325
1326
1327
    /**
1328
     * Get the hash algorithm name from the parameter in a hash function call.
1329
     *
1330
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1331
     * @param int                  $stackPtr  The position of the T_STRING function token.
1332
     *
1333
     * @return string|false The algorithm name without quotes if this was a relevant hash
1334
     *                      function call or false if it was not.
1335
     */
1336
    public function getHashAlgorithmParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1337
    {
1338
        $tokens = $phpcsFile->getTokens();
1339
1340
        // Check for the existence of the token.
1341
        if (isset($tokens[$stackPtr]) === false) {
1342
            return false;
1343
        }
1344
1345
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1346
            return false;
1347
        }
1348
1349
        $functionName   = $tokens[$stackPtr]['content'];
1350
        $functionNameLc = strtolower($functionName);
1351
1352
        // Bow out if not one of the functions we're targetting.
1353
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
1354
            return false;
1355
        }
1356
1357
        // Get the parameter from the function call which should contain the algorithm name.
1358
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
1359
        if ($algoParam === false) {
1360
            return false;
1361
        }
1362
1363
        /**
1364
         * Algorithm is a text string, so we need to remove the quotes.
1365
         */
1366
        $algo = strtolower(trim($algoParam['raw']));
1367
        $algo = $this->stripQuotes($algo);
1368
1369
        return $algo;
1370
    }
1371
1372
}//end class
1373