Completed
Push — feature/rename-phpunit-config ( 357a24...3649e1 )
by Juliette
03:31 queued 01:25
created

NewLanguageConstructsSniff   A

Complexity

Total Complexity 32

Size/Duplication

Total Lines 280
Duplicated Lines 3.93 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 32
lcom 1
cbo 1
dl 11
loc 280
rs 9.6
c 0
b 0
f 0

8 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 12 4
C process() 0 34 11
A getItemArray() 0 4 1
A getNonVersionArrayKeys() 0 4 1
A getErrorInfo() 0 8 1
A filterErrorData() 0 5 1
B isTCoalesceEqual() 4 18 7
B isTCoalesce() 7 16 6

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\NewLanguageConstructsSniff.
4
 *
5
 * @category  PHP
6
 * @package   PHPCompatibility
7
 * @author    Wim Godden <[email protected]>
8
 * @copyright 2013 Cu.be Solutions bvba
9
 */
10
11
namespace PHPCompatibility\Sniffs\PHP;
12
13
use PHPCompatibility\AbstractNewFeatureSniff;
14
15
/**
16
 * \PHPCompatibility\Sniffs\PHP\NewLanguageConstructsSniff.
17
 *
18
 * @category  PHP
19
 * @package   PHPCompatibility
20
 * @author    Wim Godden <[email protected]>
21
 * @copyright 2013 Cu.be Solutions bvba
22
 */
23
class NewLanguageConstructsSniff extends AbstractNewFeatureSniff
24
{
25
26
    /**
27
     * A list of new language constructs, not present in older versions.
28
     *
29
     * The array lists : version number with false (not present) or true (present).
30
     * If's sufficient to list the first version where the keyword appears.
31
     *
32
     * @var array(string => array(string => int|string|null))
33
     */
34
    protected $newConstructs = array(
35
        'T_NS_SEPARATOR' => array(
36
            '5.2' => false,
37
            '5.3' => true,
38
            'description' => 'the \ operator (for namespaces)',
39
        ),
40
        'T_POW' => array(
41
            '5.5' => false,
42
            '5.6' => true,
43
            'description' => 'power operator (**)',
44
        ), // Identified in PHPCS 1.5 as T_MULTIPLY + T_MULTIPLY.
45
        'T_POW_EQUAL' => array(
46
            '5.5' => false,
47
            '5.6' => true,
48
            'description' => 'power assignment operator (**=)',
49
        ), // Identified in PHPCS 1.5 as T_MULTIPLY + T_MUL_EQUAL.
50
        'T_ELLIPSIS' => array(
51
            '5.5' => false,
52
            '5.6' => true,
53
            'description' => 'variadic functions using ...',
54
        ),
55
        'T_SPACESHIP' => array(
56
            '5.6' => false,
57
            '7.0' => true,
58
            'description' => 'spaceship operator (<=>)',
59
        ), // Identified in PHPCS 1.5 as T_IS_SMALLER_OR_EQUAL + T_GREATER_THAN.
60
        'T_COALESCE' => array(
61
            '5.6' => false,
62
            '7.0' => true,
63
            'description' => 'null coalescing operator (??)',
64
        ), // Identified in PHPCS 1.5 as T_INLINE_THEN + T_INLINE_THEN.
65
        'T_COALESCE_EQUAL' => array(
66
            '7.1' => false,
67
            '7.2' => true,
68
            'description' => 'null coalesce equal operator (??=)',
69
        ), // Identified in PHPCS 1.5 as T_INLINE_THEN + T_INLINE_THEN + T_EQUAL and pre-PHPCS 2.8.1 as T_COALESCE + T_EQUAL.
70
    );
71
72
73
    /**
74
     * A list of new language constructs which are not recognized in PHPCS 1.x.
75
     *
76
     * The array lists an alternative token to listen for.
77
     *
78
     * @var array(string => int)
79
     */
80
    protected $newConstructsPHPCSCompat = array(
81
        'T_POW'            => T_MULTIPLY,
82
        'T_POW_EQUAL'      => T_MUL_EQUAL,
83
        'T_SPACESHIP'      => T_GREATER_THAN,
84
        'T_COALESCE'       => T_INLINE_THEN,
85
        'T_COALESCE_EQUAL' => T_EQUAL,
86
    );
87
88
    /**
89
     * Translation table for PHPCS 1.x and older 2.x tokens.
90
     *
91
     * The 'before' index lists the token which would have to be directly before the
92
     * token found for it to be one of the new language constructs.
93
     * The 'real_token' index indicates which language construct was found in that case.
94
     *
95
     * If the token combination has multi-layer complexity, such as is the case
96
     * with T_COALESCE(_EQUAL), a 'callback' index is added instead pointing to a
97
     * separate function which can determine whether this is the targetted token across
98
     * PHP and PHPCS versions.
99
     *
100
     * {@internal 'before' was chosen rather than 'after' as that allowed for a 1-on-1
101
     * translation list with the current tokens.}}
102
     *
103
     * @var array(string => array(string => string))
104
     */
105
    protected $PHPCSCompatTranslate = array(
106
        'T_MULTIPLY' => array(
107
            'before' => 'T_MULTIPLY',
108
            'real_token' => 'T_POW',
109
        ),
110
        'T_MUL_EQUAL' => array(
111
            'before' => 'T_MULTIPLY',
112
            'real_token' => 'T_POW_EQUAL',
113
        ),
114
        'T_GREATER_THAN' => array(
115
            'before' => 'T_IS_SMALLER_OR_EQUAL',
116
            'real_token' => 'T_SPACESHIP',
117
        ),
118
        'T_INLINE_THEN' => array(
119
            'callback' => 'isTCoalesce',
120
            'real_token' => 'T_COALESCE',
121
        ),
122
        'T_EQUAL' => array(
123
            'callback' => 'isTCoalesceEqual',
124
            'real_token' => 'T_COALESCE_EQUAL',
125
        ),
126
    );
127
128
    /**
129
     * Returns an array of tokens this test wants to listen for.
130
     *
131
     * @return array
132
     */
133
    public function register()
134
    {
135
        $tokens = array();
136
        foreach ($this->newConstructs as $token => $versions) {
137
            if (defined($token)) {
138
                $tokens[] = constant($token);
139
            } elseif (isset($this->newConstructsPHPCSCompat[$token])) {
140
                $tokens[] = $this->newConstructsPHPCSCompat[$token];
141
            }
142
        }
143
        return $tokens;
144
    }//end register()
145
146
147
    /**
148
     * Processes this test, when one of its tokens is encountered.
149
     *
150
     * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned.
151
     * @param int                   $stackPtr  The position of the current token in
152
     *                                         the stack passed in $tokens.
153
     *
154
     * @return void
155
     */
156
    public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr)
157
    {
158
        $tokens    = $phpcsFile->getTokens();
159
        $tokenType = $tokens[$stackPtr]['type'];
160
161
        // Translate older PHPCS token combis for new constructs to the actual construct.
162
        if (isset($this->newConstructs[$tokenType]) === false) {
163
            if (isset($this->PHPCSCompatTranslate[$tokenType])
164
                && ((isset($this->PHPCSCompatTranslate[$tokenType]['before'], $tokens[$stackPtr - 1]) === true
165
                    && $tokens[$stackPtr - 1]['type'] === $this->PHPCSCompatTranslate[$tokenType]['before'])
166
                || (isset($this->PHPCSCompatTranslate[$tokenType]['callback']) === true
167
                    && call_user_func(array($this, $this->PHPCSCompatTranslate[$tokenType]['callback']), $tokens, $stackPtr) === true))
168
            ) {
169
                $tokenType = $this->PHPCSCompatTranslate[$tokenType]['real_token'];
170
            }
171
        } elseif ($tokenType === 'T_COALESCE') {
172
            // Make sure that T_COALESCE is not confused with T_COALESCE_EQUAL.
173
            if (isset($tokens[($stackPtr + 1)]) !== false && $tokens[($stackPtr + 1)]['code'] === T_EQUAL) {
174
                // Ignore as will be dealt with via the T_EQUAL token.
175
                return;
176
            }
177
        }
178
179
        // If the translation did not yield one of the tokens we are looking for, bow out.
180
        if (isset($this->newConstructs[$tokenType]) === false) {
181
            return;
182
        }
183
184
        $itemInfo = array(
185
            'name'   => $tokenType,
186
        );
187
        $this->handleFeature($phpcsFile, $stackPtr, $itemInfo);
188
189
    }//end process()
