Completed
Pull Request — master (#162)
by Juliette
04:33
created

PHPCompatibility_Sniff::getTestVersion()   C

Complexity

Conditions 8
Paths 12

Size

Total Lines 41
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

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