Completed
Push — master ( a271bc...282cb8 )
by Wim
02:24
created

Sniffs/PHP/NewInterfacesSniff.php (2 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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
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
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) {
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
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