Completed
Push — feature/issue-367-phpcs-3.x-co... ( e185aa )
by Juliette
01:53
created

Sniff::doesFunctionCallHaveParameters()   C

Complexity

Conditions 10
Paths 9

Size

Total Lines 50
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 50
rs 5.7647
c 0
b 0
f 0
cc 10
eloc 23
nc 9
nop 2

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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

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

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

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

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

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

Loading history...
196
    {
197
        $testVersion = $this->getTestVersion();
198
        $testVersion = $testVersion[0];
199
200
        if (is_null($testVersion) === false
201
            && version_compare($testVersion, $phpVersion) <= 0
202
        ) {
203
            return true;
204
        } else {
205
            return false;
206
        }
207
    }//end supportsBelow()
208
209
210
    /**
211
     * Add a PHPCS message to the output stack as either a warning or an error.
212
     *
213
     * @param \PHP_CodeSniffer_File $phpcsFile The file the message applies to.
214
     * @param string                $message   The message.
215
     * @param int                   $stackPtr  The position of the token
216
     *                                         the message relates to.
217
     * @param bool                  $isError   Whether to report the message as an
218
     *                                         'error' or 'warning'.
219
     *                                         Defaults to true (error).
220
     * @param string                $code      The error code for the message.
221
     *                                         Defaults to 'Found'.
222
     * @param array                 $data      Optional input for the data replacements.
223
     *
224
     * @return void
225
     */
226
    public function addMessage(\PHP_CodeSniffer_File $phpcsFile, $message, $stackPtr, $isError, $code = 'Found', $data = array())
227
    {
228
        if ($isError === true) {
229
            $phpcsFile->addError($message, $stackPtr, $code, $data);
230
        } else {
231
            $phpcsFile->addWarning($message, $stackPtr, $code, $data);
232
        }
233
    }
234
235
236
    /**
237
     * Convert an arbitrary string to an alphanumeric string with underscores.
238
     *
239
     * Pre-empt issues with arbitrary strings being used as error codes in XML and PHP.
240
     *
241
     * @param string $baseString Arbitrary string.
242
     *
243
     * @return string
244
     */
245
    public function stringToErrorCode($baseString)
246
    {
247
        return preg_replace('`[^a-z0-9_]`i', '_', strtolower($baseString));
248
    }
249
250
251
    /**
252
     * Strip quotes surrounding an arbitrary string.
253
     *
254
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING / T_DOUBLE_QUOTED_STRING.
255
     *
256
     * @param string $string The raw string.
257
     *
258
     * @return string String without quotes around it.
259
     */
260
    public function stripQuotes($string)
261
    {
262
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
263
    }
264
265
266
    /**
267
     * Strip variables from an arbitrary double quoted string.
268
     *
269
     * Intended for use with the content of a T_DOUBLE_QUOTED_STRING.
270
     *
271
     * @param string $string The raw string.
272
     *
273
     * @return string String without variables in it.
274
     */
275
    public function stripVariables($string)
276
    {
277
        if (strpos($string, '$') === false) {
278
            return $string;
279
        }
280
281
        return preg_replace(self::REGEX_COMPLEX_VARS, '', $string);
282
    }
283
284
285
    /**
286
     * Make all top level array keys in an array lowercase.
287
     *
288
     * @param array $array Initial array.
289
     *
290
     * @return array Same array, but with all lowercase top level keys.
291
     */
292
    public function arrayKeysToLowercase($array)
293
    {
294
        $keys = array_keys($array);
295
        $keys = array_map('strtolower', $keys);
296
        return array_combine($keys, $array);
297
    }
298
299
300
    /**
301
     * Returns the name(s) of the interface(s) that the specified class implements.
302
     *
303
     * Returns FALSE on error or if there are no implemented interface names.
304
     *
305
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
306
     * This method also includes an improvement we use which was only introduced
307
     * in PHPCS 2.8.0, so only defer to upstream for higher versions.
308
     * Once the minimum supported PHPCS version for this sniff library goes beyond
309
     * that, this method can be removed and calls to it replaced with
310
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
311
     *
312
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
313
     * @param int                   $stackPtr  The position of the class token.
314
     *
315
     * @return array|false
316
     */
