Completed
Pull Request — master (#189)
by Juliette
03:24
created

PHPCompatibility_Sniff   D

Complexity

Total Complexity 117

Size/Duplication

Total Lines 804
Duplicated Lines 6.22 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 6
Bugs 1 Features 1
Metric Value
wmc 117
c 6
b 1
f 1
lcom 1
cbo 4
dl 50
loc 804
rs 4.4444

16 Methods

Rating   Name   Duplication   Size   Complexity  
B findImplementedInterfaceNames() 0 43 6
C doesFunctionCallHaveParameters() 0 33 7
D getFunctionCallParameterCount() 0 42 9
C getTestVersion() 0 41 8
A supportsAbove() 13 13 3
A supportsBelow() 13 13 3
D tokenHasScope() 0 38 9
A inClassScope() 0 10 2
B getFQClassNameFromNewToken() 0 27 3
B getFQExtendedClassName() 0 20 5
B getFQClassNameFromDoubleColonToken() 0 41 6
A getFQName() 0 21 4
A isNamespaced() 0 7 2
C determineNamespace() 0 50 11
C getDeclaredNamespaceName() 0 40 7
F getMethodParameters() 24 145 32

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like PHPCompatibility_Sniff often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use PHPCompatibility_Sniff, and based on these observations, apply Extract Interface, too.

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
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
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
Duplication introduced by
This method seems to be duplicated in your project.

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

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

Loading history...
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
        // Ok, we know we have a T_STRING with parameters and valid open & close parenthesis.
242
        $tokens = $phpcsFile->getTokens();
243
244
        $openParenthesis = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
245
        $closeParenthesis = $tokens[$openParenthesis]['parenthesis_closer'];
246
247
        // Which nesting level is the one we are interested in ?
248
        $nestedParenthesisCount = 1;
249
        if (isset($tokens[$openParenthesis]['nested_parenthesis'])) {
250
            $nestedParenthesisCount = count($tokens[$openParenthesis]['nested_parenthesis']) + 1;
251
        }
252
253
        $nextComma = $openParenthesis;
254
        $cnt = 0;
255
        while ($nextComma = $phpcsFile->findNext(array(T_COMMA, T_CLOSE_PARENTHESIS), $nextComma + 1, $closeParenthesis + 1)) {
256
            // Ignore comma's at a lower nesting level.
257
            if (
258
                $tokens[$nextComma]['type'] == 'T_COMMA'
259
                &&
260
                isset($tokens[$nextComma]['nested_parenthesis'])
261
                &&
262
                count($tokens[$nextComma]['nested_parenthesis']) != $nestedParenthesisCount
263
            ) {
264
                continue;
265
            }
266
267
            // Ignore closing parenthesis if not 'ours'.
268
            if ($tokens[$nextComma]['type'] == 'T_CLOSE_PARENTHESIS' && $nextComma != $closeParenthesis) {
269
                continue;
270
            }
271
272
            $cnt++;
273
        }
274
275
        return $cnt;
276
    }
277
278
279
    /**
280
     * Verify whether a token is within a scoped condition.
281
     *
282
     * If the optional $validScopes parameter has been passed, the function
283
     * will check that the token has at least one condition which is of a
284
     * type defined in $validScopes.
285
     *
286
     * @param PHP_CodeSniffer_File $phpcsFile   The file being scanned.
287
     * @param int                  $stackPtr    The position of the token.
288
     * @param array|int            $validScopes Optional. Array of valid scopes
289
     *                                          or int value of a valid scope.
290
     *
291
     * @return bool Without the optional $scopeTypes: True if within a scope, false otherwise.
292
     *              If the $scopeTypes are set: True if *one* of the conditions is a
293
     *              valid scope, false otherwise.
294
     */
295
    public function tokenHasScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $validScopes = null)
