Completed
Push — feature/minimal-codestyle-chec... ( aed179 )
by Juliette
02:09
created

Sniff.php (17 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
/**
3
 * PHPCompatibility_Sniff.
4
 *
5
 * @category  PHP
6
 * @package   PHPCompatibility
7
 * @author    Wim Godden <[email protected]>
8
 * @copyright 2014 Cu.be Solutions bvba
9
 */
10
11
/**
12
 * PHPCompatibility_Sniff.
13
 *
14
 * @category  PHP
15
 * @package   PHPCompatibility
16
 * @author    Wim Godden <[email protected]>
17
 * @copyright 2014 Cu.be Solutions bvba
18
 */
19
abstract class PHPCompatibility_Sniff implements PHP_CodeSniffer_Sniff
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
20
{
21
22
    const REGEX_COMPLEX_VARS = '`(?:(\{)?(?<!\\\\)\$)?(\{)?(?<!\\\\)\$(\{)?(?P<varname>[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)(?:->\$?(?P>varname)|\[[^\]]+\]|::\$?(?P>varname)|\([^\)]*\))*(?(3)\}|)(?(2)\}|)(?(1)\}|)`';
23
24
    /**
25
     * List of superglobals as an array of strings.
26
     *
27
     * Used by the ParameterShadowSuperGlobals and ForbiddenClosureUseVariableNames sniffs.
28
     *
29
     * @var array
30
     */
31
    protected $superglobals = array(
32
        '$GLOBALS',
33
        '$_SERVER',
34
        '$_GET',
35
        '$_POST',
36
        '$_FILES',
37
        '$_COOKIE',
38
        '$_SESSION',
39
        '$_REQUEST',
40
        '$_ENV',
41
    );
42
43
    /**
44
     * List of functions using hash algorithm as parameter (always the first parameter).
45
     *
46
     * Used by the new/removed hash algorithm sniffs.
47
     * Key is the function name, value is the 1-based parameter position in the function call.
48
     *
49
     * @var array
50
     */
51
    protected $hashAlgoFunctions = array(
52
        'hash_file'      => 1,
53
        'hash_hmac_file' => 1,
54
        'hash_hmac'      => 1,
55
        'hash_init'      => 1,
56
        'hash_pbkdf2'    => 1,
57
        'hash'           => 1,
58
    );
59
60
61
    /**
62
     * List of functions which take an ini directive as parameter (always the first parameter).
63
     *
64
     * Used by the new/removed ini directives sniffs.
65
     * Key is the function name, value is the 1-based parameter position in the function call.
66
     *
67
     * @var array
68
     */
69
    protected $iniFunctions = array(
70
        'ini_get' => 1,
71
        'ini_set' => 1,
72
    );
73
74
75
    /**
76
     * Get the testVersion configuration variable.
77
     *
78
     * The testVersion configuration variable may be in any of the following formats:
79
     * 1) Omitted/empty, in which case no version is specified. This effectively
80
     *    disables all the checks for new PHP features provided by this standard.
81
     * 2) A single PHP version number, e.g. "5.4" in which case the standard checks that
82
     *    the code will run on that version of PHP (no deprecated features or newer
83
     *    features being used).
84
     * 3) A range, e.g. "5.0-5.5", in which case the standard checks the code will run
85
     *    on all PHP versions in that range, and that it doesn't use any features that
86
     *    were deprecated by the final version in the list, or which were not available
87
     *    for the first version in the list.
88
     *    We accept ranges where one of the components is missing, e.g. "-5.6" means
89
     *    all versions up to PHP 5.6, and "7.0-" means all versions above PHP 7.0.
90
     * PHP version numbers should always be in Major.Minor format.  Both "5", "5.3.2"
91
     * would be treated as invalid, and ignored.
92
     *
93
     * @return array $arrTestVersions will hold an array containing min/max version
94
     *               of PHP that we are checking against (see above).  If only a
95
     *               single version number is specified, then this is used as
96
     *               both the min and max.
97
     *
98
     * @throws PHP_CodeSniffer_Exception If testVersion is invalid.
99
     */
100
    private function getTestVersion()
101
    {
102
        static $arrTestVersions = array();
103
104
        $testVersion = trim(PHP_CodeSniffer::getConfigData('testVersion'));
105
106
        if (!isset($arrTestVersions[$testVersion]) && !empty($testVersion)) {
107
108
            $arrTestVersions[$testVersion] = array(null, null);
109
            if (preg_match('/^\d+\.\d+$/', $testVersion)) {
110
                $arrTestVersions[$testVersion] = array($testVersion, $testVersion);
111
112
            } elseif (preg_match('/^(\d+\.\d+)\s*-\s*(\d+\.\d+)$/', $testVersion, $matches)) {
113
                if (version_compare($matches[1], $matches[2], '>')) {
114
                    trigger_error(
115
                        "Invalid range in testVersion setting: '" . $testVersion . "'",
116
                        E_USER_WARNING
117
                    );
118
                }
119
                else {
120
                    $arrTestVersions[$testVersion] = array($matches[1], $matches[2]);
121
                }
122
123
            } elseif (preg_match('/^\d+\.\d+-$/', $testVersion)) {
124
                $testVersion = substr($testVersion, 0, -1);
125
                // If no upper-limit is set, we set the max version to 99.9.
126
                // This is *probably* safe... :-)
127
                $arrTestVersions[$testVersion] = array($testVersion, '99.9');
128
129
            } elseif (preg_match('/^-\d+\.\d+$/', $testVersion)) {
130
                $testVersion = substr($testVersion, 1);
131
                // If no lower-limit is set, we set the min version to 4.0.
132
                // Whilst development focuses on PHP 5 and above, we also accept
133
                // sniffs for PHP 4, so we include that as the minimum.
134
                // (It makes no sense to support PHP 3 as this was effectively a
135
                // different language).
136
                $arrTestVersions[$testVersion] = array('4.0', $testVersion);
137
138
            } elseif (!$testVersion == '') {
139
                trigger_error(
140
                    "Invalid testVersion setting: '" . $testVersion . "'",
141
                    E_USER_WARNING
142
                );
143
            }
144
        }
145
146
        if (isset($arrTestVersions[$testVersion])) {
147
            return $arrTestVersions[$testVersion];
148
        } else {
149
            return array(null, null);
150
        }
151
    }
152
153
154
    /**
155
     * Check whether a specific PHP version is equal to or higher than the maximum
156
     * supported PHP version as provided by the user in `testVersion`.
157
     *
158
     * Should be used when sniffing for *old* PHP features (deprecated/removed).
159
     *
160
     * @param string $phpVersion A PHP version number in 'major.minor' format.
161
     *
162
     * @return bool True if testVersion has not been provided or if the PHP version
163
     *              is equal to or higher than the highest supported PHP version
164
     *              in testVersion. False otherwise.
165
     */
166 View Code Duplication
    public function supportsAbove($phpVersion)
0 ignored issues
show
This method seems to be duplicated in your project.

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

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

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

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

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

Loading history...
194
    {
195
        $testVersion = $this->getTestVersion();
196
        $testVersion = $testVersion[0];
197
198
        if (!is_null($testVersion)
199
            && version_compare($testVersion, $phpVersion) <= 0
200
        ) {
201
            return true;
202
        } else {
203
            return false;
204
        }
205
    }//end supportsBelow()
206
207
208
    /**
209
     * Add a PHPCS message to the output stack as either a warning or an error.
210
     *
211
     * @param PHP_CodeSniffer_File $phpcsFile The file the message applies to.
212
     * @param string               $message   The message.
213
     * @param int                  $stackPtr  The position of the token
214
     *                                        the message relates to.
215
     * @param bool                 $isError   Whether to report the message as an
216
     *                                        'error' or 'warning'.
217
     *                                        Defaults to true (error).
218
     * @param string               $code      The error code for the message.
219
     *                                        Defaults to 'Found'.
220
     * @param array                $data      Optional input for the data replacements.
221
     *
222
     * @return void
223
     */
224
    public function addMessage($phpcsFile, $message, $stackPtr, $isError, $code = 'Found', $data = array())
225
    {
226
        if ($isError === true) {
227
            $phpcsFile->addError($message, $stackPtr, $code, $data);
228
        } else {
229
            $phpcsFile->addWarning($message, $stackPtr, $code, $data);
230
        }
231
    }
232
233
234
    /**
235
     * Convert an arbitrary string to an alphanumeric string with underscores.
236
     *
237
     * Pre-empt issues with arbitrary strings being used as error codes in XML and PHP.
238
     *
239
     * @param string $baseString Arbitrary string.
240
     *
241
     * @return string
242
     */
243
    public function stringToErrorCode($baseString)
244
    {
245
        return preg_replace('`[^a-z0-9_]`i', '_', strtolower($baseString));
246
    }
247
248
249
    /**
250
     * Strip quotes surrounding an arbitrary string.
251
     *
252
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING / T_DOUBLE_QUOTED_STRING.
253
     *
254
     * @param string $string The raw string.
255
     *
256
     * @return string String without quotes around it.
257
     */
258
    public function stripQuotes($string)
259
    {
260
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
261
    }
262
263
264
    /**
265
     * Strip variables from an arbitrary double quoted string.
266
     *
267
     * Intended for use with the content of a T_DOUBLE_QUOTED_STRING.
268
     *
269
     * @param string $string The raw string.
270
     *
271
     * @return string String without variables in it.
272
     */
273
    public function stripVariables($string)
274
    {
275
        if (strpos($string, '$') === false) {
276
            return $string;
277
        }
278
279
        return preg_replace(self::REGEX_COMPLEX_VARS, '', $string);
280
    }
281
282
283
    /**
284
     * Make all top level array keys in an array lowercase.
285
     *
286
     * @param array $array Initial array.
287
     *
288
     * @return array Same array, but with all lowercase top level keys.
289
     */
290
    public function arrayKeysToLowercase($array)
291
    {
292
        $keys = array_keys($array);
293
        $keys = array_map('strtolower', $keys);
294
        return array_combine($keys, $array);
295
    }
296
297
298
    /**
299
     * Returns the name(s) of the interface(s) that the specified class implements.
300
     *
301
     * Returns FALSE on error or if there are no implemented interface names.
302
     *
303
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
304
     * This method also includes an improvement we use which was only introduced
305
     * in PHPCS 2.8.0, so only defer to upstream for higher versions.
306
     * Once the minimum supported PHPCS version for this sniff library goes beyond
307
     * that, this method can be removed and calls to it replaced with
308
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
309
     *
310
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
311
     * @param int                  $stackPtr  The position of the class token.
312
     *
313
     * @return array|false
314
     */
315
    public function findImplementedInterfaceNames(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
316
    {
317
        if (version_compare(PHP_CodeSniffer::VERSION, '2.7.1', '>') === true) {
318
            return $phpcsFile->findImplementedInterfaceNames($stackPtr);
319
        }
320
321
        $tokens = $phpcsFile->getTokens();
322
323
        // Check for the existence of the token.
324
        if (isset($tokens[$stackPtr]) === false) {
325
            return false;
326
        }
327
328 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
329
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
330
        ) {
331
            return false;
332
        }
333
334
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
335
            return false;
336
        }
337
338
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
339
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
340
        if ($implementsIndex === false) {
341
            return false;
342
        }
343
344
        $find = array(
345
            T_NS_SEPARATOR,
346
            T_STRING,
347
            T_WHITESPACE,
348
            T_COMMA,
349
        );
350
351
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
352
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
353
        $name = trim($name);
354
355
        if ($name === '') {
356
            return false;
357
        } else {
358
            $names = explode(',', $name);
359
            $names = array_map('trim', $names);
360
            return $names;
361
        }
362
363
    }//end findImplementedInterfaceNames()
364
365
366
    /**
367
     * Checks if a function call has parameters.
368
     *
369
     * Expects to be passed the T_STRING stack pointer for the function call.
370
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
371
     *
372
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer, it
373
     * will detect whether the array has values or is empty.
374
     *
375
     * @link https://github.com/wimg/PHPCompatibility/issues/120
376
     * @link https://github.com/wimg/PHPCompatibility/issues/152
377
     *
378
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
379
     * @param int                  $stackPtr  The position of the function call token.
380
     *
381
     * @return bool
382
     */
383
    public function doesFunctionCallHaveParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
384
    {
385
        $tokens = $phpcsFile->getTokens();
386
387
        // Check for the existence of the token.
388
        if (isset($tokens[$stackPtr]) === false) {
389
            return false;
390
        }
391
392
        // Is this one of the tokens this function handles ?
393
        if (in_array($tokens[$stackPtr]['code'], array(T_STRING, T_ARRAY, T_OPEN_SHORT_ARRAY), true) === false) {
394
            return false;
395
        }
396
397
        $nextNonEmpty = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
398
399
        // Deal with short array syntax.
400
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
401
            if (isset($tokens[$stackPtr]['bracket_closer']) === false) {
402
                return false;
403
            }
404
405
            if ($nextNonEmpty === $tokens[$stackPtr]['bracket_closer']) {
406
                // No parameters.
407
                return false;
408
            } else {
409
                return true;
410
            }
411
        }
412
413
        // Deal with function calls & long arrays.
414
        // Next non-empty token should be the open parenthesis.
415
        if ($nextNonEmpty === false && $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS) {
416
            return false;
417
        }
418
419
        if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
420
            return false;
421
        }