317
    public function findImplementedInterfaceNames(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
318
    {
319
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
320
            return $phpcsFile->findImplementedInterfaceNames($stackPtr);
321
        }
322
323
        $tokens = $phpcsFile->getTokens();
324
325
        // Check for the existence of the token.
326
        if (isset($tokens[$stackPtr]) === false) {
327
            return false;
328
        }
329
330 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
1 ignored issue
show
Duplication introduced by
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...
331
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
332
        ) {
333
            return false;
334
        }
335
336
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
337
            return false;
338
        }
339
340
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
341
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
342
        if ($implementsIndex === false) {
343
            return false;
344
        }
345
346
        $find = array(
347
            T_NS_SEPARATOR,
348
            T_STRING,
349
            T_WHITESPACE,
350
            T_COMMA,
351
        );
352
353
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
354
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
355
        $name = trim($name);
356
357
        if ($name === '') {
358
            return false;
359
        } else {
360
            $names = explode(',', $name);
361
            $names = array_map('trim', $names);
362
            return $names;
363
        }
364
365
    }//end findImplementedInterfaceNames()
366
367
368
    /**
369
     * Checks if a function call has parameters.
370
     *
371
     * Expects to be passed the T_STRING stack pointer for the function call.
372
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
373
     *
374
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer, it
375
     * will detect whether the array has values or is empty.
376
     *
377
     * @link https://github.com/wimg/PHPCompatibility/issues/120
378
     * @link https://github.com/wimg/PHPCompatibility/issues/152
379
     *
380
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
381
     * @param int                   $stackPtr  The position of the function call token.
382
     *
383
     * @return bool
384
     */
385
    public function doesFunctionCallHaveParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
386
    {
387
        $tokens = $phpcsFile->getTokens();
388
389
        // Check for the existence of the token.
390
        if (isset($tokens[$stackPtr]) === false) {
391
            return false;
392
        }
393
394
        // Is this one of the tokens this function handles ?
395
        if (in_array($tokens[$stackPtr]['code'], array(T_STRING, T_ARRAY, T_OPEN_SHORT_ARRAY), true) === false) {
396
            return false;
397
        }
398
399
        $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
400
401
        // Deal with short array syntax.
402
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
403
            if (isset($tokens[$stackPtr]['bracket_closer']) === false) {
404
                return false;
405
            }
406
407
            if ($nextNonEmpty === $tokens[$stackPtr]['bracket_closer']) {
408
                // No parameters.
409
                return false;
410
            } else {
411
                return true;
412
            }
413
        }
414
415
        // Deal with function calls & long arrays.
416
        // Next non-empty token should be the open parenthesis.
417
        if ($nextNonEmpty === false && $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS) {
418
            return false;
419
        }
420
421
        if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
422
            return false;
423
        }
424
425
        $closeParenthesis = $tokens[$nextNonEmpty]['parenthesis_closer'];
426
        $nextNextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextNonEmpty + 1, $closeParenthesis + 1, true);
427
428
        if ($nextNextNonEmpty === $closeParenthesis) {
429
            // No parameters.
430
            return false;
431
        }
432
433
        return true;
434
    }
435
436
437
    /**
438
     * Count the number of parameters a function call has been passed.
439
     *
440
     * Expects to be passed the T_STRING stack pointer for the function call.
441
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
442
     *
443
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
444
     * it will return the number of values in the array.
445
     *
446
     * @link https://github.com/wimg/PHPCompatibility/issues/111
447
     * @link https://github.com/wimg/PHPCompatibility/issues/114
448
     * @link https://github.com/wimg/PHPCompatibility/issues/151
449
     *
450
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
451
     * @param int                   $stackPtr  The position of the function call token.
452
     *
453
     * @return int
454
     */
