Completed
Push — feature/294-446-fix-bitshift-b... ( 89585a...8f0fdf )
by Juliette
02:36
created

Sniff::findEndOfStatement()   C

Complexity

Conditions 22
Paths 23

Size

Total Lines 71
Code Lines 44

Duplication

Lines 5
Ratio 7.04 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 5
loc 71
rs 5.4673
cc 22
eloc 44
nc 23
nop 3

How to fix   Long Method    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
        $default     = array(null, null);
109
        $testVersion = trim(PHPCSHelper::getConfigData('testVersion'));
110
111
        if (empty($testVersion) === false && isset($arrTestVersions[$testVersion]) === false) {
112
113
            $arrTestVersions[$testVersion] = $default;
114
115
            if (preg_match('`^\d+\.\d+$`', $testVersion)) {
116
                $arrTestVersions[$testVersion] = array($testVersion, $testVersion);
117
                return $arrTestVersions[$testVersion];
118
            }
119
120
            if (preg_match('`^(\d+\.\d+)?\s*-\s*(\d+\.\d+)?$`', $testVersion, $matches)) {
121
                if (empty($matches[1]) === false || empty($matches[2]) === false) {
122
                    // If no lower-limit is set, we set the min version to 4.0.
123
                    // Whilst development focuses on PHP 5 and above, we also accept
124
                    // sniffs for PHP 4, so we include that as the minimum.
125
                    // (It makes no sense to support PHP 3 as this was effectively a
126
                    // different language).
127
                    $min = empty($matches[1]) ? '4.0' : $matches[1];
128
129
                    // If no upper-limit is set, we set the max version to 99.9.
130
                    $max = empty($matches[2]) ? '99.9' : $matches[2];
131
132
                    if (version_compare($min, $max, '>')) {
133
                        trigger_error(
134
                            "Invalid range in testVersion setting: '" . $testVersion . "'",
135
                            E_USER_WARNING
136
                        );
137
                        return $default;
138
                    }
139
                    else {
140
                        $arrTestVersions[$testVersion] = array($min, $max);
141
                        return $arrTestVersions[$testVersion];
142
                    }
143
                }
144
            }
145
146
            trigger_error(
147
                "Invalid testVersion setting: '" . $testVersion . "'",
148
                E_USER_WARNING
149
            );
150
            return $default;
151
        }
152
153
        if (isset($arrTestVersions[$testVersion])) {
154
            return $arrTestVersions[$testVersion];
155
        }
156
157
        return $default;
158
    }
159
160
161
    /**
162
     * Check whether a specific PHP version is equal to or higher than the maximum
163
     * supported PHP version as provided by the user in `testVersion`.
164
     *
165
     * Should be used when sniffing for *old* PHP features (deprecated/removed).
166
     *
167
     * @param string $phpVersion A PHP version number in 'major.minor' format.
168
     *
169
     * @return bool True if testVersion has not been provided or if the PHP version
170
     *              is equal to or higher than the highest supported PHP version
171
     *              in testVersion. False otherwise.
172
     */
173 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...
174
    {
175
        $testVersion = $this->getTestVersion();
176
        $testVersion = $testVersion[1];
177
178
        if (is_null($testVersion)
179
            || version_compare($testVersion, $phpVersion) >= 0
180
        ) {
181
            return true;
182
        } else {
183
            return false;
184
        }
185
    }//end supportsAbove()
186
187
188
    /**
189
     * Check whether a specific PHP version is equal to or lower than the minimum
190
     * supported PHP version as provided by the user in `testVersion`.
191
     *
192
     * Should be used when sniffing for *new* PHP features.
193
     *
194
     * @param string $phpVersion A PHP version number in 'major.minor' format.
195
     *
196
     * @return bool True if the PHP version is equal to or lower than the lowest
197
     *              supported PHP version in testVersion.
198
     *              False otherwise or if no testVersion is provided.
199
     */
200 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...
201
    {
202
        $testVersion = $this->getTestVersion();
203
        $testVersion = $testVersion[0];
204
205
        if (is_null($testVersion) === false
206
            && version_compare($testVersion, $phpVersion) <= 0
207
        ) {
208
            return true;
209
        } else {
210
            return false;
211
        }
212
    }//end supportsBelow()
213
214
215
    /**
216
     * Add a PHPCS message to the output stack as either a warning or an error.
217
     *
218
     * @param \PHP_CodeSniffer_File $phpcsFile The file the message applies to.
219
     * @param string                $message   The message.
220
     * @param int                   $stackPtr  The position of the token
221
     *                                         the message relates to.
222
     * @param bool                  $isError   Whether to report the message as an
223
     *                                         'error' or 'warning'.
224
     *                                         Defaults to true (error).
225
     * @param string                $code      The error code for the message.
226
     *                                         Defaults to 'Found'.
227
     * @param array                 $data      Optional input for the data replacements.
228
     *
229
     * @return void
230
     */
231
    public function addMessage(\PHP_CodeSniffer_File $phpcsFile, $message, $stackPtr, $isError, $code = 'Found', $data = array())
232
    {
233
        if ($isError === true) {
234
            $phpcsFile->addError($message, $stackPtr, $code, $data);
235
        } else {
236
            $phpcsFile->addWarning($message, $stackPtr, $code, $data);
237
        }
238
    }
239
240
241
    /**
242
     * Convert an arbitrary string to an alphanumeric string with underscores.
243
     *
244
     * Pre-empt issues with arbitrary strings being used as error codes in XML and PHP.
245
     *
246
     * @param string $baseString Arbitrary string.
247
     *
248
     * @return string
249
     */
250
    public function stringToErrorCode($baseString)
251
    {
252
        return preg_replace('`[^a-z0-9_]`i', '_', strtolower($baseString));
253
    }
254
255
256
    /**
257
     * Strip quotes surrounding an arbitrary string.
258
     *
259
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING / T_DOUBLE_QUOTED_STRING.
260
     *
261
     * @param string $string The raw string.
262
     *
263
     * @return string String without quotes around it.
264
     */
265
    public function stripQuotes($string)
266
    {
267
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
268
    }
269
270
271
    /**
272
     * Strip variables from an arbitrary double quoted string.
273
     *
274
     * Intended for use with the content of a T_DOUBLE_QUOTED_STRING.
275
     *
276
     * @param string $string The raw string.
277
     *
278
     * @return string String without variables in it.
279
     */
280
    public function stripVariables($string)
281
    {
282
        if (strpos($string, '$') === false) {
283
            return $string;
284
        }
285
286
        return preg_replace(self::REGEX_COMPLEX_VARS, '', $string);
287
    }
288
289
290
    /**
291
     * Make all top level array keys in an array lowercase.
292
     *
293
     * @param array $array Initial array.
294
     *
295
     * @return array Same array, but with all lowercase top level keys.
296
     */
297
    public function arrayKeysToLowercase($array)
298
    {
299
        $keys = array_keys($array);
300
        $keys = array_map('strtolower', $keys);
301
        return array_combine($keys, $array);
302
    }
303
304
305
    /**
306
     * Returns the name(s) of the interface(s) that the specified class implements.
307
     *
308
     * Returns FALSE on error or if there are no implemented interface names.
309
     *
310
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
311
     * This method also includes an improvement we use which was only introduced
312
     * in PHPCS 2.8.0, so only defer to upstream for higher versions.
313
     * Once the minimum supported PHPCS version for this sniff library goes beyond
314
     * that, this method can be removed and calls to it replaced with
315
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
316
     *
317
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
318
     * @param int                   $stackPtr  The position of the class token.
319
     *
320
     * @return array|false
321
     */
322
    public function findImplementedInterfaceNames(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
323
    {
324
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
325
            return $phpcsFile->findImplementedInterfaceNames($stackPtr);
326
        }
327
328
        $tokens = $phpcsFile->getTokens();
329
330
        // Check for the existence of the token.
331
        if (isset($tokens[$stackPtr]) === false) {
332
            return false;
333
        }
334
335
        if ($tokens[$stackPtr]['code'] !== T_CLASS
336
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
337
        ) {
338
            return false;
339
        }
340
341
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
342
            return false;
343
        }
344
345
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
346
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
347
        if ($implementsIndex === false) {
348
            return false;
349
        }
350
351
        $find = array(
352
            T_NS_SEPARATOR,
353
            T_STRING,
354
            T_WHITESPACE,
355
            T_COMMA,
356
        );
