Completed
Push — master ( a20f6a...c10348 )
by Juliette
15s queued 10s
created

Sniff.php (9 issues)

Upgrade to new PHP Analysis Engine

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

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

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

namespace YourVendor;

class YourClass { }

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

Loading history...
23
{
24
25
    /**
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
/* The testVersion configuration variable may be in any of the following formats:
44
 * 1) Omitted/empty, in which case no version is specified.  This effectively
45
 *    disables all the checks provided by this standard.
46
 * 2) A single PHP version number, e.g. "5.4" in which case the standard checks that
47
 *    the code will run on that version of PHP (no deprecated features or newer
48
 *    features being used).
49
 * 3) A range, e.g. "5.0-5.5", in which case the standard checks the code will run
50
 *    on all PHP versions in that range, and that it doesn't use any features that
51
 *    were deprecated by the final version in the list, or which were not available
52
 *    for the first version in the list.
53
 * PHP version numbers should always be in Major.Minor format.  Both "5", "5.3.2"
54
 * would be treated as invalid, and ignored.
55
 * This standard doesn't support checking against PHP4, so the minimum version that
56
 * is recognised is "5.0".
57
 */
58
59
    private function getTestVersion()
60
    {
61
        /**
62
         * var $arrTestVersions will hold an array containing min/max version of PHP
63
         *   that we are checking against (see above).  If only a single version
64
         *   number is specified, then this is used as both the min and max.
65
         */
66
        static $arrTestVersions = array();
67
68
        $testVersion = trim(PHP_CodeSniffer::getConfigData('testVersion'));
69
70
        if (!isset($arrTestVersions[$testVersion]) && !empty($testVersion)) {
71
72
            $arrTestVersions[$testVersion] = array(null, null);
73
            if (preg_match('/^\d+\.\d+$/', $testVersion)) {
74
                $arrTestVersions[$testVersion] = array($testVersion, $testVersion);
75
            }
76
            elseif (preg_match('/^(\d+\.\d+)\s*-\s*(\d+\.\d+)$/', $testVersion,
77
                               $matches))
78
            {
79
                if (version_compare($matches[1], $matches[2], '>')) {
80
                    trigger_error("Invalid range in testVersion setting: '"
81
                                  . $testVersion . "'", E_USER_WARNING);
82
                }
83
                else {
84
                    $arrTestVersions[$testVersion] = array($matches[1], $matches[2]);
85
                }
86
            }
87
            elseif (!$testVersion == '') {
88
                trigger_error("Invalid testVersion setting: '" . $testVersion
89
                              . "'", E_USER_WARNING);
90
            }
91
        }
92
93
        if (isset($arrTestVersions[$testVersion])) {
94
            return $arrTestVersions[$testVersion];
95
        }
96
        else {
97
            return array(null, null);
98
        }
99
    }
100
101 View Code Duplication
    public function supportsAbove($phpVersion)
0 ignored issues
show
This method seems to be duplicated in your project.

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

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

Loading history...
102
    {
103
        $testVersion = $this->getTestVersion();
104
        $testVersion = $testVersion[1];
105
106
        if (is_null($testVersion)
107
            || version_compare($testVersion, $phpVersion) >= 0
108
        ) {
109
            return true;
110
        } else {
111
            return false;
112
        }
113
    }//end supportsAbove()
114
115 View Code Duplication
    public function supportsBelow($phpVersion)
0 ignored issues
show
This method seems to be duplicated in your project.

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

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

Loading history...
116
    {
117
        $testVersion = $this->getTestVersion();
118
        $testVersion = $testVersion[0];
119
120
        if (!is_null($testVersion)
121
            && version_compare($testVersion, $phpVersion) <= 0
122
        ) {
123
            return true;
124
        } else {
125
            return false;
126
        }
127
    }//end supportsBelow()
128
129
130
    /**
131
     * Strip quotes surrounding an arbitrary string.
132
     *
133
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING.
134
     *
135
     * @param string $string The raw string.
136
     *
137
     * @return string String without quotes around it.
138
     */
139
    public function stripQuotes($string) {
140
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
141
    }
142
143
144
    /**
145
     * Returns the name(s) of the interface(s) that the specified class implements.
146
     *
147
     * Returns FALSE on error or if there are no implemented interface names.
148
     *
149
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
150
     * Once the minimum supported PHPCS version for this sniff library goes beyond
151
     * that, this method can be removed and call to it replaced with
152
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
153
     *
154
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
155
     * @param int                  $stackPtr  The position of the class token.
156
     *
157
     * @return array|false
158
     */
159
    public function findImplementedInterfaceNames(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
160
    {
161
        if (method_exists($phpcsFile, 'findImplementedInterfaceNames')) {
162
            return $phpcsFile->findImplementedInterfaceNames($stackPtr);
163
        }
164
165
        $tokens = $phpcsFile->getTokens();
166
167
        // Check for the existence of the token.
168
        if (isset($tokens[$stackPtr]) === false) {
169
            return false;
170
        }
171
172
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
173
            return false;
174
        }
175
176
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
177
            return false;
178
        }
179
180
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
181
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
182
        if ($implementsIndex === false) {
183
            return false;
184
        }
185
186
        $find = array(
187
                 T_NS_SEPARATOR,
188
                 T_STRING,
189
                 T_WHITESPACE,
190
                 T_COMMA,
191
                );
192
193
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
194
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
195
        $name = trim($name);
196
197
        if ($name === '') {
198
            return false;
199
        } else {
200
            $names = explode(',', $name);
201
            $names = array_map('trim', $names);
202
            return $names;
203
        }
204
205
    }//end findImplementedInterfaceNames()