190
191
192
    /**
193
     * Get the relevant sub-array for a specific item from a multi-dimensional array.
194
     *
195
     * @param array $itemInfo Base information about the item.
196
     *
197
     * @return array Version and other information about the item.
198
     */
199
    public function getItemArray(array $itemInfo)
200
    {
201
        return $this->newConstructs[$itemInfo['name']];
202
    }
203
204
205
    /**
206
     * Get an array of the non-PHP-version array keys used in a sub-array.
207
     *
208
     * @return array
209
     */
210
    protected function getNonVersionArrayKeys()
211
    {
212
        return array('description');
213
    }
214
215
216
    /**
217
     * Retrieve the relevant detail (version) information for use in an error message.
218
     *
219
     * @param array $itemArray Version and other information about the item.
220
     * @param array $itemInfo  Base information about the item.
221
     *
222
     * @return array
223
     */
224
    public function getErrorInfo(array $itemArray, array $itemInfo)
225
    {
226
        $errorInfo = parent::getErrorInfo($itemArray, $itemInfo);
227
        $errorInfo['description'] = $itemArray['description'];
228
229
        return $errorInfo;
230
231
    }
232
233
234
    /**
235
     * Allow for concrete child classes to filter the error data before it's passed to PHPCS.
236
     *
237
     * @param array $data      The error data array which was created.
238
     * @param array $itemInfo  Base information about the item this error message applied to.
239
     * @param array $errorInfo Detail information about an item this error message applied to.
240
     *
241
     * @return array
242
     */
243
    protected function filterErrorData(array $data, array $itemInfo, array $errorInfo)
244
    {
245
        $data[0] = $errorInfo['description'];
246
        return $data;
247
    }
248
249
250
    /**
251
     * Callback function to determine whether a T_EQUAL token is really a T_COALESCE_EQUAL token.
252
     *
253
     * @param array $tokens   The token stack.
254
     * @param int   $stackPtr The current position in the token stack.
255
     *
256
     * @return bool
257
     */
258
    private function isTCoalesceEqual($tokens, $stackPtr)
259
    {
260 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_EQUAL || isset($tokens[($stackPtr - 1)]) === false) {
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...
261
            // Function called for wrong token or token has no predecesor.
262
            return false;
263
        }
264
265
        if ($tokens[($stackPtr - 1)]['type'] === 'T_COALESCE') {
266
            return true;
267
        }
268
        if ($tokens[($stackPtr - 1)]['type'] === 'T_INLINE_THEN'
269
            && ( isset($tokens[($stackPtr - 2)]) && $tokens[($stackPtr - 2)]['type'] === 'T_INLINE_THEN')
270
        ) {
271
            return true;
272
        }
273
274
        return false;
275
    }
276
277
    /**
278
     * Callback function to determine whether a T_INLINE_THEN token is really a T_COALESCE token.
279
     *
280
     * @param array $tokens   The token stack.
281
     * @param int   $stackPtr The current position in the token stack.
282
     *
283
     * @return bool
284
     */
285
    private function isTCoalesce($tokens, $stackPtr)
286
    {
287 View Code Duplication
        if ($tokens[$stackPtr]['code'] !== T_INLINE_THEN || isset($tokens[($stackPtr - 1)]) === false) {
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...
288
            // Function called for wrong token or token has no predecesor.
289
            return false;
290
        }
291
292
        if ($tokens[($stackPtr - 1)]['code'] === T_INLINE_THEN) {
293
            // Make sure not to confuse it with the T_COALESCE_EQUAL token.
294 View Code Duplication
            if (isset($tokens[($stackPtr + 1)]) === false || $tokens[($stackPtr + 1)]['code'] !== T_EQUAL) {
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...
295
                return true;
296
            }
297
        }
298
299
        return false;
300
    }
301
302
}//end class
303