46 lines
1.1 KiB
PHP
46 lines
1.1 KiB
PHP
<?php
|
|
|
|
namespace Modules\Core\Export;
|
|
|
|
/**
|
|
* A generic columns + rows -> CSV file writer. No knowledge of any domain (GDPR,
|
|
* catalog, accounting, ...) — a caller supplies the schema (CsvColumn[]) and the
|
|
* data source (any iterable of records), and this writes one CSV. Reusable for
|
|
* any future bulk-export need without modification.
|
|
*/
|
|
class CsvWriter
|
|
{
|
|
/**
|
|
* @param array<int, CsvColumn> $columns
|
|
* @param iterable<mixed> $rows
|
|
*/
|
|
public function write(array $columns, iterable $rows, string $path): void
|
|
{
|
|
$handle = fopen($path, 'w');
|
|
|
|
fputcsv($handle, array_map(fn (CsvColumn $column) => $column->header, $columns));
|
|
|
|
foreach ($rows as $row) {
|
|
fputcsv($handle, array_map(
|
|
fn (CsvColumn $column) => $this->stringify(($column->value)($row)),
|
|
$columns
|
|
));
|
|
}
|
|
|
|
fclose($handle);
|
|
}
|
|
|
|
private function stringify(mixed $value): string
|
|
{
|
|
if ($value === null) {
|
|
return '';
|
|
}
|
|
|
|
if (is_array($value)) {
|
|
return json_encode($value);
|
|
}
|
|
|
|
return (string) $value;
|
|
}
|
|
}
|