422
423
        $closeParenthesis = $tokens[$nextNonEmpty]['parenthesis_closer'];
424
        $nextNextNonEmpty = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $nextNonEmpty + 1, $closeParenthesis + 1, true);
425
426
        if ($nextNextNonEmpty === $closeParenthesis) {
427
            // No parameters.
428
            return false;
429
        }
430
431
        return true;
432
    }
433
434
435
    /**
436
     * Count the number of parameters a function call has been passed.
437
     *
438
     * Expects to be passed the T_STRING stack pointer for the function call.
439
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
440
     *
441
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
442
     * it will return the number of values in the array.
443
     *
444
     * @link https://github.com/wimg/PHPCompatibility/issues/111
445
     * @link https://github.com/wimg/PHPCompatibility/issues/114
446
     * @link https://github.com/wimg/PHPCompatibility/issues/151
447
     *
448
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
449
     * @param int                  $stackPtr  The position of the function call token.
450
     *
451
     * @return int
452
     */
453
    public function getFunctionCallParameterCount(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
454
    {
455
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
456
            return 0;
457
        }
458
459
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
460
    }
461
462
463
    /**
464
     * Get information on all parameters passed to a function call.
465
     *
466
     * Expects to be passed the T_STRING stack pointer for the function call.
467
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
468
     *
469
     * Will return an multi-dimentional array with the start token pointer, end token
470
     * pointer and raw parameter value for all parameters. Index will be 1-based.
471
     * If no parameters are found, will return an empty array.
472
     *
473
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
474
     * it will tokenize the values / key/value pairs contained in the array call.
475
     *
476
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
477
     * @param int                  $stackPtr  The position of the function call token.
478
     *
479
     * @return array
480
     */
