Completed
Pull Request — master (#162)
by Juliette
03:17
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
     * Returns the fully qualified class name for a new class instantiation.
281
     *
282
     * Returns an empty string if the class name could not be reliably inferred.
283
     *
284
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
285
     * @param int                  $stackPtr  The position of a T_NEW token.
286
     *
287
     * @return string
288
     */
289
    public function getFQClassNameFromNewToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
290
    {
291
        $tokens = $phpcsFile->getTokens();
292
293
        // Check for the existence of the token.
294
        if (isset($tokens[$stackPtr]) === false) {
295
            return '';
296
        }
297
298
        if ($tokens[$stackPtr]['code'] !== T_NEW) {
299
            return '';
300
        }
301
302
        $find = array(
303
                 T_NS_SEPARATOR,
304
                 T_STRING,
305
                 T_NAMESPACE,
306
                 T_WHITESPACE,
307
                );
308
309
        $start     = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
310
        $end       = $phpcsFile->findNext($find, ($start + 1), null, true, null, true);
311
        $className = $phpcsFile->getTokensAsString($start, ($end - $start));
312
        $className = trim($className);
313
314
        return $this->getFQName($phpcsFile, $stackPtr, $className);
315
    }
316
317
318
    /**
319
     * Returns the fully qualified name of the class that the specified class extends.
320
     *
321
     * Returns an empty string if the class does not extend another class or if
322
     * the class name could not be reliably inferred.
323
     *
324
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
325
     * @param int                  $stackPtr  The position of a T_CLASS token.
326
     *
327
     * @return string
328
     */
329
    public function getFQExtendedClassName(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
330
    {
331
        $tokens = $phpcsFile->getTokens();
332
333
        // Check for the existence of the token.
334
        if (isset($tokens[$stackPtr]) === false) {
335
            return '';
336
        }
337
338
        if ($tokens[$stackPtr]['code'] !== T_CLASS) {
339
            return '';
340
        }
341
342
        $extends = $phpcsFile->findExtendedClassName($stackPtr);
343
        if (empty($extends) || is_string($extends) === false) {
344
            return '';
345
        }
346
347
        return $this->getFQName($phpcsFile, $stackPtr, $extends);
348
    }
349
350
351
    /**
352
     * Returns the class name for the static usage of a class.
353
     * This can be a call to a method, the use of a property or constant.
354
     *
355
     * Returns an empty string if 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_NEW token.
359
     *
360
     * @return string
361
     */
362
    public function getFQClassNameFromDoubleColonToken(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_DOUBLE_COLON) {
372
            return '';
373
        }
374
375
        // Nothing to do if 'parent' or 'static' as we don't know how far the class tree extends.
376
        if (in_array($tokens[$stackPtr - 1]['code'], array(T_PARENT, T_STATIC), true)) {
377
            return '';
378
        }
379
380
        // Get the classname from the class declaration if self is used.
381
        if ($tokens[$stackPtr - 1]['code'] === T_SELF) {
382
            $classDeclarationPtr = $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1);
383
            if ($classDeclarationPtr === false) {
384
				return '';
385
			}
386
            $className = $phpcsFile->getDeclarationName($classDeclarationPtr);
1 ignored issue
show
Bug introduced by
It seems like $classDeclarationPtr defined by $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1) on line 382 can also be of type boolean; however, PHP_CodeSniffer_File::getDeclarationName() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
387
            return $this->getFQName($phpcsFile, $classDeclarationPtr, $className);
1 ignored issue
show
Bug introduced by
It seems like $classDeclarationPtr defined by $phpcsFile->findPrevious(T_CLASS, $stackPtr - 1) on line 382 can also be of type boolean; however, PHPCompatibility_Sniff::getFQName() does only seem to accept integer, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
388
        }
389
390
        $find = array(
391
                 T_NS_SEPARATOR,
392
                 T_STRING,
393
                 T_NAMESPACE,
394
                 T_WHITESPACE,
395
                );
396
397
        $start     = ($phpcsFile->findPrevious($find, $stackPtr - 1, null, true, null, true) + 1);
398
        $className = $phpcsFile->getTokensAsString($start, ($stackPtr - $start));
399
        $className = trim($className);
400
401
        return $this->getFQName($phpcsFile, $stackPtr, $className);
402
    }
403
404
405
    /**
406
     * Get the Fully Qualified name for a class/function/constant etc.
407
     *
408
     * Checks if a class/function/constant name is already fully qualified and
409
     * if not, enrich it with the relevant namespace information.
410
     *
411
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
412
     * @param int                  $stackPtr  The position of the token.
413
     * @param string               $name      The class / function / constant name.
414
     *
415
     * @return string
416
     */
417
    public function getFQName(PHP_CodeSniffer_File $phpcsFile, $stackPtr, $name)
418
    {
419
        if (strpos($name, '\\' ) === 0) {
420
            // Already fully qualified.
421
            return $name;
422
        }
423
424
        // Remove the namespace keyword if used.
425
        if (strpos($name, 'namespace\\') === 0) {
426
            $name = substr($name, 10);
427
        }
428
429
        $namespace = $this->determineNamespace($phpcsFile, $stackPtr);
430
431
        if ($namespace === '') {
432
            return '\\' . $name;
433
        }
434
        else {
435
            return '\\' . $namespace . '\\' . $name;
436
        }
437
    }