357
358
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
359
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
360
        $name = trim($name);
361
362
        if ($name === '') {
363
            return false;
364
        } else {
365
            $names = explode(',', $name);
366
            $names = array_map('trim', $names);
367
            return $names;
368
        }
369
370
    }//end findImplementedInterfaceNames()
371
372
373
    /**
374
     * Checks if a function call has parameters.
375
     *
376
     * Expects to be passed the T_STRING stack pointer for the function call.
377
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
378
     *
379
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer, it
380
     * will detect whether the array has values or is empty.
381
     *
382
     * @link https://github.com/wimg/PHPCompatibility/issues/120
383
     * @link https://github.com/wimg/PHPCompatibility/issues/152
384
     *
385
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
386
     * @param int                   $stackPtr  The position of the function call token.
387
     *
388
     * @return bool
389
     */
390
    public function doesFunctionCallHaveParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
391
    {
392
        $tokens = $phpcsFile->getTokens();
393
394
        // Check for the existence of the token.
395
        if (isset($tokens[$stackPtr]) === false) {
396
            return false;
397
        }
398
399
        // Is this one of the tokens this function handles ?
400
        if (in_array($tokens[$stackPtr]['code'], array(T_STRING, T_ARRAY, T_OPEN_SHORT_ARRAY), true) === false) {
401
            return false;
402
        }
403
404
        $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
405
406
        // Deal with short array syntax.
407
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
408
            if (isset($tokens[$stackPtr]['bracket_closer']) === false) {
409
                return false;
410
            }
411
412
            if ($nextNonEmpty === $tokens[$stackPtr]['bracket_closer']) {
413
                // No parameters.
414
                return false;
415
            } else {
416
                return true;
417
            }
418
        }
419
420
        // Deal with function calls & long arrays.
421
        // Next non-empty token should be the open parenthesis.
422
        if ($nextNonEmpty === false && $tokens[$nextNonEmpty]['code'] !== T_OPEN_PARENTHESIS) {
423
            return false;
424
        }
425
426
        if (isset($tokens[$nextNonEmpty]['parenthesis_closer']) === false) {
427
            return false;
428
        }
429
430
        $closeParenthesis = $tokens[$nextNonEmpty]['parenthesis_closer'];
431
        $nextNextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextNonEmpty + 1, $closeParenthesis + 1, true);
432
433
        if ($nextNextNonEmpty === $closeParenthesis) {
434
            // No parameters.
435
            return false;
436
        }
437
438
        return true;
439
    }
440
441
442
    /**
443
     * Count the number of parameters a function call has been passed.
444
     *
445
     * Expects to be passed the T_STRING stack pointer for the function call.
446
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
447
     *
448
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
449
     * it will return the number of values in the array.
450
     *
451
     * @link https://github.com/wimg/PHPCompatibility/issues/111
452
     * @link https://github.com/wimg/PHPCompatibility/issues/114
453
     * @link https://github.com/wimg/PHPCompatibility/issues/151
454
     *
455
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
456
     * @param int                   $stackPtr  The position of the function call token.
457
     *
458
     * @return int
459
     */
460
    public function getFunctionCallParameterCount(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
461
    {
462
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
463
            return 0;
464
        }
465
466
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
467
    }
468
469
470
    /**
471
     * Get information on all parameters passed to a function call.
472
     *
473
     * Expects to be passed the T_STRING stack pointer for the function call.
474
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
475
     *
476
     * Will return an multi-dimentional array with the start token pointer, end token
477
     * pointer and raw parameter value for all parameters. Index will be 1-based.
478
     * If no parameters are found, will return an empty array.
479
     *
480
     * Extra feature: If passed an T_ARRAY or T_OPEN_SHORT_ARRAY stack pointer,
481
     * it will tokenize the values / key/value pairs contained in the array call.
482
     *
483
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
484
     * @param int                   $stackPtr  The position of the function call token.
485
     *
486
     * @return array
487
     */
488
    public function getFunctionCallParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
489
    {
490
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
491
            return array();
492
        }
493
494
        // Ok, we know we have a T_STRING, T_ARRAY or T_OPEN_SHORT_ARRAY with parameters
495
        // and valid open & close brackets/parenthesis.
496
        $tokens = $phpcsFile->getTokens();
497
498
        // Mark the beginning and end tokens.
499
        if ($tokens[$stackPtr]['code'] === T_OPEN_SHORT_ARRAY) {
500
            $opener = $stackPtr;
501
            $closer = $tokens[$stackPtr]['bracket_closer'];
502
503
            $nestedParenthesisCount = 0;
504
505
        } else {
506
            $opener = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
507
            $closer = $tokens[$opener]['parenthesis_closer'];
508
509
            $nestedParenthesisCount = 1;
510
        }
511
512
        // Which nesting level is the one we are interested in ?
513 View Code Duplication
        if (isset($tokens[$opener]['nested_parenthesis'])) {
514
            $nestedParenthesisCount += count($tokens[$opener]['nested_parenthesis']);
515
        }
516
517
        $parameters = array();
518
        $nextComma  = $opener;
519
        $paramStart = $opener + 1;
520
        $cnt        = 1;
521
        while (($nextComma = $phpcsFile->findNext(array(T_COMMA, $tokens[$closer]['code'], T_OPEN_SHORT_ARRAY), $nextComma + 1, $closer + 1)) !== false) {
522
            // Ignore anything within short array definition brackets.
523
            if ($tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
524
                && (isset($tokens[$nextComma]['bracket_opener'])
525
                    && $tokens[$nextComma]['bracket_opener'] === $nextComma)
526
                && isset($tokens[$nextComma]['bracket_closer'])
527
            ) {
528
                // Skip forward to the end of the short array definition.
529
                $nextComma = $tokens[$nextComma]['bracket_closer'];
530
                continue;
531
            }
532
533
            // Ignore comma's at a lower nesting level.
534
            if ($tokens[$nextComma]['type'] === 'T_COMMA'
535
                && isset($tokens[$nextComma]['nested_parenthesis'])
536
                && count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
537
            ) {
538
                continue;
539
            }
540
541
            // Ignore closing parenthesis/bracket if not 'ours'.
542
            if ($tokens[$nextComma]['type'] === $tokens[$closer]['type'] && $nextComma !== $closer) {
543
                continue;
544
            }
545
546
            // Ok, we've reached the end of the parameter.
547
            $parameters[$cnt]['start'] = $paramStart;
548
            $parameters[$cnt]['end']   = $nextComma - 1;
549
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
550
551
            // Check if there are more tokens before the closing parenthesis.
552
            // Prevents code like the following from setting a third parameter:
553
            // 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...
554
            $hasNextParam = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closer, true, null, true);
555
            if ($hasNextParam === false) {
556
                break;
557
            }
558
559
            // Prepare for the next parameter.
560
            $paramStart = $nextComma + 1;
561
            $cnt++;
562
        }
563
564
        return $parameters;
565
    }
566
567
568
    /**
569
     * Get information on a specific parameter passed to a function call.
570
     *
571
     * Expects to be passed the T_STRING stack pointer for the function call.
572
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
573
     *
574
     * Will return a array with the start token pointer, end token pointer and the raw value
575
     * of the parameter at a specific offset.
576
     * If the specified parameter is not found, will return false.
577
     *
578
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
579
     * @param int                   $stackPtr    The position of the function call token.
580
     * @param int                   $paramOffset The 1-based index position of the parameter to retrieve.
581
     *
582
     * @return array|false
583
     */
584
    public function getFunctionCallParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
585
    {
586
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
587
588
        if (isset($parameters[$paramOffset]) === false) {
589
            return false;
590
        } else {
591
            return $parameters[$paramOffset];
592
        }
593
    }
594
595
596
    /**
597
     * Verify whether a token is within a scoped condition.
598
     *
599
     * If the optional $validScopes parameter has been passed, the function
600
     * will check that the token has at least one condition which is of a
601
     * type defined in $validScopes.
602
     *
603
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
604
     * @param int                   $stackPtr    The position of the token.
605
     * @param array|int             $validScopes Optional. Array of valid scopes
606
     *                                           or int value of a valid scope.
607
     *                                           Pass the T_.. constant(s) for the
608
     *                                           desired scope to this parameter.
609
     *
610
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
611
     *              If the $scopeTypes are set: True if *one* of the conditions is a
612
     *              valid scope, false otherwise.
613
     */