481
    public function getFunctionCallParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
482
    {
483
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
484
            return array();
485
        }
486
487
        // Ok, we know we have a T_STRING, T_ARRAY or T_OPEN_SHORT_ARRAY with parameters
488
        // and valid open & close brackets/parenthesis.
489
        $tokens = $phpcsFile->getTokens();
490
491
        // Mark the beginning and end tokens.
492
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
493
            $opener = $stackPtr;
494
            $closer = $tokens[$stackPtr]['bracket_closer'];
495
496
            $nestedParenthesisCount = 0;
497
498
        } else {
499
            $opener = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
500
            $closer = $tokens[$opener]['parenthesis_closer'];
501
502
            $nestedParenthesisCount = 1;
503
        }
504
505
        // Which nesting level is the one we are interested in ?
506 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...
507
            $nestedParenthesisCount += count($tokens[$opener]['nested_parenthesis']);
508
        }
509
510
        $parameters = array();
511
        $nextComma  = $opener;
512
        $paramStart = $opener + 1;
513
        $cnt        = 1;
514
        while ($nextComma = $phpcsFile->findNext(array(T_COMMA, $tokens[$closer]['code'], T_OPEN_SHORT_ARRAY), $nextComma + 1, $closer + 1)) {
515
            // Ignore anything within short array definition brackets.
516
            if ($tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
517
                && (isset($tokens[$nextComma]['bracket_opener'])
518
                    && $tokens[$nextComma]['bracket_opener'] === $nextComma)
519
                && isset($tokens[$nextComma]['bracket_closer'])
520
            ) {
521
                // Skip forward to the end of the short array definition.
522
                $nextComma = $tokens[$nextComma]['bracket_closer'];
523
                continue;
524
            }
525
526
            // Ignore comma's at a lower nesting level.
527
            if ($tokens[$nextComma]['type'] === 'T_COMMA'
528
                && isset($tokens[$nextComma]['nested_parenthesis'])
529
                && count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
530
            ) {
531
                continue;
532
            }
533
534
            // Ignore closing parenthesis/bracket if not 'ours'.
535
            if ($tokens[$nextComma]['type'] === $tokens[$closer]['type'] && $nextComma !== $closer) {
536
                continue;
537
            }
538
539
            // Ok, we've reached the end of the parameter.
540
            $parameters[$cnt]['start'] = $paramStart;
541
            $parameters[$cnt]['end']   = $nextComma - 1;
542
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
543
544
            // Check if there are more tokens before the closing parenthesis.
545
            // Prevents code like the following from setting a third parameter:
546
            // 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...
547
            $hasNextParam = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closer, true, null, true);
548
            if ($hasNextParam === false) {
549
                break;
550
            }
551
552
            // Prepare for the next parameter.
553
            $paramStart = $nextComma + 1;
