Completed
Push — master ( 8571e4...1f0247 )
by Wim
17s
created

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