csv($report); try { // Reading the file name checks the filters before anything is streamed. $fileName = $csv->fileName($request).'.csv'; } catch (InvalidReportPeriod) { abort(404); } return response()->streamDownload(function () use ($csv, $request): void { $out = fopen('php://output', 'w'); if ($out === false) { return; } fwrite($out, "\u{FEFF}"); fputcsv($out, $csv->headers(), ';', '"', ''); foreach ($csv->rows($request) as $row) { fputcsv($out, array_map(self::cell(...), $row), ';', '"', ''); } fclose($out); }, $fileName, [ '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), 'unbilled' => app(UnbilledCsv::class), 'profitability' => app(ProfitabilityCsv::class), 'sales' => app(SalesCsv::class), 'reimbursements' => app(ReimbursementsCsv::class), 'stock-usage' => app(StockUsageCsv::class), 'stock-value' => app(StockValueCsv::class), default => abort(404), }; } }