-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Csv.php
41 lines (33 loc) · 867 Bytes
/
Csv.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
<?php
namespace distantnative\CsvField;
use Kirby\Toolkit\Collection;
/**
* @package CSV Field
* @author Nico Hoffmann <[email protected]>
* @link https://github.com/distantnative/kirby-csv-field
* @copyright Nico Hoffmann
* @license https://opensource.org/licenses/MIT
*/
class Csv extends Collection
{
public function columns(): array
{
if ($first = $this->first()) {
return array_keys($first);
}
return [];
}
public static function for(string $file, string $delimiter = ','): static
{
$lines = file($file);
$lines[0] = str_replace("\xEF\xBB\xBF", '', $lines[0]);
$csv = array_map(fn ($d) => str_getcsv($d, $delimiter), $lines);
array_walk($csv, fn (&$a) => $a = array_combine($csv[0], $a));
array_shift($csv);
return new static($csv);
}
public function rows(): array
{
return $this->toArray();
}
}