455
    public function getFunctionCallParameterCount(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
456
    {
457
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
458
            return 0;
459
        }
460
461
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
462
    }
463
464
465
    /**
466
     * Get information on all parameters passed to a function call.
467
     *
468
     * Expects to be passed the T_STRING stack pointer for the function call.
469
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
470
     *
471
     * Will return an multi-dimentional array with the start token pointer, end token
472
     * pointer and raw parameter value for all parameters. Index will be 1-based.
473
     * If no parameters are found, will return an empty array.
474
     *
475
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
476
     * it will tokenize the values / key/value pairs contained in the array call.
477
     *
478
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
479
     * @param int                   $stackPtr  The position of the function call token.
480
     *
481
     * @return array
482
     */
483
    public function getFunctionCallParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
484
    {
485
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
486
            return array();
487
        }
488
489
        // Ok, we know we have a T_STRING, T_ARRAY or T_OPEN_SHORT_ARRAY with parameters
490
        // and valid open & close brackets/parenthesis.
491
        $tokens = $phpcsFile->getTokens();
492
493
        // Mark the beginning and end tokens.
494
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
495
            $opener = $stackPtr;
496
            $closer = $tokens[$stackPtr]['bracket_closer'];
497
498
            $nestedParenthesisCount = 0;
499
500
        } else {
501
            $opener = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
502
            $closer = $tokens[$opener]['parenthesis_closer'];
503
504
            $nestedParenthesisCount = 1;
505
        }
506
507
        // Which nesting level is the one we are interested in ?
508 View Code Duplication
        if (isset($tokens[$opener]['nested_parenthesis'])) {
1 ignored issue
show
Duplication introduced by
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...
509
            $nestedParenthesisCount += count($tokens[$opener]['nested_parenthesis']);
510
        }
511
512
        $parameters = array();
513
        $nextComma  = $opener;
514
        $paramStart = $opener + 1;
515
        $cnt        = 1;
516
        while (($nextComma = $phpcsFile->findNext(array(T_COMMA, $tokens[$closer]['code'], T_OPEN_SHORT_ARRAY), $nextComma + 1, $closer + 1)) !== false) {
517
            // Ignore anything within short array definition brackets.
518
            if ($tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
519
                && (isset($tokens[$nextComma]['bracket_opener'])
520
                    && $tokens[$nextComma]['bracket_opener'] === $nextComma)
521
                && isset($tokens[$nextComma]['bracket_closer'])
522
            ) {
523
                // Skip forward to the end of the short array definition.
524
                $nextComma = $tokens[$nextComma]['bracket_closer'];
525
                continue;
526
            }
527
528
            // Ignore comma's at a lower nesting level.
529
            if ($tokens[$nextComma]['type'] === 'T_COMMA'
530
                && isset($tokens[$nextComma]['nested_parenthesis'])
531
                && count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
532
            ) {
533
                continue;
534
            }
535
536
            // Ignore closing parenthesis/bracket if not 'ours'.
537
            if ($tokens[$nextComma]['type'] === $tokens[$closer]['type'] && $nextComma !== $closer) {
538
                continue;
539
            }
540
541
            // Ok, we've reached the end of the parameter.
542
            $parameters[$cnt]['start'] = $paramStart;
543
            $parameters[$cnt]['end']   = $nextComma - 1;
544
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
545
546
            // Check if there are more tokens before the closing parenthesis.
547
            // Prevents code like the following from setting a third parameter:
548
            // functionCall( $param1, $param2, );
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
549
            $hasNextParam = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closer, true, null, true);
550
            if ($hasNextParam === false) {
551
                break;
552
            }
553
554
            // Prepare for the next parameter.
555
            $paramStart = $nextComma + 1;
556
            $cnt++;
557
        }
558
559
        return $parameters;
560
    }
