Completed
Push — php72-deprecations ( e162fc...c8076f )
by Wim
10s
created

Sniff.php (11 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
     *                                          Pass the T_.. constant(s) for the
412
     *                                          desired scope to this parameter.
413
     *
414
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
415
     *              If the $scopeTypes are set: True if *one* of the conditions is a
416
     *              valid scope, false otherwise.
417
     */
418
    public function tokenHasScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
419
    {
420
        $tokens = $phpcsFile->getTokens();
421
422
        // Check for the existence of the token.
423
        if (isset($tokens[$stackPtr]) === false) {
424
            return false;
425
        }
426
427
        // No conditions = no scope.
428
        if (empty($tokens[$stackPtr]['conditions'])) {
429
            return false;
430
        }
431
432
        // Ok, there are conditions, do we have to check for specific ones ?
433
        if (isset($validScopes) === false) {
434
            return true;
435
        }
436
437
        if (is_int($validScopes)) {
438
            // Received an integer, so cast to array.
439
            $validScopes = (array) $validScopes;
440
        }
441
442
        if (empty($validScopes) || is_array($validScopes) === false) {
443
            // No valid scope types received, so will not comply.
444
            return false;
445
        }
446
447
        // Check for required scope types.
448
        foreach ($tokens[$stackPtr]['conditions'] as $pointer => $tokenCode) {
449
            if (in_array($tokenCode, $validScopes, true)) {
450
                return true;
451
            }
452
        }
453
454
        return false;
455
    }
456
457
458
    /**
459
     * Verify whether a token is within a class scope.
460
     *
461
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
462
     * @param int                  $stackPtr  The position of the token.
463
     * @param bool                 $strict    Whether to strictly check for the T_CLASS
464
     *                                        scope or also accept interfaces and traits
465
     *                                        as scope.
466
     *
467
     * @return bool True if within class scope, false otherwise.
468
     */
469
    public function inClassScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
470
    {
471
        $validScopes = array(T_CLASS);
472
        if ($strict === false) {
473
            $validScopes[] = T_INTERFACE;
474
            $validScopes[] = T_TRAIT;
475
        }
476
477
        return $this->tokenHasScope($phpcsFile, $stackPtr, $validScopes);
478
    }
479
480
481
    /**
482
     * Verify whether a token is within a scoped use statement.
483
     *
484
     * PHPCS cross-version compatibility method.
485
     *
486
     * In PHPCS 1.x no conditions are set for a scoped use statement.
487
     * This method works around that limitation.
488
     *
489
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
490
     * @param int                  $stackPtr  The position of the token.
491
     *
492
     * @return bool True if within use scope, false otherwise.
493
     */
494
    public function inUseScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
495
    {
496
        static $isLowPHPCS, $ignoreTokens;
497
498
        if (isset($isLowPHPCS) === false) {
499
            $isLowPHPCS = version_compare(PHP_CodeSniffer::VERSION, '2.0', '<');
500
        }
501
        if (isset($ignoreTokens) === false) {
502
            $ignoreTokens              = PHP_CodeSniffer_Tokens::$emptyTokens;
503
            $ignoreTokens[T_STRING]    = T_STRING;
504
            $ignoreTokens[T_AS]        = T_AS;
505
            $ignoreTokens[T_PUBLIC]    = T_PUBLIC;
506
            $ignoreTokens[T_PROTECTED] = T_PROTECTED;
507
            $ignoreTokens[T_PRIVATE]   = T_PRIVATE;
508
        }
509
510
        // PHPCS 2.0.
511
        if ($isLowPHPCS === false) {
512
            return $this->tokenHasScope($phpcsFile, $stackPtr, T_USE);
513
        } else {
514
            // PHPCS 1.x.
515
            $tokens         = $phpcsFile->getTokens();
516
            $maybeCurlyOpen = $phpcsFile->findPrevious($ignoreTokens, ($stackPtr - 1), null, true);
517
            if ($tokens[$maybeCurlyOpen]['code'] === T_OPEN_CURLY_BRACKET) {
518
                $maybeUseStatement = $phpcsFile->findPrevious($ignoreTokens, ($maybeCurlyOpen - 1), null, true);
519
                if ($tokens[$maybeUseStatement]['code'] === T_USE) {
520
                    return true;
521
                }
522
            }
523
            return false;
524
        }
525
    }
526
527
528
    /**
529
     * Returns the fully qualified class name for a new class instantiation.
530
     *
531
     * Returns an empty string if the class name could not be reliably inferred.
532
     *
533
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
534
     * @param int                  $stackPtr  The position of a T_NEW token.
535
     *
536
     * @return string
537
     */
538
    public function getFQClassNameFromNewToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
539
    {
540
        $tokens = $phpcsFile->getTokens();
541
542
        // Check for the existence of the token.
543
        if (isset($tokens[$stackPtr]) === false) {
544
            return '';
545
        }
546
547
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
548
            return '';
549
        }
550
551
        $find = array(
552
                 T_NS_SEPARATOR,
553
                 T_STRING,
554
                 T_NAMESPACE,
555
                 T_WHITESPACE,
556
                );
557
558
        $start = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
559
        // Bow out if the next token is a variable as we don't know where it was defined.
560
        if ($tokens[$start]['code'] === T_VARIABLE) {
561
            return '';
562
        }
563
564
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
565
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
566
        $className = trim($className);
567
568
        return $this->getFQName($phpcsFile, $stackPtr, $className);
569
    }
570
571
572
    /**
573
     * Returns the fully qualified name of the class that the specified class extends.
574
     *
575
     * Returns an empty string if the class does not extend another class or if
576
     * the class name could not be reliably inferred.
577
     *
578
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
579
     * @param int                  $stackPtr  The position of a T_CLASS token.
580
     *
581
     * @return string
582
     */
583
    public function getFQExtendedClassName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
584
    {
585
        $tokens = $phpcsFile->getTokens();
586
587
        // Check for the existence of the token.
588
        if (isset($tokens[$stackPtr]) === false) {
589
            return '';
590
        }
591
592
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
593
            return '';
594
        }
595
596
        $extends = $phpcsFile->findExtendedClassName($stackPtr);
597
        if (empty($extends) || is_string($extends) === false) {
598
            return '';
599
        }
600
601
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
602
    }
603
604
605
    /**
606
     * Returns the class name for the static usage of a class.
607
     * This can be a call to a method, the use of a property or constant.
608
     *
609
     * Returns an empty string if the class name could not be reliably inferred.
610
     *
611
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
612
     * @param int                  $stackPtr  The position of a T_NEW token.
613
     *
614
     * @return string
615
     */
616
    public function getFQClassNameFromDoubleColonToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
617
    {
618
        $tokens = $phpcsFile->getTokens();
619
620
        // Check for the existence of the token.
621
        if (isset($tokens[$stackPtr]) === false) {
622
            return '';
623
        }
624
625
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
626
            return '';
627
        }
628
629
        // Nothing to do if previous token is a variable as we don't know where it was defined.
630
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
631
            return '';
632
        }
633
634
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
635
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
636
            return '';
637
        }
638
639
        // Get the classname from the class declaration if self is used.
640
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
641
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
642
            if ($classDeclarationPtr === false) {
643
                return '';
644
            }
645
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
646
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
647
        }
648
649
        $find = array(
650
                 T_NS_SEPARATOR,
651
                 T_STRING,
652
                 T_NAMESPACE,
653
                 T_WHITESPACE,
654
                );
655
656
        $start     = ($phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true) + 1);
657
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
658
        $className = trim($className);
659
660
        return $this->getFQName($phpcsFile, $stackPtr, $className);
661
    }
662
663
664
    /**
665
     * Get the Fully Qualified name for a class/function/constant etc.
666
     *
667
     * Checks if a class/function/constant name is already fully qualified and
668
     * if not, enrich it with the relevant namespace information.
669
     *
670
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
671
     * @param int                  $stackPtr  The position of the token.
672
     * @param string               $name      The class / function / constant name.
673
     *
674
     * @return string
675
     */
676
    public function getFQName(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
677
    {
678
        if (strpos($name, '\\' ) === 0) {
679
            // Already fully qualified.
680
            return $name;
681
        }
682
683
        // Remove the namespace keyword if used.
684
        if (strpos($name, 'namespace\\') === 0) {
685
            $name = substr($name, 10);
686
        }
687
688
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
689
690
        if ($namespace === '') {
691
            return '\\' . $name;
692
        }
693
        else {
694
            return '\\' . $namespace . '\\' . $name;
695
        }
696
    }
697
698
699
    /**
700
     * Is the class/function/constant name namespaced or global ?
701
     *
702
     * @param string $FQName Fully Qualified name of a class, function etc.
703
     *                       I.e. should always start with a `\` !
704
     *
705
     * @return bool True if namespaced, false if global.
706
     */
707
    public function isNamespaced($FQName) {
708
        if (strpos($FQName, '\\') !== 0) {
709
            throw new PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
710
        }
711
712
        return (strpos(substr($FQName, 1), '\\') !== false);
713
    }
714
715
716
    /**
717
     * Determine the namespace name an arbitrary token lives in.
718
     *
719
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
720
     * @param int                  $stackPtr  The token position for which to determine the namespace.
721
     *
722
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
723
     */
724
    public function determineNamespace(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
        // Check for scoped namespace {}.
734
        if (empty($tokens[$stackPtr]['conditions']) === false) {
735
            foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
736
                if ($type === T_NAMESPACE) {
737
                    $namespace = $this->getDeclaredNamespaceName($phpcsFile, $pointer);
738
                    if ($namespace !== false) {
739
                        return $namespace;
740
                    }
741
                    break; // Nested namespaces is not possible.
742
                }
743
            }
744
        }
745
746
        /*
747
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
748
         * Keeping in mind that:
749
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
750
         * - the namespace keyword can also be used as part of a function/method call and such.
751
         * - that a non-named namespace resolves to the global namespace.
752
         */
753
        $previousNSToken = $stackPtr;
754
        $namespace       = false;
755
        do {
756
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, $previousNSToken -1);
757
758
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
759
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] = $previousNSToken) {
760
                break;
761
            }
762
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
763
764
        } while ($namespace === false && $previousNSToken !== false);
765
766
        // If we still haven't got a namespace, return an empty string.
767
        if ($namespace === false) {
768
            return '';
769
        }
770
        else {
771
            return $namespace;
772
        }
773
    }
774
775
    /**
776
     * Get the complete namespace name for a namespace declaration.
777
     *
778
     * For hierarchical namespaces, the name will be composed of several tokens,
779
     * i.e. MyProject\Sub\Level which will be returned together as one string.
780
     *
781
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
782
     * @param int|bool             $stackPtr  The position of a T_NAMESPACE token.
783
     *
784
     * @return string|false Namespace name or false if not a namespace declaration.
785
     *                      Namespace name can be an empty string for global namespace declaration.
786
     */
787
    public function getDeclaredNamespaceName(PHP_CodeSniffer_File $phpcsFile, $stackPtr )
788
    {
789
        $tokens = $phpcsFile->getTokens();
790
791
        // Check for the existence of the token.
792
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
793
            return false;
794
        }
795
796
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
797
            return false;
798
        }
799
800
        if ($tokens[$stackPtr + 1]['code'] === T_NS_SEPARATOR) {
801
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
802
            return false;
803
        }
804
805
        $nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
806
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
807
            // Declaration for global namespace when using multiple namespaces in a file.
808
            // I.e.: namespace {}
809
            return '';
810
        }
811
812
        // Ok, this should be a namespace declaration, so get all the parts together.
813
        $validTokens = array(
814
                        T_STRING,
815
                        T_NS_SEPARATOR,
816
                        T_WHITESPACE,
817
                       );
818
819
        $namespaceName = '';
820
        while(in_array($tokens[$nextToken]['code'], $validTokens, true) === true) {
821
            $namespaceName .= trim($tokens[$nextToken]['content']);
822
            $nextToken++;
823
        }
824
825
        return $namespaceName;
826
    }