296
    {
297
        $tokens = $phpcsFile->getTokens();
298
299
        // Check for the existence of the token.
300
        if (isset($tokens[$stackPtr]) === false) {
301
            return false;
302
        }
303
304
        // No conditions = no scope.
305
        if (empty($tokens[$stackPtr]['conditions'])) {
306
            return false;
307
        }
308
309
        // Ok, there are conditions, do we have to check for specific ones ?
310
        if (isset($validScopes) === false) {
311
            return true;
312
        }
313
314
        if (is_int($validScopes)) {
315
            // Received an integer, so cast to array.
316
            $validScopes = (array) $validScopes;
317
        }
318
319
        if (empty($validScopes) || is_array($validScopes) === false) {
320
            // No valid scope types received, so will not comply.
321
            return false;
322
        }
323
324
        // Check for required scope types.
325
        foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
326
            if (in_array($type, $validScopes, true)) {
327
                return true;
328
            }
329
        }
330
331
        return false;
332
    }
333
334
335
    /**
336
     * Verify whether a token is within a class scope.
337
     *
338
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
339
     * @param int                  $stackPtr  The position of the token.
340
     * @param bool                 $strict    Whether to strictly check for the T_CLASS
341
     *                                        scope or also accept interfaces and traits
342
     *                                        as scope.
343
     *
344
     * @return bool True if within class scope, false otherwise.
345
     */
346
    public function inClassScope(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $strict = true)
347
    {
348
        $validScopes = array(T_CLASS);
349
        if ($strict === false) {
350
            $validScopes[] = T_INTERFACE;
351
            $validScopes[] = T_TRAIT;
352
        }
353
354
        return $this->tokenHasScope($phpcsFile, $stackPtr, $validScopes);
355
    }
356
357
358
    /**
359
     * Returns the fully qualified class name for a new class instantiation.
360
     *
361
     * Returns an empty string if the class name could not be reliably inferred.
362
     *
363
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
364
     * @param int                  $stackPtr  The position of a T_NEW token.
365
     *
366
     * @return string
367
     */
368
    public function getFQClassNameFromNewToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
369
    {
370
        $tokens = $phpcsFile->getTokens();
371
372
        // Check for the existence of the token.
373
        if (isset($tokens[$stackPtr]) === false) {
374
            return '';
375
        }
376
377
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
378
            return '';
379
        }
380
381
        $find = array(
382
                 T_NS_SEPARATOR,
383
                 T_STRING,
384
                 T_NAMESPACE,
385
                 T_WHITESPACE,
386
                );
387
388
        $start     = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
389
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
390
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
391
        $className = trim($className);
392
393
        return $this->getFQName($phpcsFile, $stackPtr, $className);
394
    }
395
396
397
    /**
398
     * Returns the fully qualified name of the class that the specified class extends.
399
     *
400
     * Returns an empty string if the class does not extend another class or if
401
     * the class name could not be reliably inferred.
402
     *
403
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
404
     * @param int                  $stackPtr  The position of a T_CLASS token.
405
     *
406
     * @return string
407
     */
408
    public function getFQExtendedClassName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
409
    {
410
        $tokens = $phpcsFile->getTokens();
411
412
        // Check for the existence of the token.
413
        if (isset($tokens[$stackPtr]) === false) {
414
            return '';
415
        }
416
417
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
418
            return '';
419
        }
420
421
        $extends = $phpcsFile->findExtendedClassName($stackPtr);
422
        if (empty($extends) || is_string($extends) === false) {
423
            return '';
424
        }
425
426
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
427
    }
428
429
430
    /**
431
     * Returns the class name for the static usage of a class.
432
     * This can be a call to a method, the use of a property or constant.
433
     *
434
     * Returns an empty string if the class name could not be reliably inferred.
435
     *
436
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
437
     * @param int                  $stackPtr  The position of a T_NEW token.
438
     *
439
     * @return string
440
     */
441
    public function getFQClassNameFromDoubleColonToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
442
    {
443
        $tokens = $phpcsFile->getTokens();
444
445
        // Check for the existence of the token.
446
        if (isset($tokens[$stackPtr]) === false) {
447
            return '';
448
        }
449
450
        if ($tokens[$stackPtr]['code'] !== T_DOUBLE_COLON) {
451
            return '';
452
        }
453
454
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
455
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
456
            return '';
457
        }