206
207
208
    /**
209
     * Checks if a function call has parameters.
210
     *
211
     * Expects to be passed the T_STRING stack pointer for the function call.
212
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
213
     *
214
     * @link https://github.com/wimg/PHPCompatibility/issues/120
215
     * @link https://github.com/wimg/PHPCompatibility/issues/152
216
     *
217
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
218
     * @param int                  $stackPtr  The position of the function call token.
219
     *
220
     * @return bool
221
     */
222
    public function doesFunctionCallHaveParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
223
    {
224
        $tokens = $phpcsFile->getTokens();
225
226
        // Check for the existence of the token.
227
        if (isset($tokens[$stackPtr]) === false) {
228
            return false;
229
        }
230
231
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
232
            return false;
233
        }
234
235
        // Next non-empty token should be the open parenthesis.
236
        $openParenthesis = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
237
        if ($openParenthesis === false || $tokens[$openParenthesis]['code'] !== T_OPEN_PARENTHESIS) {
238
            return false;
239
        }
240
241
        if (isset($tokens[$openParenthesis]['parenthesis_closer']) === false) {
242
            return false;
243
        }
244
245
        $closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
246
        $nextNonEmpty     = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $openParenthesis + 1, $closeParenthesis + 1, true);
247
248
        if ($nextNonEmpty === $closeParenthesis) {
249
            // No parameters.
250
            return false;
251
        }
252
253
        return true;
254
    }
255
256
257
    /**
258
     * Count the number of parameters a function call has been passed.
259
     *
260
     * Expects to be passed the T_STRING stack pointer for the function call.
261
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
262
     *
263
     * @link https://github.com/wimg/PHPCompatibility/issues/111
264
     * @link https://github.com/wimg/PHPCompatibility/issues/114
265
     * @link https://github.com/wimg/PHPCompatibility/issues/151
266
     *
267
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
268
     * @param int                  $stackPtr  The position of the function call token.
269
     *
270
     * @return int
271
     */
272
    public function getFunctionCallParameterCount(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
273
    {
274
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
275
            return 0;
276
        }
277
278
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
279
    }
280
281
282
    /**
283
     * Get information on all parameters passed to a function call.
284
     *
285
     * Expects to be passed the T_STRING stack pointer for the function call.
286
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
287
     *
288
     * Will return an multi-dimentional array with the start token pointer, end token
289
     * pointer and raw parameter value for all parameters. Index will be 1-based.
290
     * If no parameters are found, will return an empty array.
291
     *
292
     * @param PHP_CodeSniffer_File $phpcsFile     The file being scanned.
293
     * @param int                  $stackPtr      The position of the function call token.
294
     *
295
     * @return array
296
     */
297
    public function getFunctionCallParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
298
    {
299
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
300
            return array();
301
        }
302
303
        // Ok, we know we have a T_STRING with parameters and valid open & close parenthesis.
304
        $tokens = $phpcsFile->getTokens();
