Completed
Push — master ( 1947a4...42d661 )
by Juliette
13s
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
/* The testVersion configuration variable may be in any of the following formats:
26
 * 1) Omitted/empty, in which case no version is specified.  This effectively
27
 *    disables all the checks provided by this standard.
28
 * 2) A single PHP version number, e.g. "5.4" in which case the standard checks that
29
 *    the code will run on that version of PHP (no deprecated features or newer
30
 *    features being used).
31
 * 3) A range, e.g. "5.0-5.5", in which case the standard checks the code will run
32
 *    on all PHP versions in that range, and that it doesn't use any features that
33
 *    were deprecated by the final version in the list, or which were not available
34
 *    for the first version in the list.
35
 * PHP version numbers should always be in Major.Minor format.  Both "5", "5.3.2"
36
 * would be treated as invalid, and ignored.
37
 * This standard doesn't support checking against PHP4, so the minimum version that
38
 * is recognised is "5.0".
39
 */
40
41
    private function getTestVersion()
42
    {
43
        /**
44
         * var $arrTestVersions will hold an array containing min/max version of PHP
45
         *   that we are checking against (see above).  If only a single version
46
         *   number is specified, then this is used as both the min and max.
47
         */
48
        static $arrTestVersions = array();
49
50
        $testVersion = trim(PHP_CodeSniffer::getConfigData('testVersion'));
51
52
        if (!isset($arrTestVersions[$testVersion]) && !empty($testVersion)) {
53
54
            $arrTestVersions[$testVersion] = array(null, null);
55
            if (preg_match('/^\d+\.\d+$/', $testVersion)) {
56
                $arrTestVersions[$testVersion] = array($testVersion, $testVersion);
57
            }
58
            elseif (preg_match('/^(\d+\.\d+)\s*-\s*(\d+\.\d+)$/', $testVersion,
59
                               $matches))
60
            {
61
                if (version_compare($matches[1], $matches[2], '>')) {
62
                    trigger_error("Invalid range in testVersion setting: '"
63
                                  . $testVersion . "'", E_USER_WARNING);
64
                }
65
                else {
66
                    $arrTestVersions[$testVersion] = array($matches[1], $matches[2]);
67
                }
68
            }
69
            elseif (!$testVersion == '') {
70
                trigger_error("Invalid testVersion setting: '" . $testVersion
71
                              . "'", E_USER_WARNING);
72
            }
73
        }
74
75
        if (isset($arrTestVersions[$testVersion])) {
76
            return $arrTestVersions[$testVersion];
77
        }
78
        else {
79
            return array(null, null);
80
        }
81
    }
82
83 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...
84
    {
85
        $testVersion = $this->getTestVersion();
86
        $testVersion = $testVersion[1];
87
88
        if (is_null($testVersion)
89
            || version_compare($testVersion, $phpVersion) >= 0
90
        ) {
91
            return true;
92
        } else {
93
            return false;
94
        }
95
    }//end supportsAbove()
96
97 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...
98
    {
99
        $testVersion = $this->getTestVersion();
100
        $testVersion = $testVersion[0];
101
102
        if (!is_null($testVersion)
103
            && version_compare($testVersion, $phpVersion) <= 0
104
        ) {
105
            return true;
106
        } else {
107
            return false;
108
        }
109
    }//end supportsBelow()
110
111
112
    /**
113
     * Strip quotes surrounding an arbitrary string.
114
     *
115
     * Intended for use with the content of a T_CONSTANT_ENCAPSED_STRING.
116
     *
117
     * @param string $string The raw string.
118
     *
119
     * @return string String without quotes around it.
120
     */
121
    public function stripQuotes($string) {
122
        return preg_replace('`^([\'"])(.*)\1$`Ds', '$2', $string);
123
    }
124
125
126
    /**
127
     * Returns the name(s) of the interface(s) that the specified class implements.
128
     *
129
     * Returns FALSE on error or if there are no implemented interface names.
130
     *
131
     * {@internal Duplicate of same method as introduced in PHPCS 2.7.
132
     * Once the minimum supported PHPCS version for this sniff library goes beyond
133
     * that, this method can be removed and call to it replaced with
134
     * `$phpcsFile->findImplementedInterfaceNames($stackPtr)` calls.}}
135
     *
136
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
137
     * @param int                  $stackPtr  The position of the class token.
138
     *
139
     * @return array|false
140
     */