458
459
        // Get the classname from the class declaration if self is used.
460
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
461
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
462
            if ($classDeclarationPtr === false) {
463
				return '';
464
			}
465
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
466
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
467
        }
468
469
        $find = array(
470
                 T_NS_SEPARATOR,
471
                 T_STRING,
472
                 T_NAMESPACE,
473
                 T_WHITESPACE,
474
                );
475
476
        $start     = ($phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true) + 1);
477
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
478
        $className = trim($className);
479
480
        return $this->getFQName($phpcsFile, $stackPtr, $className);
481
    }
482
483
484
    /**
485
     * Get the Fully Qualified name for a class/function/constant etc.
486
     *
487
     * Checks if a class/function/constant name is already fully qualified and
488
     * if not, enrich it with the relevant namespace information.
489
     *
490
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
491
     * @param int                  $stackPtr  The position of the token.
492
     * @param string               $name      The class / function / constant name.
493
     *
494
     * @return string
495
     */
496
    public function getFQName(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
497
    {
498
        if (strpos($name, '\\' ) === 0) {
499
            // Already fully qualified.
500
            return $name;
501
        }
502
503
        // Remove the namespace keyword if used.
504
        if (strpos($name, 'namespace\\') === 0) {
505
            $name = substr($name, 10);
506
        }
507
508
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
509
510
        if ($namespace === '') {
511
            return '\\' . $name;
512
        }
513
        else {
514
            return '\\' . $namespace . '\\' . $name;
515
        }
516
    }
517
518
519
    /**
520
     * Is the class/function/constant name namespaced or global ?
521
     *
522
     * @param string $FQName Fully Qualified name of a class, function etc.
523
     *                       I.e. should always start with a `\` !
524
     *
525
     * @return bool True if namespaced, false if global.
526
     */
527
    public function isNamespaced($FQName) {
528
        if (strpos($FQName, '\\') !== 0) {
529
            throw new PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
530
        }
531
532
        return (strpos(substr($FQName, 1), '\\') !== false);
533
    }
534
535
536
    /**
537
     * Determine the namespace name an arbitrary token lives in.
538
     *
539
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
540
     * @param int                  $stackPtr  The token position for which to determine the namespace.
541
     *
542
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
543
     */
544
    public function determineNamespace(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
545
    {
546
        $tokens = $phpcsFile->getTokens();
547
548
        // Check for the existence of the token.
549
        if (isset($tokens[$stackPtr]) === false) {
550
            return '';
551
        }
552
553
        // Check for scoped namespace {}.
554
        if (empty($tokens[$stackPtr]['conditions']) === false) {
555
            foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
556
                if ($type === T_NAMESPACE) {
557
                    $namespace = $this->getDeclaredNamespaceName($phpcsFile, $pointer);
558
                    if ($namespace !== false) {
559
                        return $namespace;
560
                    }
561
                }
562
                break; // We only need to check the highest level condition.
563
            }
564
        }
565
566
        /*
567
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
568
         * Keeping in mind that:
569
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
570
         * - the namespace keyword can also be used as part of a function/method call and such.
571
         * - that a non-named namespace resolves to the global namespace.
572
         */
573
        $previousNSToken = $stackPtr;
574
        $namespace       = false;
575
        do {
576
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, $previousNSToken -1);
577
578
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
579
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] = $previousNSToken) {
580
                break;
581
            }
582
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
583
584
        } while ($namespace === false && $previousNSToken !== false);
585
586
        // If we still haven't got a namespace, return an empty string.
587
        if ($namespace === false) {
588
            return '';
589
        }
590
        else {
591
            return $namespace;
592
        }
593
    }