305
306
        $openParenthesis  = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
307
        $closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
308
309
        // Which nesting level is the one we are interested in ?
310
        $nestedParenthesisCount = 1;
311 View Code Duplication
        if (isset($tokens[$openParenthesis]['nested_parenthesis'])) {
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
312
            $nestedParenthesisCount = count($tokens[$openParenthesis]['nested_parenthesis']) + 1;
313
        }
314
315
        $parameters = array();
316
        $nextComma  = $openParenthesis;
317
        $paramStart = $openParenthesis + 1;
318
        $cnt        = 1;
319
        while ($nextComma = $phpcsFile->findNext(array(T_COMMA, T_CLOSE_PARENTHESIS, T_OPEN_SHORT_ARRAY), $nextComma + 1, $closeParenthesis + 1)) {
320
            // Ignore anything within short array definition brackets.
321
            if (
322
                $tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
323
                &&
324
                ( isset($tokens[$nextComma]['bracket_opener']) && $tokens[$nextComma]['bracket_opener'] === $nextComma )
325
                &&
326
                isset($tokens[$nextComma]['bracket_closer'])
327
            ) {
328
                // Skip forward to the end of the short array definition.
329
                $nextComma = $tokens[$nextComma]['bracket_closer'];
330
                continue;
331
            }
332
333
            // Ignore comma's at a lower nesting level.
334
            if (
335
                $tokens[$nextComma]['type'] === 'T_COMMA'
336
                &&
337
                isset($tokens[$nextComma]['nested_parenthesis'])
338
                &&
339
                count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
340
            ) {
341
                continue;
342
            }
343
344
            // Ignore closing parenthesis if not 'ours'.
345
            if ($tokens[$nextComma]['type'] === 'T_CLOSE_PARENTHESIS' && $nextComma !== $closeParenthesis) {
346
                continue;
347
            }
348
349
            // Ok, we've reached the end of the parameter.
350
            $parameters[$cnt]['start'] = $paramStart;
351
            $parameters[$cnt]['end']   = $nextComma - 1;
352
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
353
354
            // Check if there are more tokens before the closing parenthesis.
355
            // Prevents code like the following from setting a third parameter:
356
            // 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...
357
            $hasNextParam = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closeParenthesis, true, null, true);
358
            if ($hasNextParam === false) {
359
                break;
360
            }
361
362
            // Prepare for the next parameter.
363
            $paramStart = $nextComma + 1;
364
            $cnt++;
365
        }
366
367
        return $parameters;
368
    }
369
370
371
    /**
372
     * Get information on a specific parameter passed to a function call.
373
     *
374
     * Expects to be passed the T_STRING stack pointer for the function call.
375
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
376
     *
377
     * Will return a array with the start token pointer, end token pointer and the raw value
378
     * of the parameter at a specific offset.
379
     * If the specified parameter is not found, will return false.
380
     *
381
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
382
     * @param int                  $stackPtr    The position of the function call token.
383
     * @param int                  $paramOffset The 1-based index position of the parameter to retrieve.
384
     *
385
     * @return array|false
386
     */
387
    public function getFunctionCallParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
388
    {
389
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
390
391
        if (isset($parameters[$paramOffset]) === false) {
392
            return false;
393
        }
394
        else {
395
            return $parameters[$paramOffset];
396
        }
397
    }
398
399
400
    /**
401
     * Verify whether a token is within a scoped condition.
402
     *
403
     * If the optional $validScopes parameter has been passed, the function
404
     * will check that the token has at least one condition which is of a
405
     * type defined in $validScopes.
406
     *
407
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
408
     * @param int                  $stackPtr    The position of the token.
409
     * @param array|int            $validScopes Optional. Array of valid scopes
410
     *                                          or int value of a valid scope.
411
     *
412
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
413
     *              If the $scopeTypes are set: True if *one* of the conditions is a
414
     *              valid scope, false otherwise.
415
     */
416
    public function tokenHasScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
