Completed
Pull Request — master (#168)
by Juliette
02:29
created

getFunctionCallParameterCount()   D

Complexity

Conditions 9
Paths 9

Size

Total Lines 42
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

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