594
595
    /**
596
     * Get the complete namespace name for a namespace declaration.
597
     *
598
     * For hierarchical namespaces, the name will be composed of several tokens,
599
     * i.e. MyProject\Sub\Level which will be returned together as one string.
600
     *
601
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
602
     * @param int|bool             $stackPtr  The position of a T_NAMESPACE token.
603
     *
604
     * @return string|false Namespace name or false if not a namespace declaration.
605
     *                      Namespace name can be an empty string for global namespace declaration.
606
     */
607
    public function getDeclaredNamespaceName(PHP_CodeSniffer_File $phpcsFile, $stackPtr )
608
    {
609
        $tokens = $phpcsFile->getTokens();
610
611
        // Check for the existence of the token.
612
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
613
            return false;
614
        }
615
616
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
617
            return false;
618
        }
619
620
        if ($tokens[$stackPtr + 1]['code'] === T_NS_SEPARATOR) {
621
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
622
            return false;
623
        }
624
625
        $nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
626
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
627
            // Declaration for global namespace when using multiple namespaces in a file.
628
            // I.e.: namespace {}
629
            return '';
630
        }
631
632
        // Ok, this should be a namespace declaration, so get all the parts together.
633
        $validTokens = array(
634
                        T_STRING,
635
                        T_NS_SEPARATOR,
636
                        T_WHITESPACE,
637
                       );
638
639
        $namespaceName = '';
640
        while(in_array($tokens[$nextToken]['code'], $validTokens, true) === true) {
641
            $namespaceName .= trim($tokens[$nextToken]['content']);
642
            $nextToken++;
643
        }
644
645
        return $namespaceName;
646
    }
647
648
649
    /**
650
     * Returns the method parameters for the specified T_FUNCTION token.
651
     *
652
     * Each parameter is in the following format:
653
     *
654
     * <code>
655
     *   0 => array(
656
     *         'name'              => '$var',  // The variable name.
657
     *         'pass_by_reference' => false,   // Passed by reference.
658
     *         'type_hint'         => string,  // Type hint for array or custom type
659
     *        )
660
     * </code>
661
     *
662
     * Parameters with default values have an additional array index of
663
     * 'default' with the value of the default as a string.
664
     *
665
     * {@internal Duplicate of same method as contained in the `PHP_CodeSniffer_File`
666
     * class, but with some improvements which were only introduced in PHPCS 2.7.
667
     * Once the minimum supported PHPCS version for this sniff library goes beyond
668
     * that, this method can be removed and calls to it replaced with
669
     * `$phpcsFile->getMethodParameters($stackPtr)` calls.}}
670
     *
671
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
672
     * @param int $stackPtr The position in the stack of the T_FUNCTION token
673
     *                      to acquire the parameters for.
674
     *
675
     * @return array
676
     * @throws PHP_CodeSniffer_Exception If the specified $stackPtr is not of
677
     *                                   type T_FUNCTION.
678
     */