561
562
563
    /**
564
     * Get information on a specific parameter passed to a function call.
565
     *
566
     * Expects to be passed the T_STRING stack pointer for the function call.
567
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
568
     *
569
     * Will return a array with the start token pointer, end token pointer and the raw value
570
     * of the parameter at a specific offset.
571
     * If the specified parameter is not found, will return false.
572
     *
573
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
574
     * @param int                   $stackPtr    The position of the function call token.
575
     * @param int                   $paramOffset The 1-based index position of the parameter to retrieve.
576
     *
577
     * @return array|false
578
     */
579
    public function getFunctionCallParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
580
    {
581
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
582
583
        if (isset($parameters[$paramOffset]) === false) {
584
            return false;
585
        } else {
586
            return $parameters[$paramOffset];
587
        }
588
    }
589
590
591
    /**
592
     * Verify whether a token is within a scoped condition.
593
     *
594
     * If the optional $validScopes parameter has been passed, the function
595
     * will check that the token has at least one condition which is of a
596
     * type defined in $validScopes.
597
     *
598
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
599
     * @param int                   $stackPtr    The position of the token.
600
     * @param array|int             $validScopes Optional. Array of valid scopes
601
     *                                           or int value of a valid scope.
602
     *                                           Pass the T_.. constant(s) for the
603
     *                                           desired scope to this parameter.
604
     *
605
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
606
     *              If the $scopeTypes are set: True if *one* of the conditions is a
607
     *              valid scope, false otherwise.
608
     */
609
    public function tokenHasScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
610
    {
611
        $tokens = $phpcsFile->getTokens();
612
613
        // Check for the existence of the token.
614
        if (isset($tokens[$stackPtr]) === false) {
615
            return false;
616
        }
617
618
        // No conditions = no scope.
619
        if (empty($tokens[$stackPtr]['conditions'])) {
620
            return false;
621
        }
622
623
        // Ok, there are conditions, do we have to check for specific ones ?
624
        if (isset($validScopes) === false) {
625
            return true;
626
        }
627
628
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
629
    }
630
631
632
    /**
633
     * Verify whether a token is within a class scope.
634
     *
635
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
636
     * @param int                   $stackPtr  The position of the token.
637
     * @param bool                  $strict    Whether to strictly check for the T_CLASS
638
     *                                         scope or also accept interfaces and traits
639
     *                                         as scope.
640
     *
641
     * @return bool True if within class scope, false otherwise.
642
     */
643
    public function inClassScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
644
    {
645
        $validScopes = array(T_CLASS);
646
        if (defined('T_ANON_CLASS') === true) {
647
            $validScopes[] = T_ANON_CLASS;
648
        }
649
650
        if ($strict === false) {
651
            $validScopes[] = T_INTERFACE;
652
            $validScopes[] = T_TRAIT;
653
        }
654
655
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
656
    }
657
658
659
    /**
660
     * Verify whether a token is within a scoped use statement.
661
     *
662
     * PHPCS cross-version compatibility method.
663
     *
664
     * In PHPCS 1.x no conditions are set for a scoped use statement.
665
     * This method works around that limitation.
666
     *
667
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
668
     * @param int                   $stackPtr  The position of the token.
669
     *
670
     * @return bool True if within use scope, false otherwise.
671
     */
672
    public function inUseScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
673
    {
674
        static $isLowPHPCS, $ignoreTokens;
675
676
        if (isset($isLowPHPCS) === false) {
677
            $isLowPHPCS = version_compare(PHPCSHelper::getVersion(), '2.3.0', '<');
678
        }
679
        if (isset($ignoreTokens) === false) {
680
            $ignoreTokens              = \PHP_CodeSniffer_Tokens::$emptyTokens;
681
            $ignoreTokens[T_STRING]    = T_STRING;
682
            $ignoreTokens[T_AS]        = T_AS;
683
            $ignoreTokens[T_PUBLIC]    = T_PUBLIC;
684
            $ignoreTokens[T_PROTECTED] = T_PROTECTED;
685
            $ignoreTokens[T_PRIVATE]   = T_PRIVATE;
686
        }
687
688
        // PHPCS 2.0.
689
        if ($isLowPHPCS === false) {
690
            return $phpcsFile->hasCondition($stackPtr, T_USE);
691
        } else {
692
            // PHPCS 1.x.
693
            $tokens         = $phpcsFile->getTokens();
694
            $maybeCurlyOpen = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
695
            if ($tokens[$maybeCurlyOpen]['code'] === T_OPEN_CURLY_BRACKET) {
696
                $maybeUseStatement = $phpcsFile->findPrevious($ignoreTokens, ($maybeCurlyOpen - 1), null, true);
697
                if ($tokens[$maybeUseStatement]['code'] === T_USE) {
698
                    return true;
699
                }
700
            }
701
            return false;
702
        }
703
    }
