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 |
||
27 | class NewKeyedListSniff extends Sniff |
||
28 | { |
||
29 | |||
30 | /** |
||
31 | * Returns an array of tokens this test wants to listen for. |
||
32 | * |
||
33 | * @return array |
||
34 | */ |
||
35 | public function register() |
||
42 | |||
43 | /** |
||
44 | * Do a version check to determine if this sniff needs to run at all. |
||
45 | * |
||
46 | * @return bool |
||
47 | */ |
||
48 | protected function bowOutEarly() |
||
52 | |||
53 | /** |
||
54 | * Processes this test, when one of its tokens is encountered. |
||
55 | * |
||
56 | * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. |
||
57 | * @param int $stackPtr The position of the current token in the |
||
58 | * stack passed in $tokens. |
||
59 | * |
||
60 | * @return void |
||
61 | */ |
||
62 | public function process(\PHP_CodeSniffer_File $phpcsFile, $stackPtr) |
||
104 | |||
105 | |||
106 | /** |
||
107 | * Examine the contents of a list construct to determine whether an error needs to be thrown. |
||
108 | * |
||
109 | * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. |
||
110 | * @param int $opener The position of the list open token. |
||
111 | * @param int $closer The position of the list close token. |
||
112 | * |
||
113 | * @return void |
||
114 | */ |
||
115 | protected function examineList(\PHP_CodeSniffer_File $phpcsFile, $opener, $closer) |
||
127 | |||
128 | |||
129 | /** |
||
130 | * Check whether a certain target token exists within a list construct. |
||
131 | * |
||
132 | * Skips past nested list constructs, so these can be examined based on their own token. |
||
133 | * |
||
134 | * @param \PHP_CodeSniffer_File $phpcsFile The file being scanned. |
||
135 | * @param int $start The position of the list open token or a token |
||
136 | * within the list to start (resume) the examination from. |
||
137 | * @param int $closer The position of the list close token. |
||
138 | * @param array $targets An array with one or more token constants to look for. |
||
139 | * |
||
140 | * @return int|bool Stack pointer to the target token if encountered. False otherwise. |
||
141 | */ |
||
142 | protected function hasTargetInList(\PHP_CodeSniffer_File $phpcsFile, $start, $closer, $targets) |
||
175 | } |
||
176 |
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:
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
Check for existence of the variable explicitly:
Define a default value for the variable:
Add a value for the missing path: