Completed
Push — master ( caee53...282cb8 )
by Juliette
9s
created

processClassToken()   C

Complexity

Conditions 11
Paths 23

Size

Total Lines 51
Code Lines 31

Duplication

Lines 7
Ratio 13.73 %

Importance

Changes 0
Metric Value
dl 7
loc 51
rs 5.7333
c 0
b 0
f 0
cc 11
eloc 31
nc 23
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * PHPCompatibility_Sniffs_PHP_NewInterfacesSniff.
4
 *
5
 * PHP version 5.5
6
 *
7
 * @category  PHP
8
 * @package   PHPCompatibility
9
 * @author    Juliette Reinders Folmer <[email protected]>
10
 */
11
12
/**
13
 * PHPCompatibility_Sniffs_PHP_NewInterfacesSniff.
14
 *
15
 * @category  PHP
16
 * @package   PHPCompatibility
17
 * @author    Juliette Reinders Folmer <[email protected]>
18
 */
19
class PHPCompatibility_Sniffs_PHP_NewInterfacesSniff extends PHPCompatibility_AbstractNewFeatureSniff
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...
20
{
21
22
    /**
23
     * A list of new interfaces, not present in older versions.
24
     *
25
     * The array lists : version number with false (not present) or true (present).
26
     * If's sufficient to list the first version where the interface appears.
27
     *
28
     * @var array(string => array(string => int|string|null))
29
     */
30
    protected $newInterfaces = array(
31
                                'Traversable' => array(
32
                                    '4.4' => false,
33
                                    '5.0' => true
34
                                ),
35
36
                                'Countable' => array(
37
                                    '5.0' => false,
38
                                    '5.1' => true
39
                                ),
40
                                'OuterIterator' => array(
41
                                    '5.0' => false,
42
                                    '5.1' => true
43
                                ),
44
                                'RecursiveIterator' => array(
45
                                    '5.0' => false,
46
                                    '5.1' => true
47
                                ),
48
                                'SeekableIterator' => array(
49
                                    '5.0' => false,
50
                                    '5.1' => true
51
                                ),
52
                                'Serializable' => array(
53
                                    '5.0' => false,
54
                                    '5.1' => true,
55
                                ),
56
                                'SplObserver' => array(
57
                                    '5.0' => false,
58
                                    '5.1' => true
59
                                ),
60
                                'SplSubject' => array(
61
                                    '5.0' => false,
62
                                    '5.1' => true
63
                                ),
64
65
                                'JsonSerializable' => array(
66
                                    '5.3' => false,
67
                                    '5.4' => true
68
                                ),
69
                                'SessionHandlerInterface' => array(
70
                                    '5.3' => false,
71
                                    '5.4' => true
72
                                ),
73
74
                                'DateTimeInterface' => array(
75
                                    '5.4' => false,
76
                                    '5.5' => true
77
                                ),
78
79
                                'Throwable' => array(
80
                                    '5.6' => false,
81
                                    '7.0' => true
82
                                ),
83
84
                               );
85
86
    /**
87
     * A list of methods which cannot be used in combination with particular interfaces.
88
     *
89
     * @var array(string => array(string => string))
90
     */
91
    protected $unsupportedMethods = array(
92
                                     'Serializable' => array(
93
                                         '__sleep'  => 'http://php.net/serializable',
94
                                         '__wakeup' => 'http://php.net/serializable',
95
                                     ),
96
                                    );
97
98
    /**
99
     * Returns an array of tokens this test wants to listen for.
100
     *
101
     * @return array
102
     */
103
    public function register()
104
    {
105
        // Handle case-insensitivity of interface names.
106
        $this->newInterfaces      = $this->arrayKeysToLowercase($this->newInterfaces);
107
        $this->unsupportedMethods = $this->arrayKeysToLowercase($this->unsupportedMethods);
108
109
        $targets = array(
110
            T_CLASS,
111
            T_FUNCTION,
112
            T_CLOSURE,
113
        );
114
115
        if (defined('T_ANON_CLASS')) {
116
            $targets[] = constant('T_ANON_CLASS');
117
        }
118
119
        return $targets;
120
121
    }//end register()
122
123
124
    /**
125
     * Processes this test, when one of its tokens is encountered.
126
     *
127
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
128
     * @param int                  $stackPtr  The position of the current token in
129
     *                                        the stack passed in $tokens.
130
     *
131
     * @return void
132
     */
133
    public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
134
    {
135
        $tokens = $phpcsFile->getTokens();
136
137
        switch($tokens[$stackPtr]['type']) {
138
            case 'T_CLASS':
139
            case 'T_ANON_CLASS':
140
                $this->processClassToken($phpcsFile, $stackPtr);
141
                break;
142
143
            case 'T_FUNCTION':
144
            case 'T_CLOSURE':
145
                $this->processFunctionToken($phpcsFile, $stackPtr);
146
                break;
147
148
            default:
149
                // Deliberately left empty.
150
                break;
151
        }
152
153
    }//end process()
154
155
156
    /**
157
     * Processes this test for when a class token is encountered.
158
     *
159
     * - Detect classes implementing the new interfaces.
160
     * - Detect classes implementing the new interfaces with unsupported functions.
161
     *
162
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
163
     * @param int                  $stackPtr  The position of the current token in
164
     *                                        the stack passed in $tokens.
165
     *
166
     * @return void
167
     */
168
    private function processClassToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
169
    {
170
        $interfaces = $this->findImplementedInterfaceNames($phpcsFile, $stackPtr);
171
172
        if (is_array($interfaces) === false || $interfaces === array()) {
173
            return;
174
        }
175
176
        $tokens       = $phpcsFile->getTokens();
177
        $checkMethods = false;
178
179
        if(isset($tokens[$stackPtr]['scope_closer'])) {
180
            $checkMethods = true;
181
            $scopeCloser = $tokens[$stackPtr]['scope_closer'];
182
        }
183
184
        foreach ($interfaces as $interface) {
185
            $interfaceLc = strtolower($interface);
186
187 View Code Duplication
            if (isset($this->newInterfaces[$interfaceLc]) === 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...
188
                $itemInfo = array(
189
                    'name'   => $interface,
190
                    'nameLc' => $interfaceLc,
191
                );
192
                $this->handleFeature($phpcsFile, $stackPtr, $itemInfo);
193
            }
194
195
            if ($checkMethods === true && isset($this->unsupportedMethods[$interfaceLc]) === true) {
196
                $nextFunc = $stackPtr;
197
                while (($nextFunc = $phpcsFile->findNext(T_FUNCTION, ($nextFunc + 1), $scopeCloser)) !== false) {
0 ignored issues
show
Bug introduced by
The variable $scopeCloser does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
198
                    $funcName   = $phpcsFile->getDeclarationName($nextFunc);
199
                    $funcNameLc = strtolower($funcName);
200
                    if ($funcNameLc === '') {
201
                        continue;
202
                    }
203
204
                    if (isset($this->unsupportedMethods[$interfaceLc][$funcNameLc]) === true) {
205
                        $error     = 'Classes that implement interface %s do not support the method %s(). See %s';
206
                        $errorCode = $this->stringToErrorCode($interface).'UnsupportedMethod';
207
                        $data      = array(
208
                            $interface,
209
                            $funcName,
210
                            $this->unsupportedMethods[$interfaceLc][$funcNameLc],
211
                        );
212
213
                        $phpcsFile->addError($error, $nextFunc, $errorCode, $data);
214
                    }
215
                }
216
            }
217
        }
218
    }//end processClassToken()
219
220
221
    /**
222
     * Processes this test for when a function token is encountered.
223
     *
224
     * - Detect new interfaces when used as a type hint.
225
     *
226
     * @param PHP_CodeSniffer_File $phpcsFile The file being scanned.
227
     * @param int                  $stackPtr  The position of the current token in
228
     *                                        the stack passed in $tokens.
229
     *
230
     * @return void
231
     */
232
    private function processFunctionToken(PHP_CodeSniffer_File $phpcsFile, $stackPtr)
233
    {
234
        $typeHints = $this->getTypeHintsFromFunctionDeclaration($phpcsFile, $stackPtr);
235
        if (empty($typeHints) || is_array($typeHints) === false) {
236
            return;
237
        }
238
239
        foreach ($typeHints as $hint) {
240
241
            $typeHintLc = strtolower($hint);
242
243 View Code Duplication
            if (isset($this->newInterfaces[$typeHintLc]) === 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...
244
                $itemInfo = array(
245
                    'name'   => $hint,
246
                    'nameLc' => $typeHintLc,
247
                );
248
                $this->handleFeature($phpcsFile, $stackPtr, $itemInfo);
249
            }
250
        }
251
    }
252
253
254
    /**
255
     * Get the relevant sub-array for a specific item from a multi-dimensional array.
256
     *
257
     * @param array $itemInfo Base information about the item.
258
     *
259
     * @return array Version and other information about the item.
260
     */
261
    public function getItemArray(array $itemInfo)
262
    {
263
        return $this->newInterfaces[$itemInfo['nameLc']];
264
    }
265
266
267
    /**
268
     * Get the error message template for this sniff.
269
     *
270
     * @return string
271
     */
272
    protected function getErrorMsgTemplate()
273
    {
274
        return 'The built-in interface '.parent::getErrorMsgTemplate();
275
    }
276
277
278
}//end class
279