614
    public function tokenHasScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
615
    {
616
        $tokens = $phpcsFile->getTokens();
617
618
        // Check for the existence of the token.
619
        if (isset($tokens[$stackPtr]) === false) {
620
            return false;
621
        }
622
623
        // No conditions = no scope.
624
        if (empty($tokens[$stackPtr]['conditions'])) {
625
            return false;
626
        }
627
628
        // Ok, there are conditions, do we have to check for specific ones ?
629
        if (isset($validScopes) === false) {
630
            return true;
631
        }
632
633
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
634
    }
635
636
637
    /**
638
     * Verify whether a token is within a class scope.
639
     *
640
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
641
     * @param int                   $stackPtr  The position of the token.
642
     * @param bool                  $strict    Whether to strictly check for the T_CLASS
643
     *                                         scope or also accept interfaces and traits
644
     *                                         as scope.
645
     *
646
     * @return bool True if within class scope, false otherwise.
647
     */
648
    public function inClassScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
649
    {
650
        $validScopes = array(T_CLASS);
651
        if (defined('T_ANON_CLASS') === true) {
652
            $validScopes[] = T_ANON_CLASS;
653
        }
654
655
        if ($strict === false) {
656
            $validScopes[] = T_INTERFACE;
657
658
            if (defined('T_TRAIT')) {
659
                // phpcs:ignore PHPCompatibility.PHP.NewConstants.t_traitFound
660
                $validScopes[] = T_TRAIT;
661
            }
662
        }
663
664
        return $phpcsFile->hasCondition($stackPtr, $validScopes);
665
    }
666
667
668
    /**
669
     * Verify whether a token is within a scoped use statement.
670
     *
671
     * PHPCS cross-version compatibility method.
672
     *
673
     * In PHPCS 1.x no conditions are set for a scoped use statement.
674
     * This method works around that limitation.
675
     *
676
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
677
     * @param int                   $stackPtr  The position of the token.
678
     *
679
     * @return bool True if within use scope, false otherwise.
680
     */
681
    public function inUseScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
682
    {
683
        static $isLowPHPCS, $ignoreTokens;
684
685
        if (isset($isLowPHPCS) === false) {
686
            $isLowPHPCS = version_compare(PHPCSHelper::getVersion(), '2.3.0', '<');
687
        }
688
        if (isset($ignoreTokens) === false) {
689
            $ignoreTokens              = \PHP_CodeSniffer_Tokens::$emptyTokens;
690
            $ignoreTokens[T_STRING]    = T_STRING;
691
            $ignoreTokens[T_AS]        = T_AS;
692
            $ignoreTokens[T_PUBLIC]    = T_PUBLIC;
693
            $ignoreTokens[T_PROTECTED] = T_PROTECTED;
694
            $ignoreTokens[T_PRIVATE]   = T_PRIVATE;
695
        }
696
697
        // PHPCS 2.0.
698
        if ($isLowPHPCS === false) {
699
            return $phpcsFile->hasCondition($stackPtr, T_USE);
700
        } else {
701
            // PHPCS 1.x.
702
            $tokens         = $phpcsFile->getTokens();
703
            $maybeCurlyOpen = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
704
            if ($tokens[$maybeCurlyOpen]['code'] === T_OPEN_CURLY_BRACKET) {
705
                $maybeUseStatement = $phpcsFile->findPrevious($ignoreTokens, ($maybeCurlyOpen - 1), null, true);
706
                if ($tokens[$maybeUseStatement]['code'] === T_USE) {
707
                    return true;
708
                }
709
            }
710
            return false;
711
        }
712
    }
713
714
715
    /**
716
     * Returns the fully qualified class name for a new class instantiation.
717
     *
718
     * Returns an empty string if the class name could not be reliably inferred.
719
     *
720
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
721
     * @param int                   $stackPtr  The position of a T_NEW token.
722
     *
723
     * @return string
724
     */
725
    public function getFQClassNameFromNewToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
726
    {
727
        $tokens = $phpcsFile->getTokens();
728
729
        // Check for the existence of the token.
730
        if (isset($tokens[$stackPtr]) === false) {
731
            return '';
732
        }
733
734
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
735
            return '';
736
        }
737
738
        $start = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
739
        if ($start === false) {
740
            return '';
741
        }
742
743
        // Bow out if the next token is a variable as we don't know where it was defined.
744
        if ($tokens[$start]['code'] === T_VARIABLE) {
745
            return '';
746
        }
747
748
        // Bow out if the next token is the class keyword.
749
        if ($tokens[$start]['type'] === 'T_ANON_CLASS' || $tokens[$start]['code'] === T_CLASS) {
750
            return '';
751
        }
752
753
        $find = array(
754
            T_NS_SEPARATOR,
755
            T_STRING,
756
            T_NAMESPACE,
757
            T_WHITESPACE,
758
        );
759
760
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
761
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
762
        $className = trim($className);
763
764
        return $this->getFQName($phpcsFile, $stackPtr, $className);
765
    }
766
767
768
    /**
769
     * Returns the fully qualified name of the class that the specified class extends.
770
     *
771
     * Returns an empty string if the class does not extend another class or if
772
     * the class name could not be reliably inferred.
773
     *
774
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
775
     * @param int                   $stackPtr  The position of a T_CLASS token.
776
     *
777
     * @return string
778
     */
779
    public function getFQExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
780
    {
781
        $tokens = $phpcsFile->getTokens();
782
783
        // Check for the existence of the token.
784
        if (isset($tokens[$stackPtr]) === false) {
785
            return '';
786
        }
787
788 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
789
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
790
            && $tokens[$stackPtr]['type'] !== 'T_INTERFACE'
791
        ) {
792
            return '';
793
        }
794
795
        $extends = $this->findExtendedClassName($phpcsFile, $stackPtr);
796
        if (empty($extends) || is_string($extends) === false) {
797
            return '';
798
        }
799
800
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
801
    }
802
803
804
    /**
805
     * Returns the class name for the static usage of a class.
806
     * This can be a call to a method, the use of a property or constant.
807
     *
808
     * Returns an empty string if the class name could not be reliably inferred.
809
     *
810
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
811
     * @param int                   $stackPtr  The position of a T_NEW token.
812
     *
813
     * @return string
814
     */
815
    public function getFQClassNameFromDoubleColonToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
816
    {
817
        $tokens = $phpcsFile->getTokens();
818
819
        // Check for the existence of the token.
820
        if (isset($tokens[$stackPtr]) === false) {
821
            return '';
822
        }
823
824
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
825
            return '';
826
        }
827
828
        // Nothing to do if previous token is a variable as we don't know where it was defined.
829
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
830
            return '';
831
        }
832
833
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
834
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
835
            return '';
836
        }
837
838
        // Get the classname from the class declaration if self is used.
839
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
840
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
841
            if ($classDeclarationPtr === false) {
842
                return '';
843
            }
844
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
845
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
846
        }
847
848
        $find = array(
849
            T_NS_SEPARATOR,
850
            T_STRING,
851
            T_NAMESPACE,
852
            T_WHITESPACE,
853
        );
854
855
        $start = $phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true);
856
        if ($start === false || isset($tokens[($start + 1)]) === false) {
857
            return '';
858
        }
859
860
        $start     = ($start + 1);
861
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
862
        $className = trim($className);
863
864
        return $this->getFQName($phpcsFile, $stackPtr, $className);
865
    }
866
867
868
    /**
869
     * Get the Fully Qualified name for a class/function/constant etc.
870
     *
871
     * Checks if a class/function/constant name is already fully qualified and
872
     * if not, enrich it with the relevant namespace information.
873
     *
874
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
875
     * @param int                   $stackPtr  The position of the token.
876
     * @param string                $name      The class / function / constant name.
877
     *
878
     * @return string
879
     */
880
    public function getFQName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
881
    {
882
        if (strpos($name, '\\') === 0) {
883
            // Already fully qualified.
884
            return $name;
885
        }
886
887
        // Remove the namespace keyword if used.
888
        if (strpos($name, 'namespace\\') === 0) {
889
            $name = substr($name, 10);
890
        }
891
892
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
893
894
        if ($namespace === '') {
895
            return '\\' . $name;
896
        } else {
897
            return '\\' . $namespace . '\\' . $name;
898
        }
899
    }
