Completed
Pull Request — master (#300)
by Juliette
01:45
created

PHPCompatibility_Sniff::stripQuotes()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
/**
3
 * PHPCompatibility_Sniff.
4
 *
5
 * PHP version 5.6
6
 *
7
 * @category  PHP
8
 * @package   PHPCompatibility
9
 * @author    Wim Godden <[email protected]>
10
 * @copyright 2014 Cu.be Solutions bvba
11
 */
12
13
/**
14
 * PHPCompatibility_Sniff.
15
 *
16
 * @category  PHP
17
 * @package   PHPCompatibility
18
 * @author    Wim Godden <[email protected]>
19
 * @version   1.1.0
20
 * @copyright 2014 Cu.be Solutions bvba
21
 */
22
abstract class PHPCompatibility_Sniff implements PHP_CodeSniffer_Sniff
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

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

namespace YourVendor;

class YourClass { }

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

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