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