704
705
706
    /**
707
     * Returns the fully qualified class name for a new class instantiation.
708
     *
709
     * Returns an empty string if the class name could not be reliably inferred.
710
     *
711
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
712
     * @param int                   $stackPtr  The position of a T_NEW token.
713
     *
714
     * @return string
715
     */
716
    public function getFQClassNameFromNewToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
717
    {
718
        $tokens = $phpcsFile->getTokens();
719
720
        // Check for the existence of the token.
721
        if (isset($tokens[$stackPtr]) === false) {
722
            return '';
723
        }
724
725
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
726
            return '';
727
        }
728
729
        $start = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
730
        if ($start === false) {
731
            return '';
732
        }
733
734
        // Bow out if the next token is a variable as we don't know where it was defined.
735
        if ($tokens[$start]['code'] === T_VARIABLE) {
736
            return '';
737
        }
738
739
        // Bow out if the next token is the class keyword.
740
        if ($tokens[$start]['type'] === 'T_ANON_CLASS' || $tokens[$start]['code'] === T_CLASS) {
741
            return '';
742
        }
743
744
        $find = array(
745
            T_NS_SEPARATOR,
746
            T_STRING,
747
            T_NAMESPACE,
748
            T_WHITESPACE,
749
        );
750
751
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
752
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
753
        $className = trim($className);
754
755
        return $this->getFQName($phpcsFile, $stackPtr, $className);
756
    }
757
758
759
    /**
760
     * Returns the fully qualified name of the class that the specified class extends.
761
     *
762
     * Returns an empty string if the class does not extend another class or if
763
     * the class name could not be reliably inferred.
764
     *
765
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
766
     * @param int                   $stackPtr  The position of a T_CLASS token.
767
     *
768
     * @return string
769
     */
770
    public function getFQExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
771
    {
772
        $tokens = $phpcsFile->getTokens();
773
774
        // Check for the existence of the token.
775
        if (isset($tokens[$stackPtr]) === false) {
776
            return '';
777
        }
778
779 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS') {
1 ignored issue
show
Duplication introduced by
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...
780
            return '';
781
        }
782
783
        $extends = $this->findExtendedClassName($phpcsFile, $stackPtr);
784
        if (empty($extends) || is_string($extends) === false) {
785
            return '';
786
        }
787
788
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
789
    }
790
791
792
    /**
793
     * Returns the class name for the static usage of a class.
794
     * This can be a call to a method, the use of a property or constant.
795
     *
796
     * Returns an empty string if the class name could not be reliably inferred.
797
     *
798
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
799
     * @param int                   $stackPtr  The position of a T_NEW token.
800
     *
801
     * @return string
802
     */
803
    public function getFQClassNameFromDoubleColonToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
804
    {
805
        $tokens = $phpcsFile->getTokens();
806
807
        // Check for the existence of the token.
808
        if (isset($tokens[$stackPtr]) === false) {
809
            return '';
810
        }
811
812
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
813
            return '';
814
        }
815
816
        // Nothing to do if previous token is a variable as we don't know where it was defined.
817
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
818
            return '';
819
        }
820
821
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
822
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
823
            return '';
824
        }
825
826
        // Get the classname from the class declaration if self is used.
