| Conditions | 10 |
| Paths | 16 |
| Total Lines | 45 |
| 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 |
||
| 32 | public static function csv($filename, array $options = []) |
||
| 33 | { |
||
| 34 | $filename = Yii::getAlias($filename); |
||
| 35 | |||
| 36 | // check if a given file name is provided or a csv based on the content |
||
| 37 | if (FileHelper::getFileInfo($filename)->extension) { |
||
|
|
|||
| 38 | $resource = fopen($filename, 'r'); |
||
| 39 | } else { |
||
| 40 | $resource = fopen('php://memory', 'rw'); |
||
| 41 | fwrite($resource, $filename); |
||
| 42 | rewind($resource); |
||
| 43 | } |
||
| 44 | $data = []; |
||
| 45 | while (($row = fgetcsv($resource, 0, ArrayHelper::getValue($options, 'delimiter', ','), ArrayHelper::getValue($options, 'enclosure', '"'))) !== false) { |
||
| 46 | $data[] = $row; |
||
| 47 | } |
||
| 48 | fclose($resource); |
||
| 49 | |||
| 50 | // check whether only an amount of fields should be parsed into the final array |
||
| 51 | $fields = ArrayHelper::getValue($options, 'fields', false); |
||
| 52 | if ($fields && is_array($fields)) { |
||
| 53 | $filteredData = []; |
||
| 54 | foreach ($fields as $fieldColumn) { |
||
| 55 | if (!is_numeric($fieldColumn)) { |
||
| 56 | $fieldColumn = array_search($fieldColumn, $data[0]); |
||
| 57 | } |
||
| 58 | foreach ($data as $key => $rowValue) { |
||
| 59 | if (array_key_exists($fieldColumn, $rowValue)) { |
||
| 60 | $filteredData[$key][] = $rowValue[$fieldColumn]; |
||
| 61 | } |
||
| 62 | } |
||
| 63 | } |
||
| 64 | |||
| 65 | $data = $filteredData; |
||
| 66 | unset($filteredData); |
||
| 67 | } |
||
| 68 | |||
| 69 | // if the option to remove a header is provide. remove the first key and reset and array keys |
||
| 70 | if (ArrayHelper::getValue($options, 'removeHeader', false)) { |
||
| 71 | unset($data[0]); |
||
| 72 | $data = array_values($data); |
||
| 73 | } |
||
| 74 | |||
| 75 | return $data; |
||
| 76 | } |
||
| 77 | } |
||
| 78 |
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.