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

ShortListSniff::process()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 27
rs 8.5806
c 0
b 0
f 0
cc 4
eloc 15
nc 4
nop 2
1
<?php
2
/**
3
 * \PHPCompatibility\Sniffs\Lists\ShortListSniff.
4
 *
5
 * PHP version 7.1
6
 *
7
 * @category PHP
8
 * @package  PHPCompatibility
9
 * @author   Juliette Reinders Folmer <[email protected]>
10
 */
11
12
namespace PHPCompatibility\Sniffs\Lists;
13
14
use PHPCompatibility\Sniff;
15
16
/**
17
 * \PHPCompatibility\Sniffs\Lists\ShortListSniff.
18
 *
19
 * "The shorthand array syntax ([]) may now be used to destructure arrays for
20
 * assignments (including within foreach), as an alternative to the existing
21
 * list() syntax, which is still supported."
22
 *
23
 * PHP version 7.1
24
 *
25
 * @category PHP
26
 * @package  PHPCompatibility
27
 * @author   Juliette Reinders Folmer <[email protected]>
28
 */
29
class ShortListSniff extends Sniff
30
{
31
32
    /**
33
     * Returns an array of tokens this test wants to listen for.
34
     *
35
     * @return array
36
     */
37
    public function register()
38
    {
39
        return array(T_OPEN_SHORT_ARRAY);
40
    }
41
42
    /**
43
     * Processes this test, when one of its tokens is encountered.
44
     *
45
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
46
     * @param int                   $stackPtr  The position of the current token in the
47
     *                                         stack passed in $tokens.
48
     *
49
     * @return void
50
     */
51
    public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
52
    {
53
        if ($this->supportsBelow('7.0') === false) {
54
            return;
55
        }
56
57
        if ($this->isShortList($phpcsFile, $stackPtr) === false) {
58
            return;
59
        }
60
61
        $tokens = $phpcsFile->getTokens();
62
        $closer = $tokens[$stackPtr]['bracket_closer'];
63
64
        $hasVariable = $phpcsFile->findNext(T_VARIABLE, ($stackPtr + 1), $closer);
65
        if ($hasVariable === false) {
66
            // List syntax is only valid if there are variables in it.
67
            return;
68
        }
69
70
        $phpcsFile->addError(
71
            'The shorthand list syntax "[]" to destructure arrays is not available in PHP 7.0 or earlier.',
72
            $stackPtr,
73
            'Found'
74
        );
75
76
        return ($closer + 1);
77
    }
78
}
79