417
    {
418
        $tokens = $phpcsFile->getTokens();
419
420
        // Check for the existence of the token.
421
        if (isset($tokens[$stackPtr]) === false) {
422
            return false;
423
        }
424
425
        // No conditions = no scope.
426
        if (empty($tokens[$stackPtr]['conditions'])) {
427
            return false;
428
        }
429
430
        // Ok, there are conditions, do we have to check for specific ones ?
431
        if (isset($validScopes) === false) {
432
            return true;
433
        }
434
435
        if (is_int($validScopes)) {
436
            // Received an integer, so cast to array.
437
            $validScopes = (array) $validScopes;
438
        }
439
440
        if (empty($validScopes) || is_array($validScopes) === false) {
441
            // No valid scope types received, so will not comply.
442
            return false;
443
        }
444
445
        // Check for required scope types.
446
        foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
447
            if (in_array($type, $validScopes, true)) {
448
                return true;
449
            }
450
        }
451
452
        return false;
453
    }
454
455
456
    /**
457
     * Verify whether a token is within a class scope.
458
     *
459
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
460
     * @param int                  $stackPtr  The position of the token.
461
     * @param bool                 $strict    Whether to strictly check for the T_CLASS
462
     *                                        scope or also accept interfaces and traits
463
     *                                        as scope.
464
     *
465
     * @return bool True if within class scope, false otherwise.
466
     */
467
    public function inClassScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
468
    {
469
        $validScopes = array(T_CLASS);
470
        if ($strict === false) {
471
            $validScopes[] = T_INTERFACE;
472
            $validScopes[] = T_TRAIT;
473
        }
474
475
        return $this->tokenHasScope($phpcsFile, $stackPtr, $validScopes);
476
    }
477
478
479
    /**
480
     * Returns the fully qualified class name for a new class instantiation.
481
     *
482
     * Returns an empty string if the class name could not be reliably inferred.
483
     *
484
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
485
     * @param int                  $stackPtr  The position of a T_NEW token.
486
     *
487
     * @return string
488
     */
489
    public function getFQClassNameFromNewToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
490
    {
491
        $tokens = $phpcsFile->getTokens();
492
493
        // Check for the existence of the token.
494
        if (isset($tokens[$stackPtr]) === false) {
495
            return '';
496
        }
497
498
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
499
            return '';
500
        }
501
502
        $find = array(
503
                 T_NS_SEPARATOR,
504
                 T_STRING,
505
                 T_NAMESPACE,
506
                 T_WHITESPACE,
507
                );
508
509
        $start = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
510
        // Bow out if the next token is a variable as we don't know where it was defined.
511
        if ($tokens[$start]['code'] === T_VARIABLE) {
512
            return '';
513
        }
514
515
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
516
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
517
        $className = trim($className);
518
519
        return $this->getFQName($phpcsFile, $stackPtr, $className);
520
    }
521
522
523
    /**
524
     * Returns the fully qualified name of the class that the specified class extends.
525
     *
526
     * Returns an empty string if the class does not extend another class or if
527
     * the class name could not be reliably inferred.
528
     *
529
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
530
     * @param int                  $stackPtr  The position of a T_CLASS token.
531
     *
532
     * @return string
533
     */
534
    public function getFQExtendedClassName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
535
    {
536
        $tokens = $phpcsFile->getTokens();
537
538
        // Check for the existence of the token.
539
        if (isset($tokens[$stackPtr]) === false) {
540
            return '';
541
        }
542
543
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
544
            return '';
545
        }
546
547
        $extends = $phpcsFile->findExtendedClassName($stackPtr);
548
        if (empty($extends) || is_string($extends) === false) {
549
            return '';
550
        }
551
552
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
553
    }
554
555
556
    /**
557
     * Returns the class name for the static usage of a class.
558
     * This can be a call to a method, the use of a property or constant.
559
     *
560
     * Returns an empty string if the class name could not be reliably inferred.
561
     *
562
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
563
     * @param int                  $stackPtr  The position of a T_NEW token.
564
     *
565
     * @return string
566
     */
567
    public function getFQClassNameFromDoubleColonToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
568
    {
569
        $tokens = $phpcsFile->getTokens();
570
571
        // Check for the existence of the token.
572
        if (isset($tokens[$stackPtr]) === false) {
573
            return '';
574
        }
575
576
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
577
            return '';
578
        }
579
580
        // Nothing to do if previous token is a variable as we don't know where it was defined.
581
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
582
            return '';
583
        }
584
585
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
586
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
587
            return '';
588
        }
589
590
        // Get the classname from the class declaration if self is used.
