Completed
Pull Request — master (#213)
by Juliette
05:55
created

Sniff.php (1 issue)

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