Completed
Push — master ( 9cb63b...91066a )
by Wim
8s
created

PHPCompatibility_Sniffs_PHP_ValidIntegersSniff   A

Complexity

Total Complexity 27

Size/Duplication

Total Lines 192
Duplicated Lines 21.35 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 27
c 1
b 0
f 1
lcom 1
cbo 2
dl 41
loc 192
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 10 1
C process() 23 52 9
B couldBeBinaryInteger() 0 16 5
A isInvalidBinaryInteger() 0 13 3
A getBinaryInteger() 0 13 3
A isInvalidOctalInteger() 9 9 3
A isHexidecimalNumericString() 9 9 3

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/**
3
 * PHPCompatibility_Sniffs_PHP_ValidIntegersSniff.
4
 *
5
 * @category  PHP
6
 * @package   PHPCompatibility
7
 * @author    Juliette Reinders Folmer <[email protected]>
8
 */
9
10
/**
11
 * PHPCompatibility_Sniffs_PHP_ValidIntegersSniff.
12
 *
13
 * @category  PHP
14
 * @package   PHPCompatibility
15
 * @author    Juliette Reinders Folmer <[email protected]>
16
 */
17
class PHPCompatibility_Sniffs_PHP_ValidIntegersSniff extends PHPCompatibility_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...
18
{
19
    protected $isLowPHPVersion = false;
20
21
    /**
22
     * Returns an array of tokens this test wants to listen for.
23
     *
24
     * @return array
25
     */
26
    public function register()
27
    {
28
        $this->isLowPHPVersion = version_compare(phpversion(), '5.4', '<');
29
30
        return array(
31
                T_LNUMBER, // Binary, octal integers.
32
                T_CONSTANT_ENCAPSED_STRING, // Hex numeric string.
33
               );
34
35
    }//end register()
36
37
38
    /**
39
     * Processes this test, when one of its tokens is encountered.
40
     *
41
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
42
     * @param int                  $stackPtr  The position of the current token in
43
     *                                        the stack.
44
     *
45
     * @return void
46
     */
47
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
48
    {
49
        $tokens = $phpcsFile->getTokens();
50
        $token  = $tokens[$stackPtr];
51
52
        if ($this->couldBeBinaryInteger($tokens, $stackPtr) === true) {
53
            if ($this->supportsBelow('5.3')) {
54
                $error = 'Binary integer literals were not present in PHP version 5.3 or earlier. Found: %s';
55
                if ($this->isLowPHPVersion === false) {
56
                    $data = array($token['content']);
57
                }
58
                else {
59
                    $data = array($this->getBinaryInteger($phpcsFile, $tokens, $stackPtr));
60
                }
61
                $phpcsFile->addError($error, $stackPtr, 'BinaryIntegerFound', $data);
62
            }
63
64
            if ($this->isInvalidBinaryInteger($tokens, $stackPtr) === true) {
65
                $error = 'Invalid binary integer detected. Found: %s';
66
                $data  = array($this->getBinaryInteger($phpcsFile, $tokens, $stackPtr));
67
                $phpcsFile->addError($error, $stackPtr, 'InvalidBinaryIntegerFound', $data);
68
            }
69
            return;
70
        }
71
72
        $data = array( $token['content'] );
73 View Code Duplication
        if ($this->isInvalidOctalInteger($tokens, $stackPtr) === true) {
1 ignored issue
show
Duplication introduced by
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...
74
            $error   = 'Invalid octal integer detected. Prior to PHP 7 this would lead to a truncated number. From PHP 7 onwards this causes a parse error. Found: %s';
75
            $isError = $this->supportsAbove('7.0');
76
77
            if ($isError === true) {
78
                $phpcsFile->addError($error, $stackPtr, 'InvalidOctalIntegerFound', $data);
79
            } else {
80
                $phpcsFile->addWarning($error, $stackPtr, 'InvalidOctalIntegerFound', $data);
81
            }
82
83
            return;
84
        }
85
86 View Code Duplication
        if ($this->isHexidecimalNumericString($tokens, $stackPtr) === true) {
1 ignored issue
show
Duplication introduced by
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...
87
            $error   = 'The behaviour of hexadecimal numeric strings was inconsistent prior to PHP 7 and support has been removed in PHP 7. Found: %s';
88
            $isError = $this->supportsAbove('7.0');
89
90
            if ($isError === true) {
91
                $phpcsFile->addError($error, $stackPtr, 'HexNumericStringFound', $data);
92
            } else {
93
                $phpcsFile->addWarning($error, $stackPtr, 'HexNumericStringFound', $data);
94
            }
95
            return;
96
        }
97
98
    }//end process()
99
100
101
    /**
102
     * Could the current token an potentially be a binary integer ?
103
     *
104
     * @param array $token    Token stack.
0 ignored issues
show
Documentation introduced by
There is no parameter named $token. Did you maybe mean $tokens?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
105
     * @param int   $stackPtr The current position in the token stack.
106
     *
107
     * @return bool
108
     */
109
    private function couldBeBinaryInteger($tokens, $stackPtr) {
110
        $token = $tokens[$stackPtr];
111
112
        if ($token['code'] !== T_LNUMBER) {
113
            return false;
114
        }
115
116
        if ($this->isLowPHPVersion === false) {
117
            return (preg_match('`^0b[0-1]+$`D', $token['content']) === 1);
118
        }
119
        // Pre-5.4, binary strings are tokenized as T_LNUMBER (0) + T_STRING ("b01010101").
120
        // At this point, we don't yet care whether it's a valid binary int, that's a separate check.
121
        else {
122
            return($token['content'] === '0' && $tokens[$stackPtr+1]['code'] === T_STRING && preg_match('`^b[0-9]+$`D', $tokens[$stackPtr+1]['content']) === 1);
123
        }
124
    }
125
126
    /**
127
     * Is the current token an invalid binary integer ?
128
     *
129
     * @param array $token    Token stack.
0 ignored issues
show
Documentation introduced by
There is no parameter named $token. Did you maybe mean $tokens?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
130
     * @param int   $stackPtr The current position in the token stack.
131
     *
132
     * @return bool
133
     */
134
    private function isInvalidBinaryInteger($tokens, $stackPtr) {
135
        if ($this->couldBeBinaryInteger($tokens, $stackPtr) === false) {
136
            return false;
137
        }
138
139
        if ($this->isLowPHPVersion === false) {
140
            // If it's an invalid binary int, the token will be split into two T_LNUMBER tokens.
141
            return ($tokens[$stackPtr+1]['code'] === T_LNUMBER);
142
        }
143
        else {
144
            return (preg_match('`^b[0-1]+$`D', $tokens[$stackPtr+1]['content']) === 0);
145
        }
146
    }
147
148
    /**
149
     * Retrieve the content of the tokens which together look like a binary integer.
150
     *
151
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
152
     * @param array                $token     Token stack.
0 ignored issues
show
Documentation introduced by
There is no parameter named $token. Did you maybe mean $tokens?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
153
     * @param int                  $stackPtr  The position of the current token in
154
     *                                        the stack.
155
     *
156
     * @return string
157
     */
158
    private function getBinaryInteger(PHP_CodeSniffer_File $phpcsFile, $tokens, $stackPtr) {
159
        $length = 2; // PHP < 5.4 T_LNUMBER + T_STRING
160
161
        if ($this->isLowPHPVersion === false) {
162
            $i = $stackPtr;
163
            while ($tokens[$i]['code'] === T_LNUMBER) {
164
                $i++;
165
            }
166
            $length = ($i - $stackPtr);
167
        }
168
169
        return $phpcsFile->getTokensAsString($stackPtr, $length);
170
    }
171
172
    /**
173
     * Is the current token an invalid octal integer ?
174
     *
175
     * @param array $token    Token stack.
0 ignored issues
show
Documentation introduced by
There is no parameter named $token. Did you maybe mean $tokens?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
176
     * @param int   $stackPtr The current position in the token stack.
177
     *
178
     * @return bool
179
     */
180 View Code Duplication
    private function isInvalidOctalInteger($tokens, $stackPtr) {
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...
181
        $token = $tokens[$stackPtr];
182
183
        if ($token['code'] === T_LNUMBER && preg_match('`^0[0-7]*[8-9]+[0-9]*$`D', $token['content']) === 1) {
184
            return true;
185
        }
186
187
        return false;
188
    }
189
190
    /**
191
     * Is the current token a hexidecimal numeric string ?
192
     *
193
     * @param array $token    Token stack.
0 ignored issues
show
Documentation introduced by
There is no parameter named $token. Did you maybe mean $tokens?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
194
     * @param int   $stackPtr The current position in the token stack.
195
     *
196
     * @return bool
197
     */
198 View Code Duplication
    private function isHexidecimalNumericString($tokens, $stackPtr) {
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...
199
        $token = $tokens[$stackPtr];
200
201
        if ($token['code'] === T_CONSTANT_ENCAPSED_STRING && preg_match('`^([\'"])0x[a-f0-9]+\1$`iD', $token['content']) === 1) {
202
            return true;
203
        }
204
205
        return false;
206
    }
207
208
}//end class
209