591
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
592
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
593
            if ($classDeclarationPtr === false) {
594
                return '';
595
            }
596
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
597
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
598
        }
599
600
        $find = array(
601
                 T_NS_SEPARATOR,
602
                 T_STRING,
603
                 T_NAMESPACE,
604
                 T_WHITESPACE,
605
                );
606
607
        $start     = ($phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true) + 1);
608
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
609
        $className = trim($className);
610
611
        return $this->getFQName($phpcsFile, $stackPtr, $className);
612
    }
613
614
615
    /**
616
     * Get the Fully Qualified name for a class/function/constant etc.
617
     *
618
     * Checks if a class/function/constant name is already fully qualified and
619
     * if not, enrich it with the relevant namespace information.
620
     *
621
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
622
     * @param int                  $stackPtr  The position of the token.
623
     * @param string               $name      The class / function / constant name.
624
     *
625
     * @return string
626
     */
627
    public function getFQName(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
628
    {
629
        if (strpos($name, '\\' ) === 0) {
630
            // Already fully qualified.
631
            return $name;
632
        }
633
634
        // Remove the namespace keyword if used.
635
        if (strpos($name, 'namespace\\') === 0) {
636
            $name = substr($name, 10);
637
        }
638
639
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
640
641
        if ($namespace === '') {
642
            return '\\' . $name;
643
        }
644
        else {
645
            return '\\' . $namespace . '\\' . $name;
646
        }
647
    }
648
649
650
    /**
651
     * Is the class/function/constant name namespaced or global ?
652
     *
653
     * @param string $FQName Fully Qualified name of a class, function etc.
654
     *                       I.e. should always start with a `\` !
655
     *
656
     * @return bool True if namespaced, false if global.
657
     */
658
    public function isNamespaced($FQName) {
659
        if (strpos($FQName, '\\') !== 0) {
660
            throw new PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
661
        }
662
663
        return (strpos(substr($FQName, 1), '\\') !== false);
664
    }
665
666
667
    /**
668
     * Determine the namespace name an arbitrary token lives in.
669
     *
670
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
671
     * @param int                  $stackPtr  The token position for which to determine the namespace.
672
     *
673
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
674
     */
675
    public function determineNamespace(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
676
    {
677
        $tokens = $phpcsFile->getTokens();
678
679
        // Check for the existence of the token.
680
        if (isset($tokens[$stackPtr]) === false) {
681
            return '';
682
        }
683
684
        // Check for scoped namespace {}.
685
        if (empty($tokens[$stackPtr]['conditions']) === false) {
686
            foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
687
                if ($type === T_NAMESPACE) {
688
                    $namespace = $this->getDeclaredNamespaceName($phpcsFile, $pointer);
689
                    if ($namespace !== false) {
690
                        return $namespace;
691
                    }
692
                    break; // Nested namespaces is not possible.
693
                }
694
            }
695
        }
696
697
        /*
698
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
699
         * Keeping in mind that:
700
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
701
         * - the namespace keyword can also be used as part of a function/method call and such.
702
         * - that a non-named namespace resolves to the global namespace.
703
         */
704
        $previousNSToken = $stackPtr;
705
        $namespace       = false;
706
        do {
707
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, $previousNSToken -1);
708
709
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
710
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] = $previousNSToken) {
711
                break;
712
            }
713
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
714
715
        } while ($namespace === false && $previousNSToken !== false);
716
717
        // If we still haven't got a namespace, return an empty string.
718
        if ($namespace === false) {
719
            return '';
720
        }
721
        else {
722
            return $namespace;
723
        }
724
    }
725
726
    /**
727
     * Get the complete namespace name for a namespace declaration.
728
     *
729
     * For hierarchical namespaces, the name will be composed of several tokens,
730
     * i.e. MyProject\Sub\Level which will be returned together as one string.
731
     *
732
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
733
     * @param int|bool             $stackPtr  The position of a T_NAMESPACE token.
734
     *
735
     * @return string|false Namespace name or false if not a namespace declaration.
736
     *                      Namespace name can be an empty string for global namespace declaration.
737
     */
738
    public function getDeclaredNamespaceName(PHP_CodeSniffer_File $phpcsFile, $stackPtr )
739
    {
740
        $tokens = $phpcsFile->getTokens();
741
742
        // Check for the existence of the token.
743
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
744
            return false;
745
        }