827
828
829
    /**
830
     * Returns the method parameters for the specified T_FUNCTION token.
831
     *
832
     * Each parameter is in the following format:
833
     *
834
     * <code>
835
     *   0 => array(
836
     *         'name'              => '$var',  // The variable name.
837
     *         'pass_by_reference' => false,   // Passed by reference.
838
     *         'type_hint'         => string,  // Type hint for array or custom type
839
     *         'nullable_type'     => bool,    // Whether the type given in the type hint is nullable
840
     *         'type_hint'         => string,  // Type hint for array or custom type
841
     *         'raw'               => string,  // Raw content of the tokens for the parameter
842
     *        )
843
     * </code>
844
     *
845
     * Parameters with default values have an additional array index of
846
     * 'default' with the value of the default as a string.
847
     *
848
     * {@internal Duplicate of same method as contained in the `PHP_CodeSniffer_File`
849
     * class, but with some improvements which will probably be introduced in
850
     * PHPCS 2.7.1/2.8. {@see https://github.com/squizlabs/PHP_CodeSniffer/pull/1117}
851
     * and {@see https://github.com/squizlabs/PHP_CodeSniffer/pull/1193}
852
     *
853
     * Once the minimum supported PHPCS version for this sniff library goes beyond
854
     * that, this method can be removed and calls to it replaced with
855
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.
856
     *
857
     * Last synced with PHPCS version: PHPCS 2.7.}}
858
     *
859
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
860
     * @param int                  $stackPtr  The position in the stack of the
861
     *                                        T_FUNCTION token to acquire the
862
     *                                        parameters for.
863
     *
864
     * @return array|false
865
     * @throws PHP_CodeSniffer_Exception If the specified $stackPtr is not of
866
     *                                   type T_FUNCTION.
867
     */
868
    public function getMethodParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
869
    {
870
        $tokens = $phpcsFile->getTokens();
871
872
        // Check for the existence of the token.
873
        if (isset($tokens[$stackPtr]) === false) {
874
            return false;
875
        }
876
877
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION) {
878
            throw new PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION');
879
        }
880
881
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
882
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
883
884
        $vars            = array();
885
        $currVar         = null;
886
        $paramStart      = ($opener + 1);
887
        $defaultStart    = null;
888
        $paramCount      = 0;
889
        $passByReference = false;
890
        $variableLength  = false;
891
        $typeHint        = '';
892
        $nullableType    = false;
893
894
        for ($i = $paramStart; $i <= $closer; $i++) {
895
            // Check to see if this token has a parenthesis or bracket opener. If it does
896
            // it's likely to be an array which might have arguments in it. This
897
            // could cause problems in our parsing below, so lets just skip to the
898
            // end of it.
899 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...
900
                // Don't do this if it's the close parenthesis for the method.
901
                if ($i !== $tokens[$i]['parenthesis_closer']) {
902
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
903
                }
904
            }
905
906 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...
907
                // Don't do this if it's the close parenthesis for the method.
908
                if ($i !== $tokens[$i]['bracket_closer']) {
909
                    $i = ($tokens[$i]['bracket_closer'] + 1);
910
                }
911
            }
912
913
            switch ($tokens[$i]['code']) {
914
            case T_BITWISE_AND:
915
                $passByReference = true;
916
                break;
917
            case T_VARIABLE:
918
                $currVar = $i;
919
                break;
920
            case T_ELLIPSIS:
921
                $variableLength = true;
922
                break;
923
            case T_ARRAY_HINT:
924
            case T_CALLABLE:
925
                $typeHint = $tokens[$i]['content'];
926
                break;
927
            case T_SELF:
928
            case T_PARENT:
929 View Code Duplication
            case T_STATIC:
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...
930
                // Self is valid, the others invalid, but were probably intended as type hints.
931
                if ($defaultStart === null) {
932
                    $typeHint = $tokens[$i]['content'];
933
                }
934
                break;
935
            case T_STRING:
936
                // This is a string, so it may be a type hint, but it could
937
                // also be a constant used as a default value.
938
                $prevComma = false;
939 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...
940
                    if ($tokens[$t]['code'] === T_COMMA) {
941
                        $prevComma = $t;
942
                        break;
943
                    }
944
                }
