Completed
Push — master ( 01d73e...c6357c )
by Juliette
03:01
created

Sniff.php (10 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
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, T_OPEN_SHORT_ARRAY), $nextComma + 1, $closeParenthesis + 1)) {
283
            // Ignore anything within short array definition brackets.
284
            if (
285
                $tokens[$nextComma]['type'] === 'T_OPEN_SHORT_ARRAY'
286
                &&
287
                ( isset($tokens[$nextComma]['bracket_opener']) && $tokens[$nextComma]['bracket_opener'] === $nextComma )
288
                &&
289
                isset($tokens[$nextComma]['bracket_closer'])
290
            ) {
291
                // Skip forward to the end of the short array definition.
292
                $nextComma = $tokens[$nextComma]['bracket_closer'];
293
                continue;
294
            }
295
296
            // Ignore comma's at a lower nesting level.
297
            if (
298
                $tokens[$nextComma]['type'] === 'T_COMMA'
299
                &&
300
                isset($tokens[$nextComma]['nested_parenthesis'])
301
                &&
302
                count($tokens[$nextComma]['nested_parenthesis']) !== $nestedParenthesisCount
303
            ) {
304
                continue;
305
            }
306
307
            // Ignore closing parenthesis if not 'ours'.
308
            if ($tokens[$nextComma]['type'] === 'T_CLOSE_PARENTHESIS' && $nextComma !== $closeParenthesis) {
309
                continue;
310
            }
311
312
            // Ok, we've reached the end of the parameter.
313
            $parameters[$cnt]['start'] = $paramStart;
314
            $parameters[$cnt]['end']   = $nextComma - 1;
315
            $parameters[$cnt]['raw']   = trim($phpcsFile->getTokensAsString($paramStart, ($nextComma - $paramStart)));
316
317
            // Check if there are more tokens before the closing parenthesis.
318
            // Prevents code like the following from setting a third parameter:
319
            // functionCall( $param1, $param2, );
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

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