438
439
440
    /**
441
     * Is the class/function/constant name namespaced or global ?
442
     *
443
     * @param string $FQName Fully Qualified name of a class, function etc.
444
     *                       I.e. should always start with a `\` !
445
     *
446
     * @return bool True if namespaced, false if global.
447
     */
448
    public function isNamespaced($FQName) {
449
        if (strpos($FQName, '\\') !== 0) {
450
            throw new PHP_CodeSniffer_Exception('$FQName must be a fully qualified name');
451
        }
452
453
        return (strpos(substr($FQName, 1), '\\') !== false);
454
    }
455
456
457
    /**
458
     * Determine the namespace name an arbitrary token lives in.
459
     *
460
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
461
     * @param int                  $stackPtr  The token position for which to determine the namespace.
462
     *
463
     * @return string Namespace name or empty string if it couldn't be determined or no namespace applies.
464
     */
465
    public function determineNamespace(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
466
    {
467
        $tokens = $phpcsFile->getTokens();
468
469
        // Check for the existence of the token.
470
        if (isset($tokens[$stackPtr]) === false) {
471
            return '';
472
        }
473
474
        // Check for scoped namespace {}.
475
        if (empty($tokens[$stackPtr]['conditions']) === false) {
476
            foreach ($tokens[$stackPtr]['conditions'] as $pointer => $type) {
477
                if ($type === T_NAMESPACE) {
478
                    $namespace = $this->getDeclaredNamespaceName($phpcsFile, $pointer);
479
                    if ($namespace !== false) {
480
                        return $namespace;
481
                    }
482
                }
483
                break; // We only need to check the highest level condition.
484
            }
485
        }
486
487
        /*
488
         * Not in a scoped namespace, so let's see if we can find a non-scoped namespace instead.
489
         * Keeping in mind that:
490
         * - there can be multiple non-scoped namespaces in a file (bad practice, but it happens).
491
         * - the namespace keyword can also be used as part of a function/method call and such.
492
         * - that a non-named namespace resolves to the global namespace.
493
         */
494
        $previousNSToken = $stackPtr;
495
        $namespace       = false;
496
        do {
497
            $previousNSToken = $phpcsFile->findPrevious(T_NAMESPACE, $previousNSToken -1);
498
499
            // Stop if we encounter a scoped namespace declaration as we already know we're not in one.
500
            if (empty($tokens[$previousNSToken]['scope_condition']) === false && $tokens[$previousNSToken]['scope_condition'] = $previousNSToken) {
501
                break;
502
            }
503
            $namespace = $this->getDeclaredNamespaceName($phpcsFile, $previousNSToken);
504
505
        } while ($namespace === false && $previousNSToken !== false);
506
507
        // If we still haven't got a namespace, return an empty string.
508
        if ($namespace === false) {
509
            return '';
510
        }
511
        else {
512
            return $namespace;
513
        }
514
    }
515
516
    /**
517
     * Get the complete namespace name for a namespace declaration.
518
     *
519
     * For hierarchical namespaces, the name will be composed of several tokens,
520
     * i.e. MyProject\Sub\Level which will be returned together as one string.
521
     *
522
     * @param PHP_CodeSniffer_File $phpcsFile Instance of phpcsFile.
523
     * @param int|bool             $stackPtr  The position of a T_NAMESPACE token.
524
     *
525
     * @return string|false Namespace name or false if not a namespace declaration.
526
     *                      Namespace name can be an empty string for global namespace declaration.
527
     */
528
    public function getDeclaredNamespaceName(PHP_CodeSniffer_File $phpcsFile, $stackPtr )
529
    {
530
        $tokens = $phpcsFile->getTokens();
531
532
        // Check for the existence of the token.
533
        if ($stackPtr === false || isset($tokens[$stackPtr]) === false) {
534
            return false;
535
        }
536
537
        if ($tokens[$stackPtr]['code'] !== T_NAMESPACE) {
538
            return false;
539
        }
540
541
        if ($tokens[$stackPtr + 1]['code'] === T_NS_SEPARATOR) {
542
            // Not a namespace declaration, but use of, i.e. namespace\someFunction();
543
            return false;
544
        }
545
546
        $nextToken = $phpcsFile->findNext(PHP_CodeSniffer_Tokens::$emptyTokens, $stackPtr + 1, null, true, null, true);
547
        if ($tokens[$nextToken]['code'] === T_OPEN_CURLY_BRACKET) {
548
            // Declaration for global namespace when using multiple namespaces in a file.
549
            // I.e.: namespace {}
1 ignored issue
show
Unused Code Comprehensibility introduced by
37% 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...
550
            return '';
551
        }
552
553
        // Ok, this should be a namespace declaration, so get all the parts together.
554
        $validTokens = array(
555
                        T_STRING,
556
                        T_NS_SEPARATOR,
557
                        T_WHITESPACE,
558
                       );
559
560
        $namespaceName = '';
561
        while(in_array($tokens[$nextToken]['code'], $validTokens, true) === true) {
562
            $namespaceName .= trim($tokens[$nextToken]['content']);
563
            $nextToken++;
564
        }
565
566
        return $namespaceName;
567
    }
568
569
}//end class
570