554
            $cnt++;
555
        }
556
557
        return $parameters;
558
    }
559
560
561
    /**
562
     * Get information on a specific parameter passed to a function call.
563
     *
564
     * Expects to be passed the T_STRING stack pointer for the function call.
565
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
566
     *
567
     * Will return a array with the start token pointer, end token pointer and the raw value
568
     * of the parameter at a specific offset.
569
     * If the specified parameter is not found, will return false.
570
     *
571
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
572
     * @param int                  $stackPtr    The position of the function call token.
573
     * @param int                  $paramOffset The 1-based index position of the parameter to retrieve.
574
     *
575
     * @return array|false
576
     */
577
    public function getFunctionCallParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
578
    {
579
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
580
581
        if (isset($parameters[$paramOffset]) === false) {
582
            return false;
583
        }
584
        else {
585
            return $parameters[$paramOffset];
586
        }
587
    }
588
589
590
    /**
591
     * Verify whether a token is within a scoped condition.
592
     *
593
     * If the optional $validScopes parameter has been passed, the function
594
     * will check that the token has at least one condition which is of a
595
     * type defined in $validScopes.
596
     *
597
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
598
     * @param int                  $stackPtr    The position of the token.
599
     * @param array|int            $validScopes Optional. Array of valid scopes
600
     *                                          or int value of a valid scope.
601
     *                                          Pass the T_.. constant(s) for the
602
     *                                          desired scope to this parameter.
603
     *
604
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
605
     *              If the $scopeTypes are set: True if *one* of the conditions is a
606
     *              valid scope, false otherwise.
607
     */
608
    public function tokenHasScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
609
    {
610
        $tokens = $phpcsFile->getTokens();
611
612
        // Check for the existence of the token.
613
        if (isset($tokens[$stackPtr]) === false) {
614
            return false;
615
        }
616
617
        // No conditions = no scope.
618
        if (empty($tokens[$stackPtr]['conditions'])) {
619
            return false;
620
        }
621
622
        // Ok, there are conditions, do we have to check for specific ones ?
623
        if (isset($validScopes) === false) {
624
            return true;
625
        }
626
627
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
628
    }
629
630
631
    /**
632
     * Verify whether a token is within a class scope.
633
     *
634
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
635
     * @param int                  $stackPtr  The position of the token.
636
     * @param bool                 $strict    Whether to strictly check for the T_CLASS
637
     *                                        scope or also accept interfaces and traits
638
     *                                        as scope.
639
     *
640
     * @return bool True if within class scope, false otherwise.
641
     */
642
    public function inClassScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
643
    {
644
        $validScopes = array(T_CLASS);
645
        if (defined('T_ANON_CLASS') === true) {
646
            $validScopes[] = T_ANON_CLASS;
647
        }
648
649
        if ($strict === false) {
650
            $validScopes[] = T_INTERFACE;
651
            $validScopes[] = T_TRAIT;
652
        }
653
654
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
655
    }
656
657
658
    /**
659
     * Verify whether a token is within a scoped use statement.
660
     *
661
     * PHPCS cross-version compatibility method.
662
     *
663
     * In PHPCS 1.x no conditions are set for a scoped use statement.
664
     * This method works around that limitation.
665
     *
666
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
667
     * @param int                  $stackPtr  The position of the token.
668
     *
669
     * @return bool True if within use scope, false otherwise.
670
     */
671
    public function inUseScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
672
    {
673
        static $isLowPHPCS, $ignoreTokens;
674
675
        if (isset($isLowPHPCS) === false) {
676
            $isLowPHPCS = version_compare(PHP_CodeSniffer::VERSION, '2.0', '<');
677
        }
678
        if (isset($ignoreTokens) === false) {
679
            $ignoreTokens              = PHP_CodeSniffer_Tokens::$emptyTokens;
680
            $ignoreTokens[T_STRING]    = T_STRING;
681
            $ignoreTokens[T_AS]        = T_AS;
682
            $ignoreTokens[T_PUBLIC]    = T_PUBLIC;
683
            $ignoreTokens[T_PROTECTED] = T_PROTECTED;
684
            $ignoreTokens[T_PRIVATE]   = T_PRIVATE;
685
        }
686
687
        // PHPCS 2.0.
688
        if ($isLowPHPCS === false) {
689
            return $phpcsFile->hasCondition($stackPtr, T_USE);
690
        } else {
691
            // PHPCS 1.x.
692
            $tokens         = $phpcsFile->getTokens();
693
            $maybeCurlyOpen = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
694
            if ($tokens[$maybeCurlyOpen]['code'] === T_OPEN_CURLY_BRACKET) {
695
                $maybeUseStatement = $phpcsFile->findPrevious($ignoreTokens, ($maybeCurlyOpen - 1), null, true);
696
                if ($tokens[$maybeUseStatement]['code'] === T_USE) {
697
                    return true;
698
                }
699
            }
700
            return false;
701
        }
702
    }
703
704
705
    /**
706
     * Returns the fully qualified class name for a new class instantiation.
707
     *
708
     * Returns an empty string if the class name could not be reliably inferred.
709
     *
710
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
711
     * @param int                  $stackPtr  The position of a T_NEW token.
712
     *
713
     * @return string
714
     */
715
    public function getFQClassNameFromNewToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
716
    {
717
        $tokens = $phpcsFile->getTokens();
718
719
        // Check for the existence of the token.
720
        if (isset($tokens[$stackPtr]) === false) {
721
            return '';
722
        }
723
724
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
725
            return '';
726
        }
727
728
        $start = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
729
        if ($start === false) {
730
            return '';
731
        }
732
733
        // Bow out if the next token is a variable as we don't know where it was defined.
734
        if ($tokens[$start]['code'] === T_VARIABLE) {
735
            return '';
736
        }
737
738
        // Bow out if the next token is the class keyword.
739
        if ($tokens[$start]['type'] === 'T_ANON_CLASS' || $tokens[$start]['code'] === T_CLASS) {
740
            return '';
741
        }