141
    public function findImplementedInterfaceNames($phpcsFile, $stackPtr)
142
    {
143
        $tokens = $phpcsFile->getTokens();
144
145
        // Check for the existence of the token.
146
        if (isset($tokens[$stackPtr]) === false) {
147
            return false;
148
        }
149
150
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
151
            return false;
152
        }
153
154
        if (isset($tokens[$stackPtr]['scope_closer']) === false) {
155
            return false;
156
        }
157
158
        $classOpenerIndex = $tokens[$stackPtr]['scope_opener'];
159
        $implementsIndex  = $phpcsFile->findNext(T_IMPLEMENTS, $stackPtr, $classOpenerIndex);
160
        if ($implementsIndex === false) {
161
            return false;
162
        }
163
164
        $find = array(
165
                 T_NS_SEPARATOR,
166
                 T_STRING,
167
                 T_WHITESPACE,
168
                 T_COMMA,
169
                );
170
171
        $end  = $phpcsFile->findNext($find, ($implementsIndex + 1), ($classOpenerIndex + 1), true);
172
        $name = $phpcsFile->getTokensAsString(($implementsIndex + 1), ($end - $implementsIndex - 1));
173
        $name = trim($name);
174
175
        if ($name === '') {
176
            return false;
177
        } else {
178
            $names = explode(',', $name);
179
            $names = array_map('trim', $names);
180
            return $names;
181
        }
182
183
    }//end findImplementedInterfaceNames()
184
185
186
    /**
187
     * Checks if a function call has parameters.
188
     *
189
     * Expects to be passed the T_STRING stack pointer for the function call.
190
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
191
     *
192
     * @link https://github.com/wimg/PHPCompatibility/issues/120
193
     * @link https://github.com/wimg/PHPCompatibility/issues/152
194
     *
195
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
196
     * @param int                  $stackPtr  The position of the function call token.
197
     *
198
     * @return bool
199
     */
200
    public function doesFunctionCallHaveParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
201
    {
202
        $tokens = $phpcsFile->getTokens();
203
204
        // Check for the existence of the token.
205
        if (isset($tokens[$stackPtr]) === false) {
206
            return false;
207
        }
208
209
        if ($tokens[$stackPtr]['code'] !== T_STRING) {
210
            return false;
211
        }
212
213
        // Next non-empty token should be the open parenthesis.
214
        $openParenthesis = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
215
        if ($openParenthesis === false || $tokens[$openParenthesis]['code'] !== T_OPEN_PARENTHESIS) {
216
            return false;
217
        }
218
219
        if (isset($tokens[$openParenthesis]['parenthesis_closer']) === false) {
220
            return false;
221
        }
222
223
        $closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
224
        $nextNonEmpty     = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $openParenthesis + 1, $closeParenthesis + 1, true);
225
226
        if ($nextNonEmpty === $closeParenthesis) {
227
            // No parameters.
228
            return false;
229
        }
230
231
        return true;
232
    }
233
234
235
    /**
236
     * Count the number of parameters a function call has been passed.
237
     *
238
     * Expects to be passed the T_STRING stack pointer for the function call.
239
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
240
     *
241
     * @link https://github.com/wimg/PHPCompatibility/issues/111
242
     * @link https://github.com/wimg/PHPCompatibility/issues/114
243
     * @link https://github.com/wimg/PHPCompatibility/issues/151
244
     *
245
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
246
     * @param int                  $stackPtr  The position of the function call token.
247
     *
248
     * @return int
249
     */
250
    public function getFunctionCallParameterCount(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
251
    {
252
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
253
            return 0;
254
        }
255
256
        return count($this->getFunctionCallParameters($phpcsFile, $stackPtr));
257
    }
258
259
260
    /**
261
     * Get information on all parameters passed to a function call.
262
     *
263
     * Expects to be passed the T_STRING stack pointer for the function call.
264
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
265
     *
266
     * Will return an multi-dimentional array with the start token pointer, end token
267
     * pointer and raw parameter value for all parameters. Index will be 1-based.
268
     * If no parameters are found, will return an empty array.
269
     *
270
     * @param PHP_CodeSniffer_File $phpcsFile     The file being scanned.
271
     * @param int                  $stackPtr      The position of the function call token.
272
     *
273
     * @return array
274
     */
275
    public function getFunctionCallParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
276
    {
277
        if ($this->doesFunctionCallHaveParameters($phpcsFile, $stackPtr) === false) {
278
            return array();
279
        }
280
281
        // Ok, we know we have a T_STRING with parameters and valid open & close parenthesis.
282
        $tokens = $phpcsFile->getTokens();
283
284
        $openParenthesis  = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
285
        $closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
286
287
        // Which nesting level is the one we are interested in ?
288
        $nestedParenthesisCount = 1;
289 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...
290
            $nestedParenthesisCount = count($tokens[$openParenthesis]['nested_parenthesis']) + 1;
291
        }
292
293
        $parameters = array();
294
        $nextComma  = $openParenthesis;
295
        $paramStart = $openParenthesis + 1;
296
        $cnt        = 1;
297
        while ($nextComma = $phpcsFile->findNext(array(T_COMMA, T_CLOSE_PARENTHESIS, T_OPEN_SHORT_ARRAY), $nextComma + 1, $closeParenthesis + 1)) {
298
            // Ignore anything within short array definition brackets.
299
            if (
300
                $tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
301
                &&
302
                ( isset($tokens[$nextComma]['bracket_opener']) && $tokens[$nextComma]['bracket_opener'] === $nextComma )
303
                &&
304
                isset($tokens[$nextComma]['bracket_closer'])
305
            ) {
306
                // Skip forward to the end of the short array definition.
307
                $nextComma = $tokens[$nextComma]['bracket_closer'];
308
                continue;
309
            }
310
311
            // Ignore comma's at a lower nesting level.
312
            if (
313
                $tokens[$nextComma]['type'] === 'T_COMMA'
314
                &&
315
                isset($tokens[$nextComma]['nested_parenthesis'])
316
                &&
317
                count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
318
            ) {
319
                continue;
320
            }
321
322
            // Ignore closing parenthesis if not 'ours'.
323
            if ($tokens[$nextComma]['type'] === 'T_CLOSE_PARENTHESIS' && $nextComma !== $closeParenthesis) {
324
                continue;
325
            }
326
327
            // Ok, we've reached the end of the parameter.
328
            $parameters[$cnt]['start'] = $paramStart;
329
            $parameters[$cnt]['end']   = $nextComma - 1;
330
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
331
332
            // Check if there are more tokens before the closing parenthesis.
333
            // Prevents code like the following from setting a third parameter:
334
            // 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...
335
            $hasNextParam = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $nextComma + 1, $closeParenthesis, true, null, true);
336
            if ($hasNextParam === false) {
337
                break;
338
            }
339
340
            // Prepare for the next parameter.
341
            $paramStart = $nextComma + 1;
342
            $cnt++;
343
        }
344
345
        return $parameters;
346
    }
347
348
349
    /**
350
     * Get information on a specific parameter passed to a function call.
351
     *
352
     * Expects to be passed the T_STRING stack pointer for the function call.
353
     * If passed a T_STRING which is *not* a function call, the behaviour is unreliable.
354
     *
355
     * Will return a array with the start token pointer, end token pointer and the raw value
356
     * of the parameter at a specific offset.
357
     * If the specified parameter is not found, will return false.
358
     *
359
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
360
     * @param int                  $stackPtr    The position of the function call token.
361
     * @param int                  $paramOffset The 1-based index position of the parameter to retrieve.
362
     *
363
     * @return array|false
364
     */
365
    public function getFunctionCallParameter(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $paramOffset)
366
    {
367
        $parameters = $this->getFunctionCallParameters($phpcsFile, $stackPtr);
368
369
        if (isset($parameters[$paramOffset]) === false) {
370
            return false;
371
        }
372
        else {
373
            return $parameters[$paramOffset];
374
        }
375
    }
376
377
378
    /**
379
     * Verify whether a token is within a scoped condition.
380
     *
381
     * If the optional $validScopes parameter has been passed, the function
382
     * will check that the token has at least one condition which is of a
383
     * type defined in $validScopes.
384
     *
385
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
386
     * @param int                  $stackPtr    The position of the token.
387
     * @param array|int            $validScopes Optional. Array of valid scopes
388
     *                                          or int value of a valid scope.
389
     *
390
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
391
     *              If the $scopeTypes are set: True if *one* of the conditions is a
392
     *              valid scope, false otherwise.
393
     */
394
    public function tokenHasScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
395
    {
396
        $tokens = $phpcsFile->getTokens();
397
398
        // Check for the existence of the token.
399
        if (isset($tokens[$stackPtr]) === false) {
400
            return false;
401
        }
402
403
        // No conditions = no scope.
404
        if (empty($tokens[$stackPtr]['conditions'])) {
405
            return false;
406
        }
407
408
        // Ok, there are conditions, do we have to check for specific ones ?
409
        if (isset($validScopes) === false) {
410
            return true;
411
        }
412
413
        if (is_int($validScopes)) {
414
            // Received an integer, so cast to array.
415
            $validScopes = (array) $validScopes;
416
        }
417
418
        if (empty($validScopes) || is_array($validScopes) === false) {
419
            // No valid scope types received, so will not comply.
420
            return false;
421
        }
422
423
        // Check for required scope types.
424
        foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
425
            if (in_array($type, $validScopes, true)) {
426
                return true;
427
            }
428
        }
429
430
        return false;
431
    }
432
433
434
    /**
435
     * Verify whether a token is within a class scope.
436
     *
437
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
438
     * @param int                  $stackPtr  The position of the token.
439
     * @param bool                 $strict    Whether to strictly check for the T_CLASS
440
     *                                        scope or also accept interfaces and traits
441
     *                                        as scope.
442
     *
443
     * @return bool True if within class scope, false otherwise.
444
     */
445
    public function inClassScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
446
    {
447
        $validScopes = array(T_CLASS);
448
        if ($strict === false) {
449
            $validScopes[] = T_INTERFACE;
450
            $validScopes[] = T_TRAIT;
451
        }
452
453
        return $this->tokenHasScope($phpcsFile, $stackPtr, $validScopes);
454
    }
455
456
457
    /**
458
     * Returns the fully qualified class name for a new class instantiation.
459
     *
460
     * Returns an empty string if the class name could not be reliably inferred.
461
     *
462
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
463
     * @param int                  $stackPtr  The position of a T_NEW token.
464
     *
465
     * @return string
466
     */
467
    public function getFQClassNameFromNewToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
468
    {
469
        $tokens = $phpcsFile->getTokens();
470
471
        // Check for the existence of the token.
472
        if (isset($tokens[$stackPtr]) === false) {
473
            return '';
474
        }
475
476
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
477
            return '';
478
        }
479
480
        $find = array(
481
                 T_NS_SEPARATOR,
482
                 T_STRING,
483
                 T_NAMESPACE,
484
                 T_WHITESPACE,
485
                );
486
487
        $start = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
488
        // Bow out if the next token is a variable as we don't know where it was defined.
489
        if ($tokens[$start]['code'] === T_VARIABLE) {
490
            return '';
491
        }
492
493
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
494
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
495
        $className = trim($className);
496
497
        return $this->getFQName($phpcsFile, $stackPtr, $className);
498
    }
499
500
501
    /**
502
     * Returns the fully qualified name of the class that the specified class extends.
503
     *
504
     * Returns an empty string if the class does not extend another class or if
505
     * the class name could not be reliably inferred.
506
     *
507
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
508
     * @param int                  $stackPtr  The position of a T_CLASS token.
509
     *
510
     * @return string
511
     */
512
    public function getFQExtendedClassName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
513
    {
514
        $tokens = $phpcsFile->getTokens();
515
516
        // Check for the existence of the token.
517
        if (isset($tokens[$stackPtr]) === false) {
518
            return '';
519
        }
520
521
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
522
            return '';
523
        }
524
525
        $extends = $phpcsFile->findExtendedClassName($stackPtr);
526
        if (empty($extends) || is_string($extends) === false) {
527
            return '';
528
        }
529
530
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
531
    }
532
533
534
    /**
535
     * Returns the class name for the static usage of a class.
536
     * This can be a call to a method, the use of a property or constant.
537
     *
538
     * Returns an empty string if the class name could not be reliably inferred.
539
     *
540
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
541
     * @param int                  $stackPtr  The position of a T_NEW token.
542
     *
543
     * @return string
544
     */
545
    public function getFQClassNameFromDoubleColonToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
546
    {
547
        $tokens = $phpcsFile->getTokens();
548
549
        // Check for the existence of the token.
550
        if (isset($tokens[$stackPtr]) === false) {
551
            return '';
552
        }
553
554
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
555
            return '';
556
        }
557
558
        // Nothing to do if previous token is a variable as we don't know where it was defined.
559
        if ($tokens[$stackPtr - 1]['code'] === T_VARIABLE) {
560
            return '';
561
        }
562
563
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
564
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
565
            return '';
566
        }
567
568
        // Get the classname from the class declaration if self is used.
569
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
570
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
571
            if ($classDeclarationPtr === false) {
572
                return '';
573
            }
574
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
575
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
576
        }
577
578
        $find = array(
579
                 T_NS_SEPARATOR,
580
                 T_STRING,
581
                 T_NAMESPACE,
582
                 T_WHITESPACE,
583
                );
584
585
        $start     = ($phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true) + 1);
586
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
587
        $className = trim($className);
588
589
        return $this->getFQName($phpcsFile, $stackPtr, $className);
590
    }
591
592
593
    /**
594
     * Get the Fully Qualified name for a class/function/constant etc.
595
     *
596
     * Checks if a class/function/constant name is already fully qualified and
597
     * if not, enrich it with the relevant namespace information.
598
     *
599
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
600
     * @param int                  $stackPtr  The position of the token.
601
     * @param string               $name      The class / function / constant name.
602
     *
603
     * @return string
604
     */
605
    public function getFQName(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
606
    {
607
        if (strpos($name, '\\' ) === 0) {
608
            // Already fully qualified.
609
            return $name;
610
        }
611
612
        // Remove the namespace keyword if used.
613
        if (strpos($name, 'namespace\\') === 0) {
614
            $name = substr($name, 10);
615
        }
616
617
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
618
619
        if ($namespace === '') {
620
            return '\\' . $name;
621
        }
622
        else {
623
            return '\\' . $namespace . '\\' . $name;
624
        }
625
    }
626
627
628
    /**
629
     * Is the class/function/constant name namespaced or global ?
630
     *
631
     * @param string $FQName Fully Qualified name of a class, function etc.
632
     *                       I.e. should always start with a `\` !
633
     *
634
     * @return bool True if namespaced, false if global.
635
     */
636
    public function isNamespaced($FQName) {
637
        if (strpos($FQName, '\\') !== 0) {
638
            throw new PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
639
        }
640
641
        return (strpos(substr($FQName, 1), '\\') !== false);
642
    }
643
644
645
    /**
646
     * Determine the namespace name an arbitrary token lives in.
647
     *
648
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
649
     * @param int                  $stackPtr  The token position for which to determine the namespace.
650
     *
651
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
652
     */
653
    public function determineNamespace(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
654
    {
655
        $tokens = $phpcsFile->getTokens();
656
657
        // Check for the existence of the token.
658
        if (isset($tokens[$stackPtr]) === false) {
659
            return '';
660
        }
661
662
        // Check for scoped namespace {}.
663
        if (empty($tokens[$stackPtr]['conditions']) === false) {
664
            foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
665
                if ($type === T_NAMESPACE) {
666
                    $namespace = $this->getDeclaredNamespaceName($phpcsFile, $pointer);
667
                    if ($namespace !== false) {
668
                        return $namespace;
669
                    }
670
                }
671
                break; // We only need to check the highest level condition.
672
            }
673
        }
674
675
        /*
676
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
677
         * Keeping in mind that:
678
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
679
         * - the namespace keyword can also be used as part of a function/method call and such.
680
         * - that a non-named namespace resolves to the global namespace.
681
         */
682
        $previousNSToken = $stackPtr;
683
        $namespace       = false;
684
        do {
685
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, $previousNSToken -1);
686
687
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
688
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] = $previousNSToken) {
689
                break;
690
            }
