json($statistics->report($this->range($request), $this->choice($request))); } /** One list of the period that is on the screen, as a CSV file. */ public function export(Request $request, Statistics $statistics): StreamedResponse { $export = $statistics->export($request->string('sheet')->toString(), $this->range($request), $this->choice($request)); return response()->streamDownload(function () use ($export) { $out = fopen('php://output', 'w'); if ($out === false) { return; } // The mark that tells a spreadsheet the file is UTF-8. fwrite($out, "\xEF\xBB\xBF"); fputcsv($out, $export['header'], ',', '"', ''); foreach ($export['rows'] as $row) { fputcsv($out, array_map(self::cell(...), $row), ',', '"', ''); } fclose($out); }, $export['filename'], ['Content-Type' => 'text/csv; charset=UTF-8', 'Cache-Control' => 'no-store']); } /** * A page address, a referring site and the name of a program come from visitors. A spreadsheet * runs a cell that starts like a formula, so such a cell gets a quote in front and is shown as * the text it is. */ private static function cell(string|int $value): string|int { return is_string($value) && preg_match('/^[=+\-@\t\r]/', $value) === 1 ? "'".$value : $value; } private function range(Request $request): string { return $request->string('range', Statistics::DEFAULT_RANGE)->toString(); } /** @return array */ private function choice(Request $request): array { $choice = []; foreach (['from', 'to', 'compare', 'compare_from'] as $key) { $choice[$key] = $request->string($key)->limit(20, '')->toString(); } // Nothing chosen is the period before, not "nothing". if ($choice['compare'] === '') { unset($choice['compare']); } return $choice; } }