742
743
        $find = array(
744
            T_NS_SEPARATOR,
745
            T_STRING,
746
            T_NAMESPACE,
747
            T_WHITESPACE,
748
        );
749
750
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
751
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
752
        $className = trim($className);
753
754
        return $this->getFQName($phpcsFile, $stackPtr, $className);
755
    }
756
757
758
    /**
759
     * Returns the fully qualified name of the class that the specified class extends.
760
     *
761
     * Returns an empty string if the class does not extend another class or if
762
     * the class name could not be reliably inferred.
763
     *
764
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
765
     * @param int                  $stackPtr  The position of a T_CLASS token.
766
     *
767
     * @return string
768
     */
769
    public function getFQExtendedClassName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
770
    {
771
        $tokens = $phpcsFile->getTokens();
772
773
        // Check for the existence of the token.
774
        if (isset($tokens[$stackPtr]) === false) {
775
            return '';
776
        }
777
778 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS') {
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
779
            return '';
780
        }
781
782
        $extends = $phpcsFile->findExtendedClassName($stackPtr);
783
        if (empty($extends) || is_string($extends) === false) {
784
            return '';
785
        }
786
787
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
788
    }
789
790
791
    /**
792
     * Returns the class name for the static usage of a class.
793
     * This can be a call to a method, the use of a property or constant.
794
     *
795
     * Returns an empty string if the class name could not be reliably inferred.
796
     *
797
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
798
     * @param int                  $stackPtr  The position of a T_NEW token.
799
     *
800
     * @return string
801
     */
802
    public function getFQClassNameFromDoubleColonToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
803
    {
804
        $tokens = $phpcsFile->getTokens();
805
806
        // Check for the existence of the token.
807
        if (isset($tokens[$stackPtr]) === false) {
808
            return '';
809
        }
810
811
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
812
            return '';
813
        }
814
815
        // Nothing to do if previous token is a variable as we don't know where it was defined.
816
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
817
            return '';
818
        }
819
820
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
821
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
822
            return '';
823
        }
824
825
        // Get the classname from the class declaration if self is used.
826
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
827
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
828
            if ($classDeclarationPtr === false) {
829
                return '';
830
            }
831
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
832
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
833
        }
834
835
        $find = array(
836
            T_NS_SEPARATOR,
837
            T_STRING,
838
            T_NAMESPACE,
839
            T_WHITESPACE,
840
        );
841
842
        $start = ($phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true) + 1);
843
        if ($start === false) {
844
            return '';
845
        }
846
847
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
848
        $className = trim($className);
849
850
        return $this->getFQName($phpcsFile, $stackPtr, $className);
851
    }
852
853
854
    /**
855
     * Get the Fully Qualified name for a class/function/constant etc.
856
     *
857
     * Checks if a class/function/constant name is already fully qualified and
858
     * if not, enrich it with the relevant namespace information.
859
     *
860
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
861
     * @param int                  $stackPtr  The position of the token.
862
     * @param string               $name      The class / function / constant name.
863
     *
864
     * @return string
865
     */
866
    public function getFQName(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
867
    {
868
        if (strpos($name, '\\') === 0) {
869
            // Already fully qualified.
870
            return $name;
871
        }
872
873
        // Remove the namespace keyword if used.
874
        if (strpos($name, 'namespace\\') === 0) {
875
            $name = substr($name, 10);
876
        }
877
878
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
879
880
        if ($namespace === '') {
881
            return '\\' . $name;
882
        }
883
        else {
884
            return '\\' . $namespace . '\\' . $name;
885
        }
886
    }
887
888
889
    /**
890
     * Is the class/function/constant name namespaced or global ?
891
     *
892
     * @param string $FQName Fully Qualified name of a class, function etc.
893
     *                       I.e. should always start with a `\`.
894
     *
895
     * @return bool True if namespaced, false if global.
896
     */
897
    public function isNamespaced($FQName)
898
    {
899
        if (strpos($FQName, '\\') !== 0) {
900
            throw new PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
901
        }
902
903
        return (strpos(substr($FQName, 1), '\\') !== false);
904
    }
905
906
907
    /**
908
     * Determine the namespace name an arbitrary token lives in.
909
     *
910
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
911
     * @param int                  $stackPtr  The token position for which to determine the namespace.
912
     *
913
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
914
     */
915
    public function determineNamespace(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
916
    {
917
        $tokens = $phpcsFile->getTokens();
918
919
        // Check for the existence of the token.
920
        if (isset($tokens[$stackPtr]) === false) {
921
            return '';
922
        }
923
924
        // Check for scoped namespace {}.
925
        if (empty($tokens[$stackPtr]['conditions']) === false) {
926
            $namespacePtr = $phpcsFile->getCondition($stackPtr, T_NAMESPACE);
927
            if ($namespacePtr !== false) {
928
                $namespace = $this->getDeclaredNamespaceName($phpcsFile, $namespacePtr);
929
                if ($namespace !== false) {
930
                    return $namespace;
931
                }
932
933
                // We are in a scoped namespace, but couldn't determine the name. Searching for a global namespace is futile.
934
                return '';
935
            }
936
        }
937
938
        /*
939
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
940
         * Keeping in mind that:
941
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
942
         * - the namespace keyword can also be used as part of a function/method call and such.
943
         * - that a non-named namespace resolves to the global namespace.
944
         */
945
        $previousNSToken = $stackPtr;
946
        $namespace       = false;
947
        do {
948
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, ($previousNSToken - 1));
949
950
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
951
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] === $previousNSToken) {
952
                break;
953
            }
954
955
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
956
957
        } while ($namespace === false && $previousNSToken !== false);
958
959
        // If we still haven't got a namespace, return an empty string.
960
        if ($namespace === false) {
961
            return '';
962
        }
963
        else {
964
            return $namespace;
965
        }
966
    }