691
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
692
693
        } while ($namespace === false && $previousNSToken !== false);
694
695
        // If we still haven't got a namespace, return an empty string.
696
        if ($namespace === false) {
697
            return '';
698
        }
699
        else {
700
            return $namespace;
701
        }
702
    }
703
704
    /**
705
     * Get the complete namespace name for a namespace declaration.
706
     *
707
     * For hierarchical namespaces, the name will be composed of several tokens,
708
     * i.e. MyProject\Sub\Level which will be returned together as one string.
709
     *
710
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
711
     * @param int|bool             $stackPtr  The position of a T_NAMESPACE token.
712
     *
713
     * @return string|false Namespace name or false if not a namespace declaration.
714
     *                      Namespace name can be an empty string for global namespace declaration.
715
     */
716
    public function getDeclaredNamespaceName(PHP_CodeSniffer_File $phpcsFile, $stackPtr )
717
    {
718
        $tokens = $phpcsFile->getTokens();
719
720
        // Check for the existence of the token.
721
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
722
            return false;
723
        }
724
725
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
726
            return false;
727
        }
728
729
        if ($tokens[$stackPtr + 1]['code'] === T_NS_SEPARATOR) {
730
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
731
            return false;
732
        }
733
734
        $nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
735
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
736
            // Declaration for global namespace when using multiple namespaces in a file.
737
            // I.e.: namespace {}
738
            return '';
739
        }
740
741
        // Ok, this should be a namespace declaration, so get all the parts together.
742
        $validTokens = array(
743
                        T_STRING,
744
                        T_NS_SEPARATOR,
745
                        T_WHITESPACE,
746
                       );
747
748
        $namespaceName = '';
749
        while(in_array($tokens[$nextToken]['code'], $validTokens, true) === true) {
750
            $namespaceName .= trim($tokens[$nextToken]['content']);
751
            $nextToken++;
752
        }
753
754
        return $namespaceName;
755
    }
756
757
758
    /**
759
     * Returns the method parameters for the specified T_FUNCTION token.
760
     *
761
     * Each parameter is in the following format:
762
     *
763
     * <code>
764
     *   0 => array(
765
     *         'name'              => '$var',  // The variable name.
766
     *         'pass_by_reference' => false,   // Passed by reference.
767
     *         'type_hint'         => string,  // Type hint for array or custom type
768
     *        )
769
     * </code>
770
     *
771
     * Parameters with default values have an additional array index of
772
     * 'default' with the value of the default as a string.
773
     *
774
     * {@internal Duplicate of same method as contained in the `PHP_CodeSniffer_File`
775
     * class, but with some improvements which were only introduced in PHPCS 2.7.
776
     * Once the minimum supported PHPCS version for this sniff library goes beyond
777
     * that, this method can be removed and calls to it replaced with
778
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.}}
779
     *
780
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
781
     * @param int $stackPtr The position in the stack of the T_FUNCTION token
782
     *                      to acquire the parameters for.
783
     *
784
     * @return array|false
785
     * @throws PHP_CodeSniffer_Exception If the specified $stackPtr is not of
786
     *                                   type T_FUNCTION.
787
     */
788
    public function getMethodParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
789
    {
790
        $tokens = $phpcsFile->getTokens();
791
792
        // Check for the existence of the token.
793
        if (isset($tokens[$stackPtr]) === false) {
794
            return false;
795
        }
796
797
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION) {
798
            throw new PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION');
799
        }
800
801
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
802
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
803
804
        $vars            = array();
805
        $currVar         = null;
806
        $paramStart      = ($opener + 1);
