query('alku', ''), (string) $request->query('loppu', '')); } catch (InvalidReportPeriod) { abort(404); } $csv = $this->csv($report); $rows = $csv->rows($period, $request); $headers = $csv->headers(); return response()->streamDownload(function () use ($headers, $rows): void { $out = fopen('php://output', 'w'); if ($out === false) { return; } fwrite($out, "\u{FEFF}"); fputcsv($out, $headers, ';', '"', ''); foreach ($rows as $row) { fputcsv($out, array_map(self::cell(...), $row), ';', '"', ''); } fclose($out); }, __('reports.csv_file', ['report' => __('reports.'.$report.'.file'), 'from' => $period->from, 'to' => $period->to]), [ 'Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store, private', ]); } /** * Numbers are written as they are; text that starts like a formula gets * a leading apostrophe. */ public static function cell(string|int $value): string { if (is_int($value)) { return (string) $value; } return preg_match('/^[=+\-@\t\r\n]/', $value) === 1 ? "'".$value : $value; } private function csv(string $report): ReportCsv { return match ($report) { 'hours' => app(HoursCsv::class), default => abort(404), }; } }