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:
Complex classes like NewConstantScalarExpressionsSniff often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use NewConstantScalarExpressionsSniff, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 31 | class NewConstantScalarExpressionsSniff extends Sniff |
||
| 32 | { |
||
| 33 | |||
| 34 | /** |
||
| 35 | * Error message. |
||
| 36 | * |
||
| 37 | * @var string |
||
| 38 | */ |
||
| 39 | const ERROR_PHRASE = 'Constant scalar expressions are not allowed %s in PHP 5.5 or earlier.'; |
||
| 40 | |||
| 41 | /** |
||
| 42 | * Partial error phrases to be used in combination with the error message constant. |
||
| 43 | * |
||
| 44 | * @var array |
||
| 45 | */ |
||
| 46 | protected $errorPhrases = array( |
||
| 47 | 'const' => 'when defining constants using the const keyword', |
||
| 48 | 'property' => 'in property declarations', |
||
| 49 | 'staticvar' => 'in static variable declarations', |
||
| 50 | 'default' => 'in default function arguments', |
||
| 51 | ); |
||
| 52 | |||
| 53 | /** |
||
| 54 | * Tokens which were allowed to be used in these declarations prior to PHP 5.6. |
||
| 55 | * |
||
| 56 | * This list will be enriched in the setProperties() method. |
||
| 57 | * |
||
| 58 | * @var array |
||
| 59 | */ |
||
| 60 | protected $safeOperands = array( |
||
| 61 | T_LNUMBER => T_LNUMBER, |
||
| 62 | T_DNUMBER => T_DNUMBER, |
||
| 63 | T_CONSTANT_ENCAPSED_STRING => T_CONSTANT_ENCAPSED_STRING, |
||
| 64 | T_TRUE => T_TRUE, |
||
| 65 | T_FALSE => T_FALSE, |
||
| 66 | T_NULL => T_NULL, |
||
| 67 | |||
| 68 | T_LINE => T_LINE, |
||
| 69 | T_FILE => T_FILE, |
||
| 70 | T_DIR => T_DIR, |
||
| 71 | T_FUNC_C => T_FUNC_C, |
||
| 72 | T_CLASS_C => T_CLASS_C, |
||
| 73 | T_METHOD_C => T_METHOD_C, |
||
| 74 | T_NS_C => T_NS_C, |
||
| 75 | |||
| 76 | // Special cases: |
||
| 77 | T_NS_SEPARATOR => T_NS_SEPARATOR, |
||
| 78 | /* |
||
| 79 | * This can be neigh anything, but for any usage except constants, |
||
| 80 | * the T_STRING will be combined with non-allowed tokens, so we should be good. |
||
| 81 | */ |
||
| 82 | T_STRING => T_STRING, |
||
| 83 | ); |
||
| 84 | |||
| 85 | |||
| 86 | /** |
||
| 87 | * Returns an array of tokens this test wants to listen for. |
||
| 88 | * |
||
| 89 | * @return array |
||
| 90 | */ |
||
| 91 | public function register() |
||
| 104 | |||
| 105 | |||
| 106 | /** |
||
| 107 | * Make some adjustments to the $safeOperands property. |
||
| 108 | * |
||
| 109 | * @return void |
||
| 110 | */ |
||
| 111 | public function setProperties() |
||
| 133 | |||
| 134 | |||
| 135 | /** |
||
| 136 | * Do a version check to determine if this sniff needs to run at all. |
||
| 137 | * |
||
| 138 | * @return bool |
||
| 139 | */ |
||
| 140 | protected function bowOutEarly() |
||
| 144 | |||
| 145 | |||
| 146 | /** |
||
| 147 | * Processes this test, when one of its tokens is encountered. |
||
| 148 | * |
||
| 149 | * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. |
||
| 150 | * @param int $stackPtr The position of the current token in the |
||
| 151 | * stack passed in $tokens. |
||
| 152 | * |
||
| 153 | * @return void|int Null or integer stack pointer to skip forward. |
||
| 154 | */ |
||
| 155 | public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr) |
||
| 156 | { |
||
| 157 | if ($this->bowOutEarly() === true) { |
||
| 158 | return; |
||
| 159 | } |
||
| 160 | |||
| 161 | $tokens = $phpcsFile->getTokens(); |
||
| 162 | |||
| 163 | switch ($tokens[$stackPtr]['type']) { |
||
| 164 | case 'T_FUNCTION': |
||
| 165 | case 'T_CLOSURE': |
||
| 166 | $params = PHPCSHelper::getMethodParameters($phpcsFile, $stackPtr); |
||
| 167 | if (empty($params)) { |
||
| 168 | // No parameters. |
||
| 169 | return; |
||
| 170 | } |
||
| 171 | |||
| 172 | $funcToken = $tokens[$stackPtr]; |
||
| 173 | |||
| 174 | if (isset($funcToken['parenthesis_owner'], $funcToken['parenthesis_opener'], $funcToken['parenthesis_closer']) === false |
||
| 175 | || $funcToken['parenthesis_owner'] !== $stackPtr |
||
| 176 | || isset($tokens[$funcToken['parenthesis_opener']], $tokens[$funcToken['parenthesis_closer']]) === false |
||
| 177 | ) { |
||
| 178 | // Hmm.. something is going wrong as these should all be available & valid. |
||
| 179 | return; |
||
| 180 | } |
||
| 181 | |||
| 182 | $opener = $funcToken['parenthesis_opener']; |
||
| 183 | $closer = $funcToken['parenthesis_closer']; |
||
| 184 | |||
| 185 | // Which nesting level is the one we are interested in ? |
||
| 186 | $nestedParenthesisCount = 1; |
||
| 187 | View Code Duplication | if (isset($tokens[$opener]['nested_parenthesis'])) { |
|
| 188 | $nestedParenthesisCount += count($tokens[$opener]['nested_parenthesis']); |
||
| 189 | } |
||
| 190 | |||
| 191 | foreach ($params as $param) { |
||
| 192 | if (isset($param['default']) === false) { |
||
| 193 | continue; |
||
| 194 | } |
||
| 195 | |||
| 196 | $end = $param['token']; |
||
| 197 | while (($end = $phpcsFile->findNext(array(T_COMMA, T_CLOSE_PARENTHESIS), ($end + 1), ($closer + 1))) !== false) { |
||
| 198 | $maybeSkipTo = $this->isRealEndOfDeclaration($tokens, $end, $nestedParenthesisCount); |
||
| 199 | if ($maybeSkipTo !== true) { |
||
| 200 | $end = $maybeSkipTo; |
||
| 201 | continue; |
||
| 202 | } |
||
| 203 | |||
| 204 | // Ignore closing parenthesis/bracket if not 'ours'. |
||
| 205 | if ($tokens[$end]['code'] === T_CLOSE_PARENTHESIS && $end !== $closer) { |
||
| 206 | continue; |
||
| 207 | } |
||
| 208 | |||
| 209 | // Ok, we've found the end of the param default value declaration. |
||
| 210 | break; |
||
| 211 | } |
||
| 212 | |||
| 213 | if ($this->isValidAssignment($phpcsFile, $param['token'], $end) === false) { |
||
| 214 | $this->throwError($phpcsFile, $param['token'], 'default', $param['content']); |
||
| 215 | } |
||
| 216 | } |
||
| 217 | |||
| 218 | /* |
||
| 219 | * No need for the sniff to be triggered by the T_VARIABLEs in the function |
||
| 220 | * definition as we've already examined them above, so let's skip over them. |
||
| 221 | */ |
||
| 222 | return $closer; |
||
| 223 | |||
| 224 | case 'T_VARIABLE': |
||
| 225 | case 'T_STATIC': |
||
| 226 | case 'T_CONST': |
||
| 227 | $type = 'const'; |
||
| 228 | |||
| 229 | // Filter out non-property declarations. |
||
| 230 | if ($tokens[$stackPtr]['code'] === T_VARIABLE) { |
||
| 231 | if ($this->isClassProperty($phpcsFile, $stackPtr) === false) { |
||
| 232 | return; |
||
| 233 | } |
||
| 234 | |||
| 235 | $type = 'property'; |
||
| 236 | |||
| 237 | // Move back one token to have the same starting point as the others. |
||
| 238 | $stackPtr = ($stackPtr - 1); |
||
| 239 | } |
||
| 240 | |||
| 241 | // Filter out late static binding and class properties. |
||
| 242 | if ($tokens[$stackPtr]['code'] === T_STATIC) { |
||
| 243 | $next = $phpcsFile->findNext( |
||
| 244 | \PHP_CodeSniffer_Tokens::$emptyTokens, |
||
| 245 | ($stackPtr + 1), |
||
| 246 | null, |
||
| 247 | true, |
||
| 248 | null, |
||
| 249 | true |
||
| 250 | ); |
||
| 251 | if ($next === false || $tokens[$next]['code'] !== T_VARIABLE) { |
||
| 252 | // Late static binding. |
||
| 253 | return; |
||
| 254 | } |
||
| 255 | |||
| 256 | if ($this->isClassProperty($phpcsFile, $next) === true) { |
||
| 257 | // Class properties are examined based on the T_VARIABLE token. |
||
| 258 | return; |
||
| 259 | } |
||
| 260 | unset($next); |
||
| 261 | |||
| 262 | $type = 'staticvar'; |
||
| 263 | } |
||
| 264 | |||
| 265 | $endOfStatement = $phpcsFile->findNext(array(T_SEMICOLON, T_CLOSE_TAG), ($stackPtr + 1)); |
||
| 266 | if ($endOfStatement === false) { |
||
| 267 | // No semi-colon - live coding. |
||
| 268 | return; |
||
| 269 | } |
||
| 270 | |||
| 271 | $targetNestingLevel = 0; |
||
| 272 | if (isset($tokens[$stackPtr]['nested_parenthesis']) == true) { |
||
|
|
|||
| 273 | $targetNestingLevel = count($tokens[$stackPtr]['nested_parenthesis']); |
||
| 274 | } |
||
| 275 | |||
| 276 | // Examine each variable/constant in multi-declarations. |
||
| 277 | $start = $stackPtr; |
||
| 278 | $end = $stackPtr; |
||
| 279 | while (($end = $phpcsFile->findNext(array(T_COMMA, T_SEMICOLON, T_OPEN_SHORT_ARRAY, T_CLOSE_TAG), ($end + 1), ($endOfStatement + 1))) !== false) { |
||
| 280 | |||
| 281 | $maybeSkipTo = $this->isRealEndOfDeclaration($tokens, $end, $targetNestingLevel); |
||
| 282 | if ($maybeSkipTo !== true) { |
||
| 283 | $end = $maybeSkipTo; |
||
| 284 | continue; |
||
| 285 | } |
||
| 286 | |||
| 287 | $start = $phpcsFile->findNext(\PHP_CodeSniffer_Tokens::$emptyTokens, ($start + 1), $end, true); |
||
| 288 | if ($start === false |
||
| 289 | || ($tokens[$stackPtr]['code'] === T_CONST && $tokens[$start]['code'] !== T_STRING) |
||
| 290 | || ($tokens[$stackPtr]['code'] !== T_CONST && $tokens[$start]['code'] !== T_VARIABLE) |
||
| 291 | ) { |
||
| 292 | // Shouldn't be possible. |
||
| 293 | continue; |
||
| 294 | } |
||
| 295 | |||
| 296 | if ($this->isValidAssignment($phpcsFile, $start, $end) === false) { |
||
| 297 | // Create the "found" snippet. |
||
| 298 | $content = ''; |
||
| 299 | $tokenCount = ($end - $start); |
||
| 300 | if ($tokenCount < 20) { |
||
| 301 | // Prevent large arrays from being added to the error message. |
||
| 302 | $content = $phpcsFile->getTokensAsString($start, ($tokenCount + 1)); |
||
| 303 | } |
||
| 304 | |||
| 305 | $this->throwError($phpcsFile, $start, $type, $content); |
||
| 306 | } |
||
| 307 | |||
| 308 | $start = $end; |
||
| 309 | } |
||
| 310 | |||
| 311 | // Skip to the end of the statement to prevent duplicate messages for multi-declarations. |
||
| 312 | return $endOfStatement; |
||
| 313 | } |
||
| 314 | } |
||
| 315 | |||
| 316 | |||
| 317 | /** |
||
| 318 | * Is a value declared and is the value declared valid pre-PHP 5.6 ? |
||
| 319 | * |
||
| 320 | * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. |
||
| 321 | * @param int $stackPtr The position of the current token in the |
||
| 322 | * stack passed in $tokens. |
||
| 323 | * @param int $end The end of the value definition. |
||
| 324 | * This will normally be a comma or semi-colon. |
||
| 325 | * |
||
| 326 | * @return bool |
||
| 327 | */ |
||
| 328 | protected function isValidAssignment(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $end) |
||
| 339 | |||
| 340 | |||
| 341 | /** |
||
| 342 | * Is a value declared and is the value declared constant as accepted in PHP 5.5 and lower ? |
||
| 343 | * |
||
| 344 | * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. |
||
| 345 | * @param array $tokens The token stack of the current file. |
||
| 346 | * @param int $start The stackPtr from which to start examining. |
||
| 347 | * @param int $end The end of the value definition (inclusive), |
||
| 348 | * i.e. this token will be examined as part of |
||
| 349 | * the snippet. |
||
| 350 | * @param bool $nestedArrays Optional. Array nesting level when examining |
||
| 351 | * the content of an array. |
||
| 352 | * |
||
| 353 | * @return bool |
||
| 354 | */ |
||
| 355 | protected function isStaticValue(\PHP_CodeSniffer_File $phpcsFile, $tokens, $start, $end, $nestedArrays = 0) |
||
| 493 | |||
| 494 | |||
| 495 | /** |
||
| 496 | * Throw an error if a scalar expression is found. |
||
| 497 | * |
||
| 498 | * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. |
||
| 499 | * @param int $stackPtr The position of the token to link the error to. |
||
| 500 | * @param string $type Type of usage found. |
||
| 501 | * @param string $content Optional. The value for the declaration as found. |
||
| 502 | * |
||
| 503 | * @return void |
||
| 504 | */ |
||
| 505 | protected function throwError(\PHP_CodeSniffer_File $phpcsFile, $stackPtr, $type, $content = '') |
||
| 525 | |||
| 526 | |||
| 527 | /** |
||
| 528 | * Helper function to find the end of multi variable/constant declarations. |
||
| 529 | * |
||
| 530 | * Checks whether a certain part of a declaration needs to be skipped over or |
||
| 531 | * if it is the real end of the declaration. |
||
| 532 | * |
||
| 533 | * @param array $tokens Token stack of the current file. |
||
| 534 | * @param int $endPtr The token to examine as a candidate end pointer. |
||
| 535 | * @param int $targetLevel Target nesting level. |
||
| 536 | * |
||
| 537 | * @return bool|int True if this is the real end. Int stackPtr to skip to if not. |
||
| 538 | */ |
||
| 539 | private function isRealEndOfDeclaration($tokens, $endPtr, $targetLevel) |
||
| 565 | } |
||
| 566 |
When comparing two booleans, it is generally considered safer to use the strict comparison operator.