807
        $defaultStart    = null;
808
        $paramCount      = 0;
809
        $passByReference = false;
810
        $variableLength  = false;
811
        $typeHint        = '';
812
813
        for ($i = $paramStart; $i <= $closer; $i++) {
814
            // Check to see if this token has a parenthesis or bracket opener. If it does
815
            // it's likely to be an array which might have arguments in it. This
816
            // could cause problems in our parsing below, so lets just skip to the
817
            // end of it.
818 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...
819
                // Don't do this if it's the close parenthesis for the method.
820
                if ($i !== $tokens[$i]['parenthesis_closer']) {
821
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
822
                }
823
            }
824
825 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...
826
                // Don't do this if it's the close parenthesis for the method.
827
                if ($i !== $tokens[$i]['bracket_closer']) {
828
                    $i = ($tokens[$i]['bracket_closer'] + 1);
829
                }
830
            }
831
832
            switch ($tokens[$i]['code']) {
833
            case T_BITWISE_AND:
834
                $passByReference = true;
835
                break;
836
            case T_VARIABLE:
837
                $currVar = $i;
838
                break;
839
            case T_ELLIPSIS:
840
                $variableLength = true;
841
                break;
842
            case T_ARRAY_HINT:
843
            case T_CALLABLE:
844
                $typeHint = $tokens[$i]['content'];
845
                break;
846
            case T_SELF:
847
            case T_PARENT:
848
            case T_STATIC:
849
                // Self is valid, the others invalid, but were probably intended as type hints.
850
                if (isset($defaultStart) === false) {
851
                    $typeHint = $tokens[$i]['content'];
852
                }
853
                break;
854
            case T_STRING:
855
                // This is a string, so it may be a type hint, but it could
856
                // also be a constant used as a default value.
857
                $prevComma = false;
858 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...
859
                    if ($tokens[$t]['code'] === T_COMMA) {
860
                        $prevComma = $t;
861
                        break;
862
                    }
863
                }
864
865
                if ($prevComma !== false) {
866
                    $nextEquals = false;
867 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...
868
                        if ($tokens[$t]['code'] === T_EQUAL) {
869
                            $nextEquals = $t;
870
                            break;
871
                        }
872
                    }
873
874
                    if ($nextEquals !== false) {
875
                        break;
876
                    }
877
                }
878
879
                if ($defaultStart === null) {
880
                    $typeHint .= $tokens[$i]['content'];
881
                }
882
                break;
883
            case T_NS_SEPARATOR:
884
                // Part of a type hint or default value.
885
                if ($defaultStart === null) {
886
                    $typeHint .= $tokens[$i]['content'];
887
                }
888
                break;
889
            case T_CLOSE_PARENTHESIS:
890
            case T_COMMA:
891
                // If it's null, then there must be no parameters for this
892
                // method.
893
                if ($currVar === null) {
894
                    continue;
895
                }
896
897
                $vars[$paramCount]         = array();
898
                $vars[$paramCount]['name'] = $tokens[$currVar]['content'];
899
900
                if ($defaultStart !== null) {
901
                    $vars[$paramCount]['default']
902
                        = $phpcsFile->getTokensAsString(
903
                            $defaultStart,
904
                            ($i - $defaultStart)
905
                        );
906
                }
907
908
                $rawContent = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
909
910
                $vars[$paramCount]['pass_by_reference'] = $passByReference;
911
                $vars[$paramCount]['variable_length']   = $variableLength;
912
                $vars[$paramCount]['type_hint']         = $typeHint;
913
                $vars[$paramCount]['raw'] = $rawContent;
914
915
                // Reset the vars, as we are about to process the next parameter.
916
                $defaultStart    = null;
917
                $paramStart      = ($i + 1);
918
                $passByReference = false;
919
                $variableLength  = false;
920
                $typeHint        = '';
921
922
                $paramCount++;
923
                break;
924
            case T_EQUAL:
925
                $defaultStart = ($i + 1);
926
                break;
927
            }//end switch
928
        }//end for
929
930
        return $vars;
931
932
    }//end getMethodParameters()
933
934
}//end class
935