-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCSV.php
More file actions
30 lines (27 loc) · 940 Bytes
/
CSV.php
File metadata and controls
30 lines (27 loc) · 940 Bytes
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
<?php declare(strict_types=1);
namespace Stratadox\Parser\Test\Examples\CSV;
use Stratadox\Parser\Helpers\Between;
use Stratadox\Parser\Parser;
use function array_combine;
use function array_filter;
use function array_map;
use function array_slice;
use function Stratadox\Parser\any;
use function Stratadox\Parser\pattern;
final class CSV
{
public static function parser(
Parser|string $separator = ',',
Parser|string $escape = '"',
): Parser {
$newline = pattern('\r\n|\r|\n');
return Between::escaped('"', '"', $escape)
->or(any()->except($newline->or($separator, $escape))->repeatableString())
->mustSplit($separator)->maybe()
->split($newline)
->end()->map(fn(array $file) => array_map(
fn(array $line) => array_combine($file[0], $line),
array_filter(array_slice($file, 1), fn($x) => $x),
));
}
}