827
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
828
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
829
            if ($classDeclarationPtr === false) {
830
                return '';
831
            }
832
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
833
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
834
        }
835
836
        $find = array(
837
            T_NS_SEPARATOR,
838
            T_STRING,
839
            T_NAMESPACE,
840
            T_WHITESPACE,
841
        );
842
843
        $start = $phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true);
844
        if ($start === false || isset($tokens[($start + 1)]) === false) {
845
            return '';
846
        }
847
848
        $start     = ($start + 1);
849
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
850
        $className = trim($className);
851
852
        return $this->getFQName($phpcsFile, $stackPtr, $className);
853
    }
854
855
856
    /**
857
     * Get the Fully Qualified name for a class/function/constant etc.
858
     *
859
     * Checks if a class/function/constant name is already fully qualified and
860
     * if not, enrich it with the relevant namespace information.
861
     *
862
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
863
     * @param int                   $stackPtr  The position of the token.
864
     * @param string                $name      The class / function / constant name.
865
     *
866
     * @return string
867
     */
868
    public function getFQName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
869
    {
870
        if (strpos($name, '\\') === 0) {
871
            // Already fully qualified.
872
            return $name;
873
        }
874
875
        // Remove the namespace keyword if used.
876
        if (strpos($name, 'namespace\\') === 0) {
877
            $name = substr($name, 10);
878
        }
879
880
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
881
882
        if ($namespace === '') {
883
            return '\\' . $name;
884
        } else {
885
            return '\\' . $namespace . '\\' . $name;
886
        }
887
    }
888
889
890
    /**
891
     * Is the class/function/constant name namespaced or global ?
892
     *
893
     * @param string $FQName Fully Qualified name of a class, function etc.
894
     *                       I.e. should always start with a `\`.
895
     *
896
     * @return bool True if namespaced, false if global.
897
     */
898
    public function isNamespaced($FQName)
899
    {
900
        if (strpos($FQName, '\\') !== 0) {
901
            throw new \PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
902
        }
903
904
        return (strpos(substr($FQName, 1), '\\') !== false);
905
    }
906
907
908
    /**
909
     * Determine the namespace name an arbitrary token lives in.
910
     *
911
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
912
     * @param int                   $stackPtr  The token position for which to determine the namespace.
913
     *
914
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
915
     */
916
    public function determineNamespace(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
917
    {
918
        $tokens = $phpcsFile->getTokens();
919
920
        // Check for the existence of the token.
921
        if (isset($tokens[$stackPtr]) === false) {
922
            return '';
923
        }
924
925
        // Check for scoped namespace {}.
926
        if (empty($tokens[$stackPtr]['conditions']) === false) {
927
            $namespacePtr = $phpcsFile->getCondition($stackPtr, T_NAMESPACE);
928
            if ($namespacePtr !== false) {
929
                $namespace = $this->getDeclaredNamespaceName($phpcsFile, $namespacePtr);
930
                if ($namespace !== false) {
931
                    return $namespace;
932
                }
933
934
                // We are in a scoped namespace, but couldn't determine the name. Searching for a global namespace is futile.
935
                return '';
936
            }
937
        }
938
939
        /*
940
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
941
         * Keeping in mind that:
942
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
943
         * - the namespace keyword can also be used as part of a function/method call and such.
944
         * - that a non-named namespace resolves to the global namespace.
945
         */
946
        $previousNSToken = $stackPtr;
947
        $namespace       = false;
948
        do {
949
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, ($previousNSToken - 1));
950
951
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
952
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] === $previousNSToken) {
953
                break;
954
            }
955
956
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
957
958
        } while ($namespace === false && $previousNSToken !== false);
959
960
        // If we still haven't got a namespace, return an empty string.