900
901
902
    /**
903
     * Is the class/function/constant name namespaced or global ?
904
     *
905
     * @param string $FQName Fully Qualified name of a class, function etc.
906
     *                       I.e. should always start with a `\`.
907
     *
908
     * @return bool True if namespaced, false if global.
909
     */
910
    public function isNamespaced($FQName)
911
    {
912
        if (strpos($FQName, '\\') !== 0) {
913
            throw new \PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
914
        }
915
916
        return (strpos(substr($FQName, 1), '\\') !== false);
917
    }
918
919
920
    /**
921
     * Determine the namespace name an arbitrary token lives in.
922
     *
923
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
924
     * @param int                   $stackPtr  The token position for which to determine the namespace.
925
     *
926
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
927
     */
928
    public function determineNamespace(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
929
    {
930
        $tokens = $phpcsFile->getTokens();
931
932
        // Check for the existence of the token.
933
        if (isset($tokens[$stackPtr]) === false) {
934
            return '';
935
        }
936
937
        // Check for scoped namespace {}.
938
        if (empty($tokens[$stackPtr]['conditions']) === false) {
939
            $namespacePtr = $phpcsFile->getCondition($stackPtr, T_NAMESPACE);
940
            if ($namespacePtr !== false) {
941
                $namespace = $this->getDeclaredNamespaceName($phpcsFile, $namespacePtr);
942
                if ($namespace !== false) {
943
                    return $namespace;
944
                }
945
946
                // We are in a scoped namespace, but couldn't determine the name. Searching for a global namespace is futile.
947
                return '';
948
            }
949
        }
950
951
        /*
952
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
953
         * Keeping in mind that:
954
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
955
         * - the namespace keyword can also be used as part of a function/method call and such.
956
         * - that a non-named namespace resolves to the global namespace.
957
         */
958
        $previousNSToken = $stackPtr;
959
        $namespace       = false;
960
        do {
961
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, ($previousNSToken - 1));
962
963
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
964
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] === $previousNSToken) {
965
                break;
966
            }
967
968
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
969
970
        } while ($namespace === false && $previousNSToken !== false);
971
972
        // If we still haven't got a namespace, return an empty string.
973
        if ($namespace === false) {
974
            return '';
975
        } else {
976
            return $namespace;
977
        }
978
    }
979
980
    /**
981
     * Get the complete namespace name for a namespace declaration.
982
     *
983
     * For hierarchical namespaces, the name will be composed of several tokens,
984
     * i.e. MyProject\Sub\Level which will be returned together as one string.
985
     *
986
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
987
     * @param int|bool              $stackPtr  The position of a T_NAMESPACE token.
988
     *
989
     * @return string|false Namespace name or false if not a namespace declaration.
990
     *                      Namespace name can be an empty string for global namespace declaration.
991
     */
992
    public function getDeclaredNamespaceName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
993
    {
994
        $tokens = $phpcsFile->getTokens();
995
996
        // Check for the existence of the token.
997 View Code Duplication
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
998
            return false;
999
        }
1000
1001
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
1002
            return false;
1003
        }
1004
1005
        if ($tokens[($stackPtr + 1)]['code'] === T_NS_SEPARATOR) {
1006
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
1007
            return false;
1008
        }
1009
1010
        $nextToken = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true, null, true);
1011
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
1012
            // Declaration for global namespace when using multiple namespaces in a file.
1013
            // I.e.: namespace {}
1014
            return '';
1015
        }
1016
1017
        // Ok, this should be a namespace declaration, so get all the parts together.
1018
        $validTokens = array(
1019
            T_STRING       => true,
1020
            T_NS_SEPARATOR => true,
1021
            T_WHITESPACE   => true,
1022
        );
1023
1024
        $namespaceName = '';
1025
        while (isset($validTokens[$tokens[$nextToken]['code']]) === true) {
1026
            $namespaceName .= trim($tokens[$nextToken]['content']);
1027
            $nextToken++;
1028
        }
1029
1030
        return $namespaceName;
1031
    }
1032
1033
1034
    /**
1035
     * Get the stack pointer for a return type token for a given function.
1036
     *
1037
     * Compatible layer for older PHPCS versions which don't recognize
1038
     * return type hints correctly.
1039
     *
1040
     * Expects to be passed T_RETURN_TYPE, T_FUNCTION or T_CLOSURE token.
1041
     *
1042
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1043
     * @param int                   $stackPtr  The position of the token.
1044
     *
1045
     * @return int|false Stack pointer to the return type token or false if
1046
     *                   no return type was found or the passed token was
1047
     *                   not of the correct type.
1048
     */
1049
    public function getReturnTypeHintToken(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1050
    {
1051
        $tokens = $phpcsFile->getTokens();
1052
1053
        if (defined('T_RETURN_TYPE') && $tokens[$stackPtr]['code'] === T_RETURN_TYPE) {
1054
            return $tokens[$stackPtr]['code'];
1055
        }
1056
1057 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1058
            return false;
1059
        }
1060
1061
        if (isset($tokens[$stackPtr]['parenthesis_closer'], $tokens[$stackPtr]['scope_opener']) === false
1062
            || ($tokens[$stackPtr]['parenthesis_closer'] + 1) === $tokens[$stackPtr]['scope_opener']
1063
        ) {
1064
            return false;
1065
        }
1066
1067
        $hasColon = $phpcsFile->findNext(
1068
            array(T_COLON, T_INLINE_ELSE),
1069
            ($tokens[$stackPtr]['parenthesis_closer'] + 1),
1070
            $tokens[$stackPtr]['scope_opener']
1071
        );
1072
        if ($hasColon === false) {
1073
            return false;
1074
        }
1075
1076
        // `self`, `parent` and `callable` are not being recognized as return types in PHPCS < 2.6.0.
1077
        $unrecognizedTypes = array(
1078
            T_CALLABLE,
1079
            T_SELF,
1080
            T_PARENT,
1081
        );
1082
1083
        // Return types are not recognized at all in PHPCS < 2.4.0.
1084
        if (defined('T_RETURN_TYPE') === false) {
1085
            $unrecognizedTypes[] = T_ARRAY;
1086
            $unrecognizedTypes[] = T_STRING;
1087
        }
1088
1089
        return $phpcsFile->findPrevious($unrecognizedTypes, ($tokens[$stackPtr]['scope_opener'] - 1), $hasColon);
1090
    }
1091
1092
1093
    /**
1094
     * Get the complete return type declaration for a given function.
1095
     *
1096
     * Cross-version compatible way to retrieve the complete return type declaration.
1097
     *
1098
     * For a classname-based return type, PHPCS, as well as the Sniff::getReturnTypeHintToken()
1099
     * method will mark the classname as the return type token.
1100
     * This method will find preceeding namespaces and namespace separators and will return a
1101
     * string containing the qualified return type declaration.
1102
     *
1103
     * Expects to be passed a T_RETURN_TYPE token or the return value from a call to
1104
     * the Sniff::getReturnTypeHintToken() method.
1105
     *
1106
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1107
     * @param int                   $stackPtr  The position of the return type token.
1108
     *
1109
     * @return string|false The name of the return type token.
1110
     */
1111
    public function getReturnTypeHintName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1112
    {
1113
        $tokens = $phpcsFile->getTokens();
1114
1115
        // In older PHPCS versions, the nullable indicator will turn a return type colon into a T_INLINE_ELSE.
1116
        $colon = $phpcsFile->findPrevious(array(T_COLON, T_INLINE_ELSE, T_FUNCTION, T_CLOSE_PARENTHESIS), ($stackPtr - 1));
1117
        if ($colon === false
1118
            || ($tokens[$colon]['code'] !== T_COLON && $tokens[$colon]['code'] !== T_INLINE_ELSE)
1119
        ) {
1120
            // Shouldn't happen, just in case.
1121
            return;
1122
        }
1123
1124
        $returnTypeHint = '';
1125
        for ($i = ($colon + 1); $i < $stackPtr; $i++) {
1126
            if ($tokens[$i]['code'] === T_STRING || $tokens[$i]['code'] === T_NS_SEPARATOR) {
1127
                $returnTypeHint .= $tokens[$i]['content'];
1128
            }
1129
        }
1130
        $returnTypeHint .= $tokens[$stackPtr]['content'];
1131
1132
        return $returnTypeHint;
1133
    }
