Completed
Push — master ( c6357c...5bad31 )
by Juliette
9s
created

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