945
946
                if ($prevComma !== false) {
947
                    $nextEquals = false;
948 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...
949
                        if ($tokens[$t]['code'] === T_EQUAL) {
950
                            $nextEquals = $t;
951
                            break;
952
                        }
953
                    }
954
955
                    if ($nextEquals !== false) {
956
                        break;
957
                    }
958
                }
959
960
                if ($defaultStart === null) {
961
                    $typeHint .= $tokens[$i]['content'];
962
                }
963
                break;
964 View Code Duplication
            case T_NS_SEPARATOR:
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...
965
                // Part of a type hint or default value.
966
                if ($defaultStart === null) {
967
                    $typeHint .= $tokens[$i]['content'];
968
                }
969
                break;
970
            case T_INLINE_THEN:
971
                if ($defaultStart === null) {
972
                    $nullableType = true;
973
                    $typeHint    .= $tokens[$i]['content'];
974
                }
975
                break;
976
            case T_CLOSE_PARENTHESIS:
977
            case T_COMMA:
978
                // If it's null, then there must be no parameters for this
979
                // method.
980
                if ($currVar === null) {
981
                    continue;
982
                }
983
984
                $vars[$paramCount]         = array();
985
                $vars[$paramCount]['name'] = $tokens[$currVar]['content'];
986
987
                if ($defaultStart !== null) {
988
                    $vars[$paramCount]['default']
989
                        = $phpcsFile->getTokensAsString(
990
                            $defaultStart,
991
                            ($i - $defaultStart)
992
                        );
993
                }
994
995
                $rawContent = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
996
997
                $vars[$paramCount]['pass_by_reference'] = $passByReference;
998
                $vars[$paramCount]['variable_length']   = $variableLength;
999
                $vars[$paramCount]['type_hint']         = $typeHint;
1000
                $vars[$paramCount]['nullable_type']     = $nullableType;
1001
                $vars[$paramCount]['raw']               = $rawContent;
1002
1003
                // Reset the vars, as we are about to process the next parameter.
1004
                $defaultStart    = null;
1005
                $paramStart      = ($i + 1);
1006
                $passByReference = false;
1007
                $variableLength  = false;
1008
                $typeHint        = '';
1009
                $nullableType    = false;
1010
1011
                $paramCount++;
1012
                break;
1013
            case T_EQUAL:
1014
                $defaultStart = ($i + 1);
1015
                break;
1016
            }//end switch
1017
        }//end for
1018
1019
        return $vars;
1020
1021
    }//end getMethodParameters()
1022
1023
1024
    /**
1025
     * Get the hash algorithm name from the parameter in a hash function call.
1026
     *
1027
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
1028
     * @param int                  $stackPtr  The position of the T_STRING function token.
1029
     *
1030
     * @return string|false The algorithm name without quotes if this was a relevant hash
1031
     *                      function call or false if it was not.
1032
     */
1033
    public function getHashAlgorithmParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
1034
    {
1035
        $tokens = $phpcsFile->getTokens();
1036
1037
        // Check for the existence of the token.
1038
        if (isset($tokens[$stackPtr]) === false) {
1039
            return false;
1040
        }
1041
1042
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
1043
            return false;
1044
        }
1045
1046
        $functionName   = $tokens[$stackPtr]['content'];
1047
        $functionNameLc = strtolower($functionName);
1048
1049
        // Bow out if not one of the functions we're targetting.
1050
        if (isset($this->hashAlgoFunctions[$functionNameLc]) === false) {
1051
            return false;
1052
        }
1053
1054
        // Get the parameter from the function call which should contain the algorithm name.
1055
        $algoParam = $this->getFunctionCallParameter($phpcsFile, $stackPtr, $this->hashAlgoFunctions[$functionNameLc]);
1056
        if ($algoParam === false) {
1057
            return false;
1058
        }
1059
1060
        /**
1061
         * Algorithm is a T_CONSTANT_ENCAPSED_STRING, so we need to remove the quotes.
1062
         */
1063
        $algo = strtolower(trim($algoParam['raw']));
1064
        $algo = $this->stripQuotes($algo);
1065
1066
        return $algo;
1067
    }
1068
1069
}//end class
1070