679
    public function getMethodParameters(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
680
    {
681
        $tokens = $phpcsFile->getTokens();
682
683
        // Check for the existence of the token.
684
        if (isset($tokens[$stackPtr]) === false) {
685
            return false;
686
        }
687
688
        if ($tokens[$stackPtr]['code'] !== T_FUNCTION) {
689
            throw new PHP_CodeSniffer_Exception('$stackPtr must be of type T_FUNCTION');
690
        }
691
692
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
693
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
694
695
        $vars            = array();
696
        $currVar         = null;
697
        $paramStart      = ($opener + 1);
698
        $defaultStart    = null;
699
        $paramCount      = 0;
700
        $passByReference = false;
701
        $variableLength  = false;
702
        $typeHint        = '';
703
704
        for ($i = $paramStart; $i <= $closer; $i++) {
705
            // Check to see if this token has a parenthesis or bracket opener. If it does
706
            // it's likely to be an array which might have arguments in it. This
707
            // could cause problems in our parsing below, so lets just skip to the
708
            // end of it.
709 View Code Duplication
            if (isset($tokens[$i]['parenthesis_opener']) === true) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
710
                // Don't do this if it's the close parenthesis for the method.
711
                if ($i !== $tokens[$i]['parenthesis_closer']) {
712
                    $i = ($tokens[$i]['parenthesis_closer'] + 1);
713
                }
714
            }
715
716 View Code Duplication
            if (isset($tokens[$i]['bracket_opener']) === true) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
717
                // Don't do this if it's the close parenthesis for the method.
718
                if ($i !== $tokens[$i]['bracket_closer']) {
719
                    $i = ($tokens[$i]['bracket_closer'] + 1);
720
                }
721
            }
722
723
            switch ($tokens[$i]['code']) {
724
            case T_BITWISE_AND:
725
                $passByReference = true;
726
                break;
727
            case T_VARIABLE:
728
                $currVar = $i;
729
                break;
730
            case T_ELLIPSIS:
731
                $variableLength = true;
732
                break;
733
            case T_ARRAY_HINT:
734
            case T_CALLABLE:
735
                $typeHint = $tokens[$i]['content'];
736
                break;
737
            case T_SELF:
738
            case T_PARENT:
739
            case T_STATIC:
740
                // Self is valid, the others invalid, but were probably intended as type hints.
741
                if (isset($defaultStart) === false) {
742
                    $typeHint = $tokens[$i]['content'];
743
                }
744
                break;
745
            case T_STRING:
746
                // This is a string, so it may be a type hint, but it could
747
                // also be a constant used as a default value.
748
                $prevComma = false;
749 View Code Duplication
                for ($t = $i; $t >= $opener; $t--) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
750
                    if ($tokens[$t]['code'] === T_COMMA) {
751
                        $prevComma = $t;
752
                        break;
753
                    }
754
                }
755
756
                if ($prevComma !== false) {
757
                    $nextEquals = false;
758 View Code Duplication
                    for ($t = $prevComma; $t < $i; $t++) {
1 ignored issue
show
Duplication introduced by
This code seems to be duplicated across your project.

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

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

Loading history...
759
                        if ($tokens[$t]['code'] === T_EQUAL) {
760
                            $nextEquals = $t;
761
                            break;
762
                        }
763
                    }
764
765
                    if ($nextEquals !== false) {
766
                        break;
767
                    }
768
                }
769
770
                if ($defaultStart === null) {
771
                    $typeHint .= $tokens[$i]['content'];
772
                }
773
                break;
774
            case T_NS_SEPARATOR:
775
                // Part of a type hint or default value.
776
                if ($defaultStart === null) {
777
                    $typeHint .= $tokens[$i]['content'];
778
                }
779
                break;
780
            case T_CLOSE_PARENTHESIS:
781
            case T_COMMA:
782
                // If it's null, then there must be no parameters for this
783
                // method.
784
                if ($currVar === null) {
785
                    continue;
786
                }
787
788
                $vars[$paramCount]         = array();
789
                $vars[$paramCount]['name'] = $tokens[$currVar]['content'];
790
791
                if ($defaultStart !== null) {
792
                    $vars[$paramCount]['default']
793
                        = $phpcsFile->getTokensAsString(
794
                            $defaultStart,
795
                            ($i - $defaultStart)
796
                        );
797
                }
798
799
                $rawContent = trim($phpcsFile->getTokensAsString($paramStart, ($i - $paramStart)));
800
801
                $vars[$paramCount]['pass_by_reference'] = $passByReference;
802
                $vars[$paramCount]['variable_length']   = $variableLength;
803
                $vars[$paramCount]['type_hint']         = $typeHint;
804
                $vars[$paramCount]['raw'] = $rawContent;
805
806
                // Reset the vars, as we are about to process the next parameter.
807
                $defaultStart    = null;
808
                $paramStart      = ($i + 1);
809
                $passByReference = false;
810
                $variableLength  = false;
811
                $typeHint        = '';
812
813
                $paramCount++;
814
                break;
815
            case T_EQUAL:
816
                $defaultStart = ($i + 1);
817
                break;
818
            }//end switch
819
        }//end for
820
821
        return $vars;
822
823
    }//end getMethodParameters()
824
825
}//end class
826