967
968
    /**
969
     * Get the complete namespace name for a namespace declaration.
970
     *
971
     * For hierarchical namespaces, the name will be composed of several tokens,
972
     * i.e. MyProject\Sub\Level which will be returned together as one string.
973
     *
974
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
975
     * @param int|bool             $stackPtr  The position of a T_NAMESPACE token.
976
     *
977
     * @return string|false Namespace name or false if not a namespace declaration.
978
     *                      Namespace name can be an empty string for global namespace declaration.
979
     */
980
    public function getDeclaredNamespaceName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
981
    {
982
        $tokens = $phpcsFile->getTokens();
983
984
        // Check for the existence of the token.
985 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...
986
            return false;
987
        }
988
989
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
990
            return false;
991
        }
992
993
        if ($tokens[($stackPtr + 1)]['code'] === T_NS_SEPARATOR) {
994
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
995
            return false;
996
        }
997
998
        $nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
999
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
1000
            // Declaration for global namespace when using multiple namespaces in a file.
1001
            // I.e.: namespace {}
1002
            return '';
1003
        }
1004
1005
        // Ok, this should be a namespace declaration, so get all the parts together.
1006
        $validTokens = array(
1007
            T_STRING       => true,
1008
            T_NS_SEPARATOR => true,
1009
            T_WHITESPACE   => true,
1010
        );
1011
1012
        $namespaceName = '';
1013
        while (isset($validTokens[$tokens[$nextToken]['code']]) === true) {
1014
            $namespaceName .= trim($tokens[$nextToken]['content']);
1015
            $nextToken++;
1016
        }
1017
1018
        return $namespaceName;
1019
    }
1020
1021
1022
    /**
1023
     * Get the stack pointer for a return type token for a given function.
1024
     *
1025
     * Compatible layer for older PHPCS versions which don't recognize
1026
     * return type hints correctly.
1027
     *
1028
     * Expects to be passed T_RETURN_TYPE, T_FUNCTION or T_CLOSURE token.
1029
     *
1030
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
1031
     * @param int                  $stackPtr  The position of the token.
1032
     *
1033
     * @return int|false Stack pointer to the return type token or false if
1034
     *                   no return type was found or the passed token was
1035
     *                   not of the correct type.
1036
     */
1037
    public function getReturnTypeHintToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1038
    {
1039
        $tokens = $phpcsFile->getTokens();
1040
1041
        if (defined('T_RETURN_TYPE') && $tokens[$stackPtr]['code'] === T_RETURN_TYPE) {
1042
            return $tokens[$stackPtr]['code'];
1043
        }
1044
1045 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...
1046
            return false;
1047
        }
1048
1049
        if (isset($tokens[$stackPtr]['parenthesis_closer'], $tokens[$stackPtr]['scope_opener']) === false
1050
            || ($tokens[$stackPtr]['parenthesis_closer'] + 1) === $tokens[$stackPtr]['scope_opener']
1051
        ) {
1052
            return false;
1053
        }
1054
1055
        $hasColon = $phpcsFile->findNext(array(T_COLON, T_INLINE_ELSE), ($tokens[$stackPtr]['parenthesis_closer'] + 1), $tokens[$stackPtr]['scope_opener']);
1056
        if ($hasColon === false) {
1057
            return false;
1058
        }
1059
1060
        // `self` and `callable` are not being recognized as return types in PHPCS < 2.6.0.
1061
        $unrecognizedTypes = array(
1062
            T_CALLABLE,
1063
            T_SELF,
1064
        );
1065
1066
        // Return types are not recognized at all in PHPCS < 2.4.0.
1067
        if (defined('T_RETURN_TYPE') === false) {
1068
            $unrecognizedTypes[] = T_ARRAY;
1069
            $unrecognizedTypes[] = T_STRING;
1070
        }
1071
1072
        return $phpcsFile->findNext($unrecognizedTypes, ($hasColon + 1), $tokens[$stackPtr]['scope_opener']);
1073
    }
1074
1075
1076
    /**
1077
     * Check whether a T_VARIABLE token is a class property declaration.
1078
     *
1079
     * Compatibility layer for PHPCS cross-version compatibility
1080
     * as PHPCS 2.4.0 - 2.7.1 does not have good enough support for
1081
     * anonymous classes. Along the same lines, the`getMemberProperties()`
1082
     * method does not support the `var` prefix.
1083
     *
1084
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1085
     * @param int                  $stackPtr  The position in the stack of the
1086
     *                                        T_VARIABLE token to verify.
1087
     *
1088
     * @return bool
1089
     */
1090
    public function isClassProperty(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1091
    {
1092
        $tokens = $phpcsFile->getTokens();
1093
1094 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...
1095
            return false;
1096
        }
1097
1098
        // Note: interfaces can not declare properties.
1099
        $validScopes = array(
1100
            'T_CLASS'      => true,
1101
            'T_ANON_CLASS' => true,
1102
            'T_TRAIT'      => true,
1103
        );
1104
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1105
            // Make sure it's not a method parameter.
1106
            if (empty($tokens[$stackPtr]['nested_parenthesis']) === true) {
1107
                return true;
1108
            }
1109
        }
1110
1111
        return false;
1112
    }
1113
1114
1115
    /**
1116
     * Check whether a T_CONST token is a class constant declaration.
1117
     *
1118
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1119
     * @param int                  $stackPtr  The position in the stack of the
1120
     *                                        T_CONST token to verify.
1121
     *
1122
     * @return bool
1123
     */
1124
    public function isClassConstant(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1125
    {
1126
        $tokens = $phpcsFile->getTokens();
1127
1128 View Code Duplication
        if (isset($tokens[$stackPtr]) === false || $tokens[$stackPtr]['code'] !== T_CONST) {
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
1129
            return false;
1130
        }
1131
1132
        // Note: traits can not declare constants.
1133
        $validScopes = array(
1134
            'T_CLASS'      => true,
1135
            'T_ANON_CLASS' => true,
1136
            'T_INTERFACE'  => true,
1137
        );
1138
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1139
            return true;
1140
        }
1141
1142
        return false;
1143
    }
