Completed
Pull Request — master (#396)
by Juliette
02:05
created

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