| Conditions | 12 |
| Paths | 38 |
| Total Lines | 54 |
| Lines | 0 |
| Ratio | 0 % |
| Changes | 0 | ||
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:
If many parameters/temporary variables are present:
| 1 | <?php |
||
| 53 | public function arrangeExcel($data, $fields) |
||
| 54 | { |
||
| 55 | $data = $this->trimExcel($data); |
||
| 56 | |||
| 57 | $header_index = 0; |
||
| 58 | while(true) |
||
| 59 | { |
||
| 60 | $header = array_shift($data); |
||
| 61 | if (!$header) { |
||
| 62 | throw new \UnexpectedValueException('表头定位错误。', -11142); |
||
| 63 | } |
||
| 64 | |||
| 65 | if (is_array($header)) { |
||
| 66 | if (in_array($header[0], $fields)) { |
||
| 67 | break; |
||
| 68 | } |
||
| 69 | if (++$header_index > 5) { |
||
| 70 | throw new \UnexpectedValueException('表头定位错误。', -11142); |
||
| 71 | } |
||
| 72 | } |
||
| 73 | } |
||
| 74 | |||
| 75 | // the first row is used for the issue keys |
||
| 76 | if (array_search('', $header) !== false) { |
||
|
|
|||
| 77 | throw new \UnexpectedValueException('表头不能有空值。', -11143); |
||
| 78 | } |
||
| 79 | // check the header title |
||
| 80 | if (count($header) !== count(array_unique($header))) { |
||
| 81 | throw new \UnexpectedValueException('表头不能有重复列。', -11144); |
||
| 82 | } |
||
| 83 | |||
| 84 | $field_keys = []; |
||
| 85 | foreach($header as $field) |
||
| 86 | { |
||
| 87 | $tmp = array_search($field, $fields); |
||
| 88 | if ($tmp === false) { |
||
| 89 | throw new \UnexpectedValueException('表头有不明确列。', -11145); |
||
| 90 | } |
||
| 91 | $field_keys[] = $tmp; |
||
| 92 | } |
||
| 93 | |||
| 94 | $new_data = []; |
||
| 95 | foreach ($data as $item) |
||
| 96 | { |
||
| 97 | $tmp = []; |
||
| 98 | foreach ($item as $key => $val) |
||
| 99 | { |
||
| 100 | $tmp[$field_keys[$key]] = $val; |
||
| 101 | } |
||
| 102 | $new_data[] = $tmp; |
||
| 103 | } |
||
| 104 | |||
| 105 | return $new_data; |
||
| 106 | } |
||
| 107 | |||
| 127 |
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: