Completed
Push — php-5.5/new-lists-in-foreach-s... ( dd34ac )
by Juliette
07:23 queued 05:16
created

NewListInForeachSniff::process()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 31
Code Lines 18

Duplication

Lines 3
Ratio 9.68 %

Importance

Changes 0
Metric Value
dl 3
loc 31
rs 8.439
c 0
b 0
f 0
cc 5
eloc 18
nc 5
nop 2
1
<?php
2
/**
3
 * \PHPCompatibility\Sniffs\Lists\NewListInForeachSniff.
4
 *
5
 * PHP version 5.5
6
 *
7
 * @category PHP
8
 * @package  PHPCompatibility\Lists
9
 * @author   Juliette Reinders Folmer <[email protected]>
10
 */
11
12
namespace PHPCompatibility\Sniffs\Lists;
13
14
use PHPCompatibility\Sniff;
15
use PHPCompatibility\PHPCSHelper;
16
17
/**
18
 * \PHPCompatibility\Sniffs\Lists\NewListInForeachSniff.
19
 *
20
 * Detect unpacking nested arrays with list() in a foreach().
21
 *
22
 * PHP version 5.5
23
 *
24
 * @category PHP
25
 * @package  PHPCompatibility\Lists
26
 * @author   Juliette Reinders Folmer <[email protected]>
27
 */
28
class NewListInForeachSniff extends Sniff
29
{
30
31
    /**
32
     * Returns an array of tokens this test wants to listen for.
33
     *
34
     * @return array
35
     */
36
    public function register()
37
    {
38
        return array(T_FOREACH);
39
    }
40
41
    /**
42
     * Processes this test, when one of its tokens is encountered.
43
     *
44
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
45
     * @param int                   $stackPtr  The position of the current token in the
46
     *                                         stack passed in $tokens.
47
     *
48
     * @return void
49
     */
50
    public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
51
    {
52
        if ($this->supportsBelow('5.4') === false) {
53
            return;
54
        }
55
56
        $tokens = $phpcsFile->getTokens();
57
58 View Code Duplication
        if (isset($tokens[$stackPtr]['parenthesis_opener'], $tokens[$stackPtr]['parenthesis_closer']) === false) {
59
            return;
60
        }
61
62
        $opener = $tokens[$stackPtr]['parenthesis_opener'];
63
        $closer = $tokens[$stackPtr]['parenthesis_closer'];
64
65
        $asToken = $phpcsFile->findNext(T_AS, ($opener + 1), $closer);
66
        if ($asToken === false) {
67
            return;
68
        }
69
70
        $hasList = $phpcsFile->findNext(array(T_LIST, T_OPEN_SHORT_ARRAY), ($asToken + 1), $closer);
71
        if ($hasList === false) {
72
            return;
73
        }
74
75
        $phpcsFile->addError(
76
            'Unpacking nested arrays with list() in a foreach is not supported in PHP 5.4 or earlier.',
77
            $hasList,
78
            'Found'
79
        );
80
    }
81
}
82