961
        if ($namespace === false) {
962
            return '';
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
Duplication introduced by
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
Duplication introduced by
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
Duplication introduced by
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
Duplication introduced by
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
Duplication introduced by
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(PHPCSHelper::getVersion(), '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
Duplication introduced by
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
Duplication introduced by
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
Duplication introduced by
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]['type']) {
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
Duplication introduced by
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
Duplication introduced by
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
     * Returns the name of the class that the specified class extends.
1446
     *
1447
     * Returns FALSE on error or if there is no extended class name.
1448
     *
1449
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1450
     * class, but with some improvements which have been introduced in
1451
     * PHPCS 2.8.0.
1452
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/commit/0011d448119d4c568e3ac1f825ae78815bf2cc34}.
1453
     *
1454
     * Once the minimum supported PHPCS version for this standard goes beyond
1455
     * that, this method can be removed and calls to it replaced with
1456
     * `$phpcsFile->findExtendedClassName($stackPtr)` calls.
1457
     *
1458
     * Last synced with PHPCS version: PHPCS 2.9.0 at commit b940fb7dca8c2a37f0514161b495363e5b36d879}}
1459
     *
1460
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1461
     * @param int                   $stackPtr  The position in the stack of the
1462
     *                                         class token.
1463
     *
1464
     * @return string|false
1465
     */
1466
    public function findExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1467
    {
1468
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
1469
            return $phpcsFile->findExtendedClassName($stackPtr);
1470
        }
1471
1472
        $tokens = $phpcsFile->getTokens();
1473
1474
        // Check for the existence of the token.
1475
        if (isset($tokens[$stackPtr]) === false) {
1476
            return false;
1477
        }
1478
1479 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
1 ignored issue
show
Duplication introduced by
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...
1480
            && $tokens[$stackPtr]['code'] !== T_ANON_CLASS
1481
        ) {
1482
            return false;
1483
        }
1484
1485
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
1486
            return false;
1487
        }
1488
1489
        $classCloserIndex = $tokens[$stackPtr]['scope_closer'];
1490
        $extendsIndex     = $phpcsFile->findNext(T_EXTENDS, $stackPtr, $classCloserIndex);
1491
        if (false === $extendsIndex) {
1492
            return false;
1493
        }
1494
1495
        $find = array(
1496
                 T_NS_SEPARATOR,
1497
                 T_STRING,
1498
                 T_WHITESPACE,
1499
                );
1500
1501
        $end  = $phpcsFile->findNext($find, ($extendsIndex + 1), $classCloserIndex, true);
1502
        $name = $phpcsFile->getTokensAsString(($extendsIndex + 1), ($end - $extendsIndex - 1));
1503
        $name = trim($name);
1504
1505
        if ($name === '') {
1506
            return false;
1507
        }
1508
1509
        return $name;
1510
1511
    }//end findExtendedClassName()
1512
1513
1514
    /**
1515
     * Get the hash algorithm name from the parameter in a hash function call.
1516
     *
1517
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1518
     * @param int                   $stackPtr  The position of the T_STRING function token.
1519
     *
1520
     * @return string|false The algorithm name without quotes if this was a relevant hash
1521
     *                      function call or false if it was not.
1522
     */
1523
    public function getHashAlgorithmParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1524
    {
1525
        $tokens = $phpcsFile->getTokens();
1526
1527
        // Check for the existence of the token.
1528
        if (isset($tokens[$stackPtr]) === false) {
1529
            return false;
1530
        }
1531
1532
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1533
            return false;
1534
        }
1535
1536
        $functionName   = $tokens[$stackPtr]['content'];
1537
        $functionNameLc = strtolower($functionName);
1538
1539
        // Bow out if not one of the functions we're targetting.
1540
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
1541
            return false;
1542
        }
1543
1544
        // Get the parameter from the function call which should contain the algorithm name.
1545
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
1546
        if ($algoParam === false) {
1547
            return false;
1548
        }
1549
1550
        // Algorithm is a text string, so we need to remove the quotes.
1551
        $algo = strtolower(trim($algoParam['raw']));
1552
        $algo = $this->stripQuotes($algo);
1553
1554
        return $algo;
1555
    }
1556
1557
}//end class
1558