1144
1145
1146
    /**
1147
     * Check whether the direct wrapping scope of a token is within a limited set of
1148
     * acceptable tokens.
1149
     *
1150
     * Used to check, for instance, if a T_CONST is a class constant.
1151
     *
1152
     * @param PHP_CodeSniffer_File $phpcsFile   Instance of phpcsFile.
1153
     * @param int                  $stackPtr    The position in the stack of the
1154
     *                                          T_CONST token to verify.
1155
     * @param array                $validScopes Array of token types.
1156
     *                                          Keys should be the token types in string
1157
     *                                          format to allow for newer token types.
1158
     *                                          Value is irrelevant.
1159
     *
1160
     * @return bool
1161
     */
1162
    protected function validDirectScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes)
1163
    {
1164
        $tokens = $phpcsFile->getTokens();
1165
1166
        if (empty($tokens[$stackPtr]['conditions']) === true) {
1167
            return false;
1168
        }
1169
1170
        /*
1171
         * Check only the direct wrapping scope of the token.
1172
         */
1173
        $conditions = array_keys($tokens[$stackPtr]['conditions']);
1174
        $ptr        = array_pop($conditions);
1175
1176
        if (isset($tokens[$ptr]) === false) {
1177
            return false;
1178
        }
1179
1180
        if (isset($validScopes[$tokens[$ptr]['type']]) === true) {
1181
            return true;
1182
        }
1183
1184
        return false;
1185
    }
1186
1187
1188
    /**
1189
     * Get an array of just the type hints from a function declaration.
1190
     *
1191
     * Expects to be passed T_FUNCTION or T_CLOSURE token.
1192
     *
1193
     * Strips potential nullable indicator and potential global namespace
1194
     * indicator from the type hints before returning them.
1195
     *
1196
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
1197
     * @param int                  $stackPtr  The position of the token.
1198
     *
1199
     * @return array Array with type hints or an empty array if
1200
     *               - the function does not have any parameters
1201
     *               - no type hints were found
1202
     *               - or the passed token was not of the correct type.
1203
     */
1204
    public function getTypeHintsFromFunctionDeclaration(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1205
    {
1206
        $tokens = $phpcsFile->getTokens();
1207
1208 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...
1209
            return array();
1210
        }
1211
1212
        $parameters = $this->getMethodParameters($phpcsFile, $stackPtr);
1213
        if (empty($parameters) || is_array($parameters) === false) {
1214
            return array();
1215
        }
1216
1217
        $typeHints = array();
1218
1219
        foreach ($parameters as $param) {
1220
            if ($param['type_hint'] === '') {
1221
                continue;
1222
            }
1223
1224
            // Strip off potential nullable indication.
1225
            $typeHint = ltrim($param['type_hint'], '?');
1226
1227
            // Strip off potential (global) namespace indication.
1228
            $typeHint = ltrim($typeHint, '\\');
1229
1230
            if ($typeHint !== '') {
1231
                $typeHints[] = $typeHint;
1232
            }
1233
        }
1234
1235
        return $typeHints;
1236
    }
1237
1238
1239
    /**
1240
     * Returns the method parameters for the specified function token.
1241
     *
1242
     * Each parameter is in the following format:
1243
     *
1244
     * <code>
1245
     *   0 => array(
1246
     *         'token'             => int,     // The position of the var in the token stack.
1247
     *         'name'              => '$var',  // The variable name.
1248
     *         'content'           => string,  // The full content of the variable definition.
1249
     *         'pass_by_reference' => boolean, // Is the variable passed by reference?
1250
     *         'variable_length'   => boolean, // Is the param of variable length through use of `...` ?
1251
     *         'type_hint'         => string,  // The type hint for the variable.
1252
     *         'nullable_type'     => boolean, // Is the variable using a nullable type?
1253
     *        )
1254
     * </code>
1255
     *
1256
     * Parameters with default values have an additional array index of
1257
     * 'default' with the value of the default as a string.
1258
     *
1259
     * {@internal Duplicate of same method as contained in the `PHP_CodeSniffer_File`
1260
     * class, but with some improvements which have been introduced in
1261
     * PHPCS 2.8.0.
1262
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1117},
1263
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1193} and
1264
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1293}.
1265
     *
1266
     * Once the minimum supported PHPCS version for this standard goes beyond
1267
     * that, this method can be removed and calls to it replaced with
1268
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.
1269
     *
1270
     * NOTE: This version does not deal with the new T_NULLABLE token type.
1271
     * This token is included upstream only in 2.8.0+ and as we defer to upstream
1272
     * in that case, no need to deal with it here.
1273
     *
1274
     * Last synced with PHPCS version: PHPCS 2.9.0-alpha at commit f1511adad043edfd6d2e595e77385c32577eb2bc}}
1275
     *
1276
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1277
     * @param int                  $stackPtr  The position in the stack of the
1278
     *                                        function token to acquire the
1279
     *                                        parameters for.
1280
     *
1281
     * @return array|false
1282
     * @throws PHP_CodeSniffer_Exception If the specified $stackPtr is not of
1283
     *                                   type T_FUNCTION or T_CLOSURE.
1284
     */
1285
    public function getMethodParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1286
    {
1287
        if (version_compare(PHP_CodeSniffer::VERSION, '2.7.1', '>') === true) {
1288
            return $phpcsFile->getMethodParameters($stackPtr);
1289
        }
1290
1291
        $tokens = $phpcsFile->getTokens();
1292
1293
        // Check for the existence of the token.
1294
        if (isset($tokens[$stackPtr]) === false) {
1295
            return false;
1296
        }
1297
1298 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...
1299
            throw new PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION or T_CLOSURE');
1300
        }
1301
1302
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
1303
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
1304
1305
        $vars            = array();
1306
        $currVar         = null;
1307
        $paramStart      = ($opener + 1);
1308
        $defaultStart    = null;
1309
        $paramCount      = 0;
1310
        $passByReference = false;
1311
        $variableLength  = false;
1312
        $typeHint        = '';
1313
        $nullableType    = false;
