forked from studiofrenetic/laravel-formatter
-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathCsvParser.php
50 lines (43 loc) · 1.29 KB
/
CsvParser.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
<?php namespace SoapBox\Formatter\Parsers;
use InvalidArgumentException;
use League\Csv\Reader;
use SoapBox\Formatter\ArrayHelpers;
class CsvParser extends Parser
{
private $csv;
public function __construct($data, $delimiter = null)
{
if (is_string($data)) {
$this->csv = Reader::createFromString($data);
if ($delimiter) {
$this->csv->setDelimiter($delimiter);
}
$this->csv->setEnclosure('|');
} else {
throw new InvalidArgumentException(
'CsvParser only accepts (string) [csv] for $data.'
);
}
}
public function toArray()
{
$temp = $this->csv->jsonSerialize();
$headings = $temp[0];
$result = $headings;
if (count($temp) > 1) {
$result = [];
for ($i = 1; $i < count($temp); ++$i) {
$row = [];
for ($j = 0; $j < count($headings); ++$j) {
$row[$headings[$j]] = $temp[$i][$j];
}
$expanded = [];
foreach ($row as $key => $value) {
ArrayHelpers::set($expanded, $key, $value);
}
$result[] = $expanded;
}
}
return $result;
}
}