746
747
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
748
            return false;
749
        }
750
751
        if ($tokens[$stackPtr + 1]['code'] === T_NS_SEPARATOR) {
752
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
753
            return false;
754
        }
755
756
        $nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
757
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
758
            // Declaration for global namespace when using multiple namespaces in a file.
759
            // I.e.: namespace {}
760
            return '';
761
        }
762
763
        // Ok, this should be a namespace declaration, so get all the parts together.
764
        $validTokens = array(
765
                        T_STRING,
766
                        T_NS_SEPARATOR,
767
                        T_WHITESPACE,
768
                       );
769
770
        $namespaceName = '';
771
        while(in_array($tokens[$nextToken]['code'], $validTokens, true) === true) {
772
            $namespaceName .= trim($tokens[$nextToken]['content']);
773
            $nextToken++;
774
        }
775
776
        return $namespaceName;
777
    }
778
779
780
    /**
781
     * Returns the method parameters for the specified T_FUNCTION token.
782
     *
783
     * Each parameter is in the following format:
784
     *
785
     * <code>
786
     *   0 => array(
787
     *         'name'              => '$var',  // The variable name.
788
     *         'pass_by_reference' => false,   // Passed by reference.
789
     *         'type_hint'         => string,  // Type hint for array or custom type
790
     *        )
791
     * </code>
792
     *
793
     * Parameters with default values have an additional array index of
794
     * 'default' with the value of the default as a string.
795
     *
796
     * {@internal Duplicate of same method as contained in the `PHP_CodeSniffer_File`
797
     * class, but with some improvements which will probably be introduced in
798
     * PHPCS 2.7.1/2.8. {@see https://github.com/squizlabs/PHP_CodeSniffer/pull/1117}
799
     *
800
     * Once the minimum supported PHPCS version for this sniff library goes beyond
801
     * that, this method can be removed and calls to it replaced with
802
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.
803
     *
804
     * Last synced with PHPCS version: PHPCS 2.7.}}
805
     *
806
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
807
     * @param int $stackPtr The position in the stack of the T_FUNCTION token
808
     *                      to acquire the parameters for.
809
     *
810
     * @return array|false
811
     * @throws PHP_CodeSniffer_Exception If the specified $stackPtr is not of
812
     *                                   type T_FUNCTION.
813
     */
814
    public function getMethodParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
815
    {
816
        $tokens = $phpcsFile->getTokens();
817
818
        // Check for the existence of the token.
819
        if (isset($tokens[$stackPtr]) === false) {
820
            return false;
821
        }
822
823
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION) {
824
            throw new PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION');
825
        }
826
827
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
828
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
829
830
        $vars            = array();
831
        $currVar         = null;
832
        $paramStart      = ($opener + 1);
833
        $defaultStart    = null;
834
        $paramCount      = 0;
835
        $passByReference = false;
836
        $variableLength  = false;
837
        $typeHint        = '';
838
839
        for ($i = $paramStart; $i <= $closer; $i++) {
840
            // Check to see if this token has a parenthesis or bracket opener. If it does
841
            // it's likely to be an array which might have arguments in it. This
842
            // could cause problems in our parsing below, so lets just skip to the
843
            // end of it.
844 View Code Duplication
            if (isset($tokens[$i]['parenthesis_opener']) === true) {
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
845
                // Don't do this if it's the close parenthesis for the method.
846
                if ($i !== $tokens[$i]['parenthesis_closer']) {
847
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
848
                }
849
            }
850
851 View Code Duplication
            if (isset($tokens[$i]['bracket_opener']) === true) {
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
852
                // Don't do this if it's the close parenthesis for the method.
853
                if ($i !== $tokens[$i]['bracket_closer']) {
854
                    $i = ($tokens[$i]['bracket_closer'] + 1);
855
                }
856
            }
857
858
            switch ($tokens[$i]['code']) {
859
            case T_BITWISE_AND:
860
                $passByReference = true;
861
                break;
862
            case T_VARIABLE:
863
                $currVar = $i;
864
                break;
865
            case T_ELLIPSIS:
866
                $variableLength = true;
867
                break;
868
            case T_ARRAY_HINT:
869
            case T_CALLABLE:
870
                $typeHint = $tokens[$i]['content'];
871
                break;
872
            case T_SELF:
873
            case T_PARENT:
874
            case T_STATIC:
875
                // Self is valid, the others invalid, but were probably intended as type hints.
876
                if (isset($defaultStart) === false) {
877
                    $typeHint = $tokens[$i]['content'];
878
                }
879
                break;
880
            case T_STRING:
881
                // This is a string, so it may be a type hint, but it could
882
                // also be a constant used as a default value.
883
                $prevComma = false;
884 View Code Duplication
                for ($t = $i; $t >= $opener; $t--) {
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
885
                    if ($tokens[$t]['code'] === T_COMMA) {
886
                        $prevComma = $t;
887
                        break;
888
                    }
889
                }
890
891
                if ($prevComma !== false) {
892
                    $nextEquals = false;
893 View Code Duplication
                    for ($t = $prevComma; $t < $i; $t++) {
1 ignored issue
show
This code seems to be duplicated across your project.

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

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

Loading history...
894
                        if ($tokens[$t]['code'] === T_EQUAL) {
895
                            $nextEquals = $t;
896
                            break;
897
                        }
898
                    }
899
900
                    if ($nextEquals !== false) {
901
                        break;
902
                    }
903
                }
904
905
                if ($defaultStart === null) {
906
                    $typeHint .= $tokens[$i]['content'];
907
                }
908
                break;
909
            case T_NS_SEPARATOR:
910
                // Part of a type hint or default value.
911
                if ($defaultStart === null) {
912
                    $typeHint .= $tokens[$i]['content'];
913
                }
914
                break;
915
            case T_CLOSE_PARENTHESIS:
916
            case T_COMMA:
917
                // If it's null, then there must be no parameters for this
918
                // method.
919
                if ($currVar === null) {
920
                    continue;
921
                }
922
923
                $vars[$paramCount]         = array();
924
                $vars[$paramCount]['name'] = $tokens[$currVar]['content'];
925
926
                if ($defaultStart !== null) {
927
                    $vars[$paramCount]['default']
928
                        = $phpcsFile->getTokensAsString(
929
                            $defaultStart,
930
                            ($i - $defaultStart)
931
                        );
932
                }
933
934
                $rawContent = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
935
936
                $vars[$paramCount]['pass_by_reference'] = $passByReference;
937
                $vars[$paramCount]['variable_length']   = $variableLength;
938
                $vars[$paramCount]['type_hint']         = $typeHint;
939
                $vars[$paramCount]['raw'] = $rawContent;
940
941
                // Reset the vars, as we are about to process the next parameter.
942
                $defaultStart    = null;
943
                $paramStart      = ($i + 1);
944
                $passByReference = false;
945
                $variableLength  = false;
946
                $typeHint        = '';
947
948
                $paramCount++;
949
                break;
950
            case T_EQUAL:
951
                $defaultStart = ($i + 1);
952
                break;
953
            }//end switch
954
        }//end for
955
956
        return $vars;
957
958
    }//end getMethodParameters()
959
960
961
    /**
962
     * Get the hash algorithm name from the parameter in a hash function call.
963
     *
964
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
965
     * @param int                  $stackPtr  The position of the T_STRING function token.
966
     *
967
     * @return string|false The algorithm name without quotes if this was a relevant hash
968
     *                      function call or false if it was not.
969
     */
970
    public function getHashAlgorithmParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
971
    {
972
        $tokens = $phpcsFile->getTokens();
973
974
        // Check for the existence of the token.
975
        if (isset($tokens[$stackPtr]) === false) {
976
            return false;
977
        }
978
979
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
980
            return false;
981
        }
982
983
        $functionName   = $tokens[$stackPtr]['content'];
984
        $functionNameLc = strtolower($functionName);
985
986
        // Bow out if not one of the functions we're targetting.
987
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
988
            return false;
989
        }
990
991
        // Get the parameter from the function call which should contain the algorithm name.
992
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
993
        if ($algoParam === false) {
994
            return false;
995
        }
996
997
        /**
998
         * Algorithm is a T_CONSTANT_ENCAPSED_STRING, so we need to remove the quotes.
999
         */
1000
        $algo = strtolower(trim($algoParam['raw']));
1001
        $algo = $this->stripQuotes($algo);
1002
1003
        return $algo;
1004
    }
1005
1006
}//end class
1007