1314
1315
        for ($i = $paramStart; $i <= $closer; $i++) {
1316
            // Check to see if this token has a parenthesis or bracket opener. If it does
1317
            // it's likely to be an array which might have arguments in it. This
1318
            // could cause problems in our parsing below, so lets just skip to the
1319
            // end of it.
1320 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...
1321
                // Don't do this if it's the close parenthesis for the method.
1322
                if ($i !== $tokens[$i]['parenthesis_closer']) {
1323
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
1324
                }
1325
            }
1326
1327 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...
1328
                // Don't do this if it's the close parenthesis for the method.
1329
                if ($i !== $tokens[$i]['bracket_closer']) {
1330
                    $i = ($tokens[$i]['bracket_closer'] + 1);
1331
                }
1332
            }
1333
1334
            switch ($tokens[$i]['code']) {
1335
                case T_BITWISE_AND:
1336
                    $passByReference = true;
1337
                    break;
1338
                case T_VARIABLE:
1339
                    $currVar = $i;
1340
                    break;
1341
                case T_ELLIPSIS:
1342
                    $variableLength = true;
1343
                    break;
1344
                case T_ARRAY_HINT:
1345
                case T_CALLABLE:
1346
                    $typeHint .= $tokens[$i]['content'];
1347
                    break;
1348
                case T_SELF:
1349
                case T_PARENT:
1350
                case T_STATIC:
1351
                    // Self is valid, the others invalid, but were probably intended as type hints.
1352
                    if (isset($defaultStart) === false) {
1353
                        $typeHint .= $tokens[$i]['content'];
1354
                    }
1355
                    break;
1356
                case T_STRING:
1357
                    // This is a string, so it may be a type hint, but it could
1358
                    // also be a constant used as a default value.
1359
                    $prevComma = false;
1360 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...
1361
                        if ($tokens[$t]['code'] === T_COMMA) {
1362
                            $prevComma = $t;
1363
                            break;
1364
                        }
1365
                    }
1366
    
1367
                    if ($prevComma !== false) {
1368
                        $nextEquals = false;
1369 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...
1370
                            if ($tokens[$t]['code'] === T_EQUAL) {
1371
                                $nextEquals = $t;
1372
                                break;
1373
                            }
1374
                        }
1375
    
1376
                        if ($nextEquals !== false) {
1377
                            break;
1378
                        }
1379
                    }
1380
    
1381
                    if ($defaultStart === null) {
1382
                        $typeHint .= $tokens[$i]['content'];
1383
                    }
1384
                    break;
1385
                case T_NS_SEPARATOR:
1386
                    // Part of a type hint or default value.
1387
                    if ($defaultStart === null) {
1388
                        $typeHint .= $tokens[$i]['content'];
1389
                    }
1390
                    break;
1391
                case T_INLINE_THEN:
1392
                    if ($defaultStart === null) {
1393
                        $nullableType = true;
1394
                        $typeHint    .= $tokens[$i]['content'];
1395
                    }
1396
                    break;
1397
                case T_CLOSE_PARENTHESIS:
1398
                case T_COMMA:
1399
                    // If it's null, then there must be no parameters for this
1400
                    // method.
1401
                    if ($currVar === null) {
1402
                        continue;
1403
                    }
1404
    
1405
                    $vars[$paramCount]            = array();
1406
                    $vars[$paramCount]['token']   = $currVar;
1407
                    $vars[$paramCount]['name']    = $tokens[$currVar]['content'];
1408
                    $vars[$paramCount]['content'] = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
1409
    
1410
                    if ($defaultStart !== null) {
1411
                        $vars[$paramCount]['default']
1412
                            = trim($phpcsFile->getTokensAsString(
1413
                                $defaultStart,
1414
                                ($i - $defaultStart)
1415
                            ));
1416
                    }
1417
    
1418
                    $vars[$paramCount]['pass_by_reference'] = $passByReference;
1419
                    $vars[$paramCount]['variable_length']   = $variableLength;
1420
                    $vars[$paramCount]['type_hint']         = $typeHint;
1421
                    $vars[$paramCount]['nullable_type']     = $nullableType;
1422
    
1423
                    // Reset the vars, as we are about to process the next parameter.
1424
                    $defaultStart    = null;
1425
                    $paramStart      = ($i + 1);
1426
                    $passByReference = false;
1427
                    $variableLength  = false;
1428
                    $typeHint        = '';
1429
                    $nullableType    = false;
1430
    
1431
                    $paramCount++;
1432
                    break;
1433
                case T_EQUAL:
1434
                    $defaultStart = ($i + 1);
1435
                    break;
1436
            }//end switch
1437
        }//end for
1438
1439
        return $vars;
1440
1441
    }//end getMethodParameters()
1442
1443
1444
    /**
1445
     * Get the hash algorithm name from the parameter in a hash function call.
1446
     *
1447
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1448
     * @param int                  $stackPtr  The position of the T_STRING function token.
1449
     *
1450
     * @return string|false The algorithm name without quotes if this was a relevant hash
1451
     *                      function call or false if it was not.
1452
     */
1453
    public function getHashAlgorithmParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1454
    {
1455
        $tokens = $phpcsFile->getTokens();
1456
1457
        // Check for the existence of the token.
1458
        if (isset($tokens[$stackPtr]) === false) {
1459
            return false;
1460
        }
1461
1462
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1463
            return false;
1464
        }
1465
1466
        $functionName   = $tokens[$stackPtr]['content'];
1467
        $functionNameLc = strtolower($functionName);
1468
1469
        // Bow out if not one of the functions we're targetting.
1470
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
1471
            return false;
1472
        }
1473
1474
        // Get the parameter from the function call which should contain the algorithm name.
1475
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
1476
        if ($algoParam === false) {
1477
            return false;
1478
        }
1479
1480
        // Algorithm is a text string, so we need to remove the quotes.
1481
        $algo = strtolower(trim($algoParam['raw']));
1482
        $algo = $this->stripQuotes($algo);
1483
1484
        return $algo;
1485
    }
1486
1487
}//end class
1488