Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
| CsvParser | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
5 | |
100.00% |
1 / 1 |
| parseCSV | |
100.00% |
17 / 17 |
|
100.00% |
1 / 1 |
5 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Helper\CsvParser; |
| 6 | |
| 7 | use RuntimeException; |
| 8 | use stdClass; |
| 9 | use UnexpectedValueException; |
| 10 | |
| 11 | class CsvParser |
| 12 | { |
| 13 | /** |
| 14 | * @param array<int, string|false> $contents |
| 15 | */ |
| 16 | public function parseCSV(array $contents): CsvObject |
| 17 | { |
| 18 | if ($contents === []) { |
| 19 | throw new UnexpectedValueException('CSV file is empty'); |
| 20 | } |
| 21 | |
| 22 | $csvObject = new CsvObject(); |
| 23 | |
| 24 | $headVars = explode(',', trim(trim((string)$contents[0]), '"')); |
| 25 | |
| 26 | $csvObject->headVars = $headVars; |
| 27 | |
| 28 | $lines = []; |
| 29 | |
| 30 | // Strip header |
| 31 | unset($contents[0]); |
| 32 | |
| 33 | foreach ($contents as $line) { |
| 34 | $fields = explode(',', trim(trim((string)$line), '"')); |
| 35 | |
| 36 | $o = new stdClass(); |
| 37 | |
| 38 | foreach ($fields as $i => $field) { |
| 39 | if (!isset($headVars[$i])) { |
| 40 | throw new RuntimeException('Malformed CSV file.'); |
| 41 | } |
| 42 | |
| 43 | $o->{strtolower($headVars[$i])} = trim($field); |
| 44 | } |
| 45 | |
| 46 | $lines[] = $o; |
| 47 | } |
| 48 | |
| 49 | $csvObject->lines = $lines; |
| 50 | |
| 51 | return $csvObject; |
| 52 | } |
| 53 | } |