1134
1135
1136
    /**
1137
     * Check whether a T_VARIABLE token is a class property declaration.
1138
     *
1139
     * Compatibility layer for PHPCS cross-version compatibility
1140
     * as PHPCS 2.4.0 - 2.7.1 does not have good enough support for
1141
     * anonymous classes. Along the same lines, the`getMemberProperties()`
1142
     * method does not support the `var` prefix.
1143
     *
1144
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1145
     * @param int                   $stackPtr  The position in the stack of the
1146
     *                                         T_VARIABLE token to verify.
1147
     *
1148
     * @return bool
1149
     */
1150
    public function isClassProperty(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1151
    {
1152
        $tokens = $phpcsFile->getTokens();
1153
1154 View Code Duplication
        if (isset($tokens[$stackPtr]) === false || $tokens[$stackPtr]['code'] !== T_VARIABLE) {
1155
            return false;
1156
        }
1157
1158
        // Note: interfaces can not declare properties.
1159
        $validScopes = array(
1160
            'T_CLASS'      => true,
1161
            'T_ANON_CLASS' => true,
1162
            'T_TRAIT'      => true,
1163
        );
1164
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1165
            // Make sure it's not a method parameter.
1166
            if (empty($tokens[$stackPtr]['nested_parenthesis']) === true) {
1167
                return true;
1168
            }
1169
        }
1170
1171
        return false;
1172
    }
1173
1174
1175
    /**
1176
     * Check whether a T_CONST token is a class constant declaration.
1177
     *
1178
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1179
     * @param int                   $stackPtr  The position in the stack of the
1180
     *                                         T_CONST token to verify.
1181
     *
1182
     * @return bool
1183
     */
1184
    public function isClassConstant(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1185
    {
1186
        $tokens = $phpcsFile->getTokens();
1187
1188 View Code Duplication
        if (isset($tokens[$stackPtr]) === false || $tokens[$stackPtr]['code'] !== T_CONST) {
1189
            return false;
1190
        }
1191
1192
        // Note: traits can not declare constants.
1193
        $validScopes = array(
1194
            'T_CLASS'      => true,
1195
            'T_ANON_CLASS' => true,
1196
            'T_INTERFACE'  => true,
1197
        );
1198
        if ($this->validDirectScope($phpcsFile, $stackPtr, $validScopes) === true) {
1199
            return true;
1200
        }
1201
1202
        return false;
1203
    }
1204
1205
1206
    /**
1207
     * Check whether the direct wrapping scope of a token is within a limited set of
1208
     * acceptable tokens.
1209
     *
1210
     * Used to check, for instance, if a T_CONST is a class constant.
1211
     *
1212
     * @param \PHP_CodeSniffer_File $phpcsFile   Instance of phpcsFile.
1213
     * @param int                   $stackPtr    The position in the stack of the
1214
     *                                           T_CONST token to verify.
1215
     * @param array                 $validScopes Array of token types.
1216
     *                                           Keys should be the token types in string
1217
     *                                           format to allow for newer token types.
1218
     *                                           Value is irrelevant.
1219
     *
1220
     * @return bool
1221
     */
1222
    protected function validDirectScope(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes)
1223
    {
1224
        $tokens = $phpcsFile->getTokens();
1225
1226
        if (empty($tokens[$stackPtr]['conditions']) === true) {
1227
            return false;
1228
        }
1229
1230
        /*
1231
         * Check only the direct wrapping scope of the token.
1232
         */
1233
        $conditions = array_keys($tokens[$stackPtr]['conditions']);
1234
        $ptr        = array_pop($conditions);
1235
1236
        if (isset($tokens[$ptr]) === false) {
1237
            return false;
1238
        }
1239
1240
        if (isset($validScopes[$tokens[$ptr]['type']]) === true) {
1241
            return true;
1242
        }
1243
1244
        return false;
1245
    }
1246
1247
1248
    /**
1249
     * Get an array of just the type hints from a function declaration.
1250
     *
1251
     * Expects to be passed T_FUNCTION or T_CLOSURE token.
1252
     *
1253
     * Strips potential nullable indicator and potential global namespace
1254
     * indicator from the type hints before returning them.
1255
     *
1256
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1257
     * @param int                   $stackPtr  The position of the token.
1258
     *
1259
     * @return array Array with type hints or an empty array if
1260
     *               - the function does not have any parameters
1261
     *               - no type hints were found
1262
     *               - or the passed token was not of the correct type.
1263
     */
1264
    public function getTypeHintsFromFunctionDeclaration(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1265
    {
1266
        $tokens = $phpcsFile->getTokens();
1267
1268 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1269
            return array();
1270
        }
1271
1272
        $parameters = $this->getMethodParameters($phpcsFile, $stackPtr);
1273
        if (empty($parameters) || is_array($parameters) === false) {
1274
            return array();
1275
        }
1276
1277
        $typeHints = array();
1278
1279
        foreach ($parameters as $param) {
1280
            if ($param['type_hint'] === '') {
1281
                continue;
1282
            }
1283
1284
            // Strip off potential nullable indication.
1285
            $typeHint = ltrim($param['type_hint'], '?');
1286
1287
            // Strip off potential (global) namespace indication.
1288
            $typeHint = ltrim($typeHint, '\\');
1289
1290
            if ($typeHint !== '') {
1291
                $typeHints[] = $typeHint;
1292
            }
1293
        }
1294
1295
        return $typeHints;
1296
    }
1297
1298
1299
    /**
1300
     * Returns the method parameters for the specified function token.
1301
     *
1302
     * Each parameter is in the following format:
1303
     *
1304
     * <code>
1305
     *   0 => array(
1306
     *         'token'             => int,     // The position of the var in the token stack.
1307
     *         'name'              => '$var',  // The variable name.
1308
     *         'content'           => string,  // The full content of the variable definition.
1309
     *         'pass_by_reference' => boolean, // Is the variable passed by reference?
1310
     *         'variable_length'   => boolean, // Is the param of variable length through use of `...` ?
1311
     *         'type_hint'         => string,  // The type hint for the variable.
1312
     *         'nullable_type'     => boolean, // Is the variable using a nullable type?
1313
     *        )
1314
     * </code>
1315
     *
1316
     * Parameters with default values have an additional array index of
1317
     * 'default' with the value of the default as a string.
1318
     *
1319
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1320
     * class, but with some improvements which have been introduced in
1321
     * PHPCS 2.8.0.
1322
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1117},
1323
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1193} and
1324
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/pull/1293}.
1325
     *
1326
     * Once the minimum supported PHPCS version for this standard goes beyond
1327
     * that, this method can be removed and calls to it replaced with
1328
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.
1329
     *
1330
     * NOTE: This version does not deal with the new T_NULLABLE token type.
1331
     * This token is included upstream only in 2.8.0+ and as we defer to upstream
1332
     * in that case, no need to deal with it here.
1333
     *
1334
     * Last synced with PHPCS version: PHPCS 2.9.0-alpha at commit f1511adad043edfd6d2e595e77385c32577eb2bc}}
1335
     *
1336
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1337
     * @param int                   $stackPtr  The position in the stack of the
1338
     *                                         function token to acquire the
1339
     *                                         parameters for.
1340
     *
1341
     * @return array|false
1342
     * @throws \PHP_CodeSniffer_Exception If the specified $stackPtr is not of
1343
     *                                    type T_FUNCTION or T_CLOSURE.
1344
     */
1345
    public function getMethodParameters(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1346
    {
1347
        if (version_compare(PHPCSHelper::getVersion(), '2.7.1', '>') === true) {
1348
            return $phpcsFile->getMethodParameters($stackPtr);
1349
        }
1350
1351
        $tokens = $phpcsFile->getTokens();
1352
1353
        // Check for the existence of the token.
1354
        if (isset($tokens[$stackPtr]) === false) {
1355
            return false;
1356
        }
1357
1358 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION && $tokens[$stackPtr]['code'] !== T_CLOSURE) {
1359
            throw new \PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION or T_CLOSURE');
1360
        }
1361
1362
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
1363
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
1364
1365
        $vars            = array();
1366
        $currVar         = null;
1367
        $paramStart      = ($opener + 1);
1368
        $defaultStart    = null;
1369
        $paramCount      = 0;
1370
        $passByReference = false;
1371
        $variableLength  = false;
1372
        $typeHint        = '';
1373
        $nullableType    = false;
1374
1375
        for ($i = $paramStart; $i <= $closer; $i++) {
1376
            // Check to see if this token has a parenthesis or bracket opener. If it does
1377
            // it's likely to be an array which might have arguments in it. This
1378
            // could cause problems in our parsing below, so lets just skip to the
1379
            // end of it.
1380 View Code Duplication
            if (isset($tokens[$i]['parenthesis_opener']) === true) {
1381
                // Don't do this if it's the close parenthesis for the method.
1382
                if ($i !== $tokens[$i]['parenthesis_closer']) {
1383
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
1384
                }
1385
            }
1386
1387 View Code Duplication
            if (isset($tokens[$i]['bracket_opener']) === true) {
1388
                // Don't do this if it's the close parenthesis for the method.
1389
                if ($i !== $tokens[$i]['bracket_closer']) {
1390
                    $i = ($tokens[$i]['bracket_closer'] + 1);
1391
                }
1392
            }
1393
1394
            switch ($tokens[$i]['type']) {
1395
                case 'T_BITWISE_AND':
1396
                    $passByReference = true;
1397
                    break;
1398
                case 'T_VARIABLE':
1399
                    $currVar = $i;
1400
                    break;
1401
                case 'T_ELLIPSIS':
1402
                    $variableLength = true;
1403
                    break;
1404
                case 'T_ARRAY_HINT':
1405
                case 'T_CALLABLE':
1406
                    $typeHint .= $tokens[$i]['content'];
1407
                    break;
1408
                case 'T_SELF':
1409
                case 'T_PARENT':
1410
                case 'T_STATIC':
1411
                    // Self is valid, the others invalid, but were probably intended as type hints.
1412
                    if (isset($defaultStart) === false) {
1413
                        $typeHint .= $tokens[$i]['content'];
1414
                    }
1415
                    break;
1416
                case 'T_STRING':
1417
                    // This is a string, so it may be a type hint, but it could
1418
                    // also be a constant used as a default value.
1419
                    $prevComma = false;
1420 View Code Duplication
                    for ($t = $i; $t >= $opener; $t--) {
1421
                        if ($tokens[$t]['code'] === T_COMMA) {
1422
                            $prevComma = $t;
1423
                            break;
1424
                        }
1425
                    }
1426
1427
                    if ($prevComma !== false) {
1428
                        $nextEquals = false;
1429 View Code Duplication
                        for ($t = $prevComma; $t < $i; $t++) {
1430
                            if ($tokens[$t]['code'] === T_EQUAL) {
1431
                                $nextEquals = $t;
1432
                                break;
1433
                            }
1434
                        }
1435
1436
                        if ($nextEquals !== false) {
1437
                            break;
1438
                        }
1439
                    }
1440
1441
                    if ($defaultStart === null) {
1442
                        $typeHint .= $tokens[$i]['content'];
1443
                    }
1444
                    break;
1445
                case 'T_NS_SEPARATOR':
1446
                    // Part of a type hint or default value.
1447
                    if ($defaultStart === null) {
1448
                        $typeHint .= $tokens[$i]['content'];
1449
                    }
1450
                    break;
1451
                case 'T_INLINE_THEN':
1452
                    if ($defaultStart === null) {
1453
                        $nullableType = true;
1454
                        $typeHint    .= $tokens[$i]['content'];
1455
                    }
1456
                    break;
1457
                case 'T_CLOSE_PARENTHESIS':
1458
                case 'T_COMMA':
1459
                    // If it's null, then there must be no parameters for this
1460
                    // method.
1461
                    if ($currVar === null) {
1462
                        continue;
1463
                    }
1464
1465
                    $vars[$paramCount]            = array();
1466
                    $vars[$paramCount]['token']   = $currVar;
1467
                    $vars[$paramCount]['name']    = $tokens[$currVar]['content'];
1468
                    $vars[$paramCount]['content'] = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
1469
1470
                    if ($defaultStart !== null) {
1471
                        $vars[$paramCount]['default'] = trim(
1472
                            $phpcsFile->getTokensAsString(
1473
                                $defaultStart,
1474
                                ($i - $defaultStart)
1475
                            )
1476
                        );
1477
                    }
1478
1479
                    $vars[$paramCount]['pass_by_reference'] = $passByReference;
1480
                    $vars[$paramCount]['variable_length']   = $variableLength;
1481
                    $vars[$paramCount]['type_hint']         = $typeHint;
1482
                    $vars[$paramCount]['nullable_type']     = $nullableType;
1483
1484
                    // Reset the vars, as we are about to process the next parameter.
1485
                    $defaultStart    = null;
1486
                    $paramStart      = ($i + 1);
1487
                    $passByReference = false;
1488
                    $variableLength  = false;
1489
                    $typeHint        = '';
1490
                    $nullableType    = false;
1491
1492
                    $paramCount++;
1493
                    break;
1494
                case 'T_EQUAL':
1495
                    $defaultStart = ($i + 1);
1496
                    break;
1497
            }//end switch
1498
        }//end for
1499
1500
        return $vars;
1501
1502
    }//end getMethodParameters()
1503
1504
1505
    /**
1506
     * Returns the name of the class that the specified class extends
1507
     * (works for classes, anonymous classes and interfaces).
1508
     *
1509
     * Returns FALSE on error or if there is no extended class name.
1510
     *
1511
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1512
     * class, but with some improvements which have been introduced in
1513
     * PHPCS 2.8.0.
1514
     * {@link https://github.com/squizlabs/PHP_CodeSniffer/commit/0011d448119d4c568e3ac1f825ae78815bf2cc34}.
1515
     *
1516
     * Once the minimum supported PHPCS version for this standard goes beyond
1517
     * that, this method can be removed and calls to it replaced with
1518
     * `$phpcsFile->findExtendedClassName($stackPtr)` calls.
1519
     *
1520
     * Last synced with PHPCS version: PHPCS 3.1.0-alpha at commit a9efcc9b0703f3f9f4a900623d4e97128a6aafc6}}
1521
     *
1522
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1523
     * @param int                   $stackPtr  The position of the class token in the stack.
1524
     *
1525
     * @return string|false
1526
     */
1527
    public function findExtendedClassName(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1528
    {
1529
        if (version_compare(PHPCSHelper::getVersion(), '3.1.0', '>=') === true) {
1530
            return $phpcsFile->findExtendedClassName($stackPtr);
1531
        }
1532
1533
        $tokens = $phpcsFile->getTokens();
1534
1535
        // Check for the existence of the token.
1536
        if (isset($tokens[$stackPtr]) === false) {
1537
            return false;
1538
        }
1539
1540 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_CLASS
1541
            && $tokens[$stackPtr]['type'] !== 'T_ANON_CLASS'
1542
            && $tokens[$stackPtr]['type'] !== 'T_INTERFACE'
1543
        ) {
1544
            return false;
1545
        }
1546
1547
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
1548
            return false;
1549
        }
1550
1551
        $classCloserIndex = $tokens[$stackPtr]['scope_closer'];
1552
        $extendsIndex     = $phpcsFile->findNext(T_EXTENDS, $stackPtr, $classCloserIndex);
1553
        if (false === $extendsIndex) {
1554
            return false;
1555
        }
1556
1557
        $find = array(
1558
            T_NS_SEPARATOR,
1559
            T_STRING,
1560
            T_WHITESPACE,
1561
        );
1562
1563
        $end  = $phpcsFile->findNext($find, ($extendsIndex + 1), $classCloserIndex, true);
1564
        $name = $phpcsFile->getTokensAsString(($extendsIndex + 1), ($end - $extendsIndex - 1));
1565
        $name = trim($name);
1566
1567
        if ($name === '') {
1568
            return false;
1569
        }
1570
1571
        return $name;
1572
1573
    }//end findExtendedClassName()
1574
1575
1576
    /**
1577
     * Get the hash algorithm name from the parameter in a hash function call.
1578
     *
1579
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1580
     * @param int                   $stackPtr  The position of the T_STRING function token.
1581
     *
1582
     * @return string|false The algorithm name without quotes if this was a relevant hash
1583
     *                      function call or false if it was not.
1584
     */
1585
    public function getHashAlgorithmParameter(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1586
    {
1587
        $tokens = $phpcsFile->getTokens();
1588
1589
        // Check for the existence of the token.
1590
        if (isset($tokens[$stackPtr]) === false) {
1591
            return false;
1592
        }
1593
1594
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1595
            return false;
1596
        }
1597
1598
        $functionName   = $tokens[$stackPtr]['content'];
1599
        $functionNameLc = strtolower($functionName);
1600
1601
        // Bow out if not one of the functions we're targetting.
1602
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
1603
            return false;
1604
        }
1605
1606
        // Get the parameter from the function call which should contain the algorithm name.
1607
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
1608
        if ($algoParam === false) {
1609
            return false;
1610
        }
1611
1612
        // Algorithm is a text string, so we need to remove the quotes.
1613
        $algo = strtolower(trim($algoParam['raw']));
1614
        $algo = $this->stripQuotes($algo);
1615
1616
        return $algo;
1617
    }
1618
1619
1620
    /**
1621
     * Determine whether an arbitrary T_STRING token is the use of a global constant.
1622
     *
1623
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
1624
     * @param int                   $stackPtr  The position of the function call token.
1625
     *
1626
     * @return bool
1627
     */
1628
    public function isUseOfGlobalConstant(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1629
    {
1630
        static $isLowPHPCS, $isLowPHP;
1631
1632
        $tokens = $phpcsFile->getTokens();
1633
1634
        // Check for the existence of the token.
1635
        if (isset($tokens[$stackPtr]) === false) {
1636
            return false;
1637
        }
1638
1639
        // Is this one of the tokens this function handles ?
1640
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1641
            return false;
1642
        }
1643
1644
        // Check for older PHP, PHPCS version so we can compensate for misidentified tokens.
1645
        if (isset($isLowPHPCS, $isLowPHP) === false) {
1646
            $isLowPHP   = false;
1647
            $isLowPHPCS = false;
1648
            if (version_compare(PHP_VERSION_ID, '50400', '<')) {
1649
                $isLowPHP   = true;
1650
                $isLowPHPCS = version_compare(PHPCSHelper::getVersion(), '2.4.0', '<');
1651
            }
1652
        }
1653
1654
        $next = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr + 1), null, true);
1655
        if ($next !== false
1656
            && ($tokens[$next]['code'] === T_OPEN_PARENTHESIS
1657
                || $tokens[$next]['code'] === T_DOUBLE_COLON)
1658
        ) {
1659
            // Function call or declaration.
1660
            return false;
1661
        }
1662
1663
        // Array of tokens which if found preceding the $stackPtr indicate that a T_STRING is not a global constant.
1664
        $tokensToIgnore = array(
1665
            'T_NAMESPACE'       => true,
1666
            'T_USE'             => true,
1667
            'T_CLASS'           => true,
1668
            'T_TRAIT'           => true,
1669
            'T_INTERFACE'       => true,
1670
            'T_EXTENDS'         => true,
1671
            'T_IMPLEMENTS'      => true,
1672
            'T_NEW'             => true,
1673
            'T_FUNCTION'        => true,
1674
            'T_DOUBLE_COLON'    => true,
1675
            'T_OBJECT_OPERATOR' => true,
1676
            'T_INSTANCEOF'      => true,
1677
            'T_INSTEADOF'       => true,
1678
            'T_GOTO'            => true,
1679
            'T_AS'              => true,
1680
            'T_PUBLIC'          => true,
1681
            'T_PROTECTED'       => true,
1682
            'T_PRIVATE'         => true,
1683
        );
1684
1685
        $prev = $phpcsFile->findPrevious(\PHP_CodeSniffer_Tokens::$emptyTokens, ($stackPtr - 1), null, true);
1686
        if ($prev !== false
1687
            && (isset($tokensToIgnore[$tokens[$prev]['type']]) === true
1688
                || ($tokens[$prev]['code'] === T_STRING
1689
                    && (($isLowPHPCS === true
1690
                        && $tokens[$prev]['content'] === 'trait')
1691
                    || ($isLowPHP === true
1692
                        && $tokens[$prev]['content'] === 'insteadof'))))
1693
        ) {
1694
            // Not the use of a constant.
1695
            return false;
1696
        }
1697
1698
        if ($prev !== false
1699
            && $tokens[$prev]['code'] === T_NS_SEPARATOR
1700
            && $tokens[($prev - 1)]['code'] === T_STRING
1701
        ) {
1702
            // Namespaced constant of the same name.
1703
            return false;
1704
        }
1705
1706
        if ($prev !== false
1707
            && $tokens[$prev]['code'] === T_CONST
1708
            && $this->isClassConstant($phpcsFile, $prev) === true
1709
        ) {
1710
            // Class constant declaration of the same name.
1711
            return false;
1712
        }
1713
1714
        /*
1715
         * Deal with a number of variations of use statements.
1716
         */
1717
        for ($i = $stackPtr; $i > 0; $i--) {
1718
            if ($tokens[$i]['line'] !== $tokens[$stackPtr]['line']) {
1719
                break;
1720
            }
1721
        }
1722
1723
        $firstOnLine = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($i + 1), null, true);
1724
        if ($firstOnLine !== false && $tokens[$firstOnLine]['code'] === T_USE) {
1725
            $nextOnLine = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($firstOnLine + 1), null, true);
1726
            if ($nextOnLine !== false) {
1727
                if (($tokens[$nextOnLine]['code'] === T_STRING && $tokens[$nextOnLine]['content'] === 'const')
1728
                    || $tokens[$nextOnLine]['code'] === T_CONST // Happens in some PHPCS versions.
1729
                ) {
1730
                    $hasNsSep = $phpcsFile->findNext(T_NS_SEPARATOR, ($nextOnLine + 1), $stackPtr);
1731
                    if ($hasNsSep !== false) {
1732
                        // Namespaced const (group) use statement.
1733
                        return false;
1734
                    }
1735
                } else {
1736
                    // Not a const use statement.
1737
                    return false;
1738
                }
1739
            }
1740
        }
1741
1742
        return true;
1743
    }
1744
1745
1746
    /**
1747
     * Determine whether the tokens between $start and $end together form a negative number
1748
     * as recognized by PHP.
1749
     *
1750
     * The outcome of this function is reliable for `true`, `false` should be regarded as
1751
     * "undetermined".
1752
     *
1753
     * @link https://3v4l.org/npTeM
1754
     *
1755
     * Mainly intended for examining variable assignments, function call parameters, array values
1756
     * where the start and end of the snippet to examine is very clear.
1757
     *
1758
     * @param \PHP_CodeSniffer_File $phpcsFile   The file being scanned.
1759
     * @param int                   $start       Start of the snippet (inclusive), i.e. this
1760
     *                                           token will be examined as part of the snippet.
1761
     * @param int                   $end         End of the snippet (inclusive), i.e. this
1762
     *                                           token will be examined as part of the snippet.
1763
     * @param bool                  $allowFloats Whether to only consider integers, or also floats.
1764
     *
1765
     * @return bool True if PHP would evaluate the snippet as a negative number.
1766
     *              False if not or if it could not be reliably determined (variable or calculations and such).
1767
     */
1768
    public function isNegativeNumber(\PHP_CodeSniffer_File $phpcsFile, $start, $end, $allowFloats = false)
1769
    {
1770
        $stringTokens  = array_flip(\PHP_CodeSniffer_Tokens::$heredocTokens); // Flipping for PHPCS 1.x compat.
1771
        $stringTokens += array_flip(\PHP_CodeSniffer_Tokens::$stringTokens); // Flipping for PHPCS 1.x compat.
1772
1773
        $validTokens            = array();
1774
        $validTokens[T_LNUMBER] = true;
1775
        $validTokens[T_TRUE]    = true; // Evaluates to int 1.
1776
1777
        if ($allowFloats === true) {
1778
            $validTokens[T_DNUMBER] = true;
1779
        }
1780
1781
        $maybeValidTokens = $stringTokens + $validTokens;
1782
1783
        $tokens    = $phpcsFile->getTokens();
1784
        $searchEnd = ($end + 1);
1785
1786
        if (isset($tokens[$start], $tokens[$searchEnd]) === false) {
1787
            return false;
1788
        }
1789
1790
        $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, $start, $searchEnd, true);
1791
        if ($nextNonEmpty === false || $tokens[$nextNonEmpty]['code'] !== T_MINUS) {
1792
            return false;
1793
        }
1794
1795
        $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($nextNonEmpty + 1), $searchEnd, true);
1796
        if ($nextNonEmpty === false || isset($maybeValidTokens[$tokens[$nextNonEmpty]['code']]) === false) {
1797
            return false;
1798
        }
1799
1800
        $content = '';
1801
        if ($tokens[$nextNonEmpty]['code'] === T_LNUMBER
1802
            || $tokens[$nextNonEmpty]['code'] === T_DNUMBER
1803
        ) {
1804
            $content = (float) $tokens[$nextNonEmpty]['content'];
1805
        } elseif ($tokens[$nextNonEmpty]['code'] === T_TRUE) {
1806
            $content = 1.0;
1807
        } elseif (isset($stringTokens[$tokens[$nextNonEmpty]['code']]) === true) {
1808
1809
            if ($tokens[$nextNonEmpty]['code'] === T_START_HEREDOC
1810
                || $tokens[$nextNonEmpty]['code'] === T_START_NOWDOC
1811
            ) {
1812
                // Skip past heredoc/nowdoc opener to the first content.
1813
                $firstDocToken = $phpcsFile->findNext(array(T_HEREDOC, T_NOWDOC), ($nextNonEmpty + 1), $searchEnd);
1814
                if ($firstDocToken === false) {
1815
                    // Live coding or parse error.
1816
                    return false;
1817
                }
1818
1819
                $content = $tokens[$firstDocToken]['content'];
1820
1821
                // Skip forward to the end in preparation for the next part of the examination.
1822
                $nextNonEmpty = $phpcsFile->findNext(array(T_END_HEREDOC, T_END_NOWDOC), ($nextNonEmpty + 1), $searchEnd);
1823
                if ($nextNonEmpty === false) {
1824
                    // Live coding or parse error.
1825
                    return false;
1826
                }
1827
            } else {
1828
                // Gather subsequent lines for a multi-line string.
1829
                for ($i = $nextNonEmpty; $i < $searchEnd; $i++) {
1830
                    if ($tokens[$i]['code'] !== $tokens[$nextNonEmpty]['code']) {
1831
                        break;
1832
                    }
1833
                    $content .= $tokens[$i]['content'];
1834
                }
1835
1836
                $nextNonEmpty = --$i;
1837
                $content = $this->stripQuotes($content);
1838
            }
1839
1840
            /*
1841
             * Regexes based on the formats outlined in the manual, created by JRF.
1842
             * @link http://php.net/manual/en/language.types.float.php
1843
             */
1844
            $regexInt   = '`^\s*[0-9]+`';
1845
            $regexFloat = '`^\s*(?:[+-]?(?:(?:(?P<LNUM>[0-9]+)|(?P<DNUM>([0-9]*\.(?P>LNUM)|(?P>LNUM)\.[0-9]*)))[eE][+-]?(?P>LNUM))|(?P>DNUM))`';
1846
1847
            $intString   = preg_match($regexInt, $content, $intMatch);
1848
            $floatString = preg_match($regexFloat, $content, $floatMatch);
1849
1850
            // Does the text string start with a number ? If so, PHP would juggle it and use it as a number.
1851
            if ($allowFloats === false) {
1852
                if ($intString !== 1 || $floatString === 1) {
1853
                    // Found non-numeric start or float. Only integers targetted.
1854
                    return false;
1855
                }
1856
1857
                $content = (float) trim($intMatch[0]);
1858
            } else {
1859
                if ($intString !== 1 && $floatString !== 1) {
1860
                    return false;
1861
                }
1862
1863
                $content = ($floatString === 1) ? (float) trim($floatMatch[0]) : (float) trim($intMatch[0]);
1864
            }
1865
1866
            // Allow for different behaviour for hex numeric strings between PHP 5 vs PHP 7.
1867
            if ($intString === 1 && trim($intMatch[0]) === '0'
1868
                && preg_match('`^\s*0x[a-f0-9]+`', $content) === 1
1869
                && $this->supportsBelow('5.6') === true
1870
            ) {
1871
                $content = 0.1; // Fake the content to bypass the `0`-check.
1872
            }
1873
        }
1874
1875
        // Make sure the number found is not a zero.
1876
        if (0.0 === $content) {
1877
            return false;
1878
        }
1879
1880
        // OK, so we have a negative number, now is there still more code after it ?
1881
        $nextNonEmpty = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($nextNonEmpty + 1), $searchEnd, true);
1882
        if ($nextNonEmpty !== false) {
1883
            return false;
1884
        }
1885
1886
        return true;
1887
    }
1888
1889
1890
    /**
1891
     * Returns the position of the last non-whitespace token in a statement.
1892
     *
1893
     * {@internal Duplicate of same method as contained in the `\PHP_CodeSniffer_File`
1894
     * class and introduced in PHPCS 2.x.
1895
     *
1896
     * Once the minimum supported PHPCS version for this standard goes beyond
1897
     * that, this method can be removed and calls to it replaced with
1898
     * `$phpcsFile->findEndOfStatement($start, $ignore)` calls.
1899
     *
1900
     * Last synced with PHPCS version: PHPCS 3.3.0-alpha at commit e2a3e465b6a6f7cbd50eaa8a6ed5c47dbe5de641}}
1901
     *
1902
     * @param \PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1903
     * @param int                   $start     The position to start searching from in the token stack.
1904
     * @param int|array             $ignore    Token types that should not be considered stop points.
1905
     *
1906
     * @return int
1907
     */
1908
    public function findEndOfStatement(\PHP_CodeSniffer_File $phpcsFile, $start, $ignore=null)
1909
    {
1910
        if (version_compare(PHPCSHelper::getVersion(), '2.0.0', '>=') === true) {
1911
            return $phpcsFile->findEndOfStatement($start, $ignore);
1912
        }
1913
1914
        $tokens    = $phpcsFile->getTokens();
1915
        $endTokens = [
1916
            T_COLON                => true,
1917
            T_COMMA                => true,
1918
            T_DOUBLE_ARROW         => true,
1919
            T_SEMICOLON            => true,
1920
            T_CLOSE_PARENTHESIS    => true,
1921
            T_CLOSE_SQUARE_BRACKET => true,
1922
            T_CLOSE_CURLY_BRACKET  => true,
1923
            T_CLOSE_SHORT_ARRAY    => true,
1924
            T_OPEN_TAG             => true,
1925
            T_CLOSE_TAG            => true,
1926
        ];
1927
1928
        if ($ignore !== null) {
1929
            $ignore = (array) $ignore;
1930
            foreach ($ignore as $code) {
1931
                if (isset($endTokens[$code]) === true) {
1932
                    unset($endTokens[$code]);
1933
                }
1934
            }
1935
        }
1936
1937
        $lastNotEmpty = $start;
1938
1939
        for ($i = $start; $i < $phpcsFile->numTokens; $i++) {
1940
            if ($i !== $start && isset($endTokens[$tokens[$i]['code']]) === true) {
1941
                // Found the end of the statement.
1942
                if ($tokens[$i]['code'] === T_CLOSE_PARENTHESIS
1943
                    || $tokens[$i]['code'] === T_CLOSE_SQUARE_BRACKET
1944
                    || $tokens[$i]['code'] === T_CLOSE_CURLY_BRACKET
1945
                    || $tokens[$i]['code'] === T_CLOSE_SHORT_ARRAY
1946
                    || $tokens[$i]['code'] === T_OPEN_TAG
1947
                    || $tokens[$i]['code'] === T_CLOSE_TAG
1948
                ) {
1949
                    return $lastNotEmpty;
1950
                }
1951
1952
                return $i;
1953
            }
1954
1955
            // Skip nested statements.
1956
            if (isset($tokens[$i]['scope_closer']) === true
1957
                && ($i === $tokens[$i]['scope_opener']
1958
                || $i === $tokens[$i]['scope_condition'])
1959
            ) {
1960
                $i = $tokens[$i]['scope_closer'];
1961
            } else if (isset($tokens[$i]['bracket_closer']) === true
1962
                && $i === $tokens[$i]['bracket_opener']
1963
            ) {
1964
                $i = $tokens[$i]['bracket_closer'];
1965 View Code Duplication
            } else if (isset($tokens[$i]['parenthesis_closer']) === true
1966
                && $i === $tokens[$i]['parenthesis_opener']
1967
            ) {
1968
                $i = $tokens[$i]['parenthesis_closer'];
1969
            }
1970
1971
            if (isset(\PHP_CodeSniffer_Tokens::$emptyTokens[$tokens[$i]['code']]) === false) {
1972
                $lastNotEmpty = $i;
1973
            }
1974
        }//end for
1975
1976
        return ($phpcsFile->numTokens - 1);
1977
1978
    }//end findEndOfStatement()
1979
1980
}//end class
1981