Skip to content

Instantly share code, notes, and snippets.

@tsh-code
Created December 6, 2023 13:55
Show Gist options
  • Save tsh-code/4cff8590fbce0c41473dccef630571d5 to your computer and use it in GitHub Desktop.
Save tsh-code/4cff8590fbce0c41473dccef630571d5 to your computer and use it in GitHub Desktop.
<?php
class Generator {
private const JSON_TYPE = ‘application/json’;
private const CSV_TYPE = ‘text/csv’;
private const JSON_EXT = ‘json’;
private const CSV_EXT = ‘csv’;
private function disposition(
string $filename,
string $content,
string $fileType,
): void {
$ext = $fileType == self::JSON_TYPE ? self::JSON_EXT : self::CSV;
header(“Content-Type: $fileType”);
header(sprintf(‘Content-Disposition: attachment; filename="%s”`), sprintf(‘%s.%s’, $filename, $ext);
ob_start();
echo $content;
ob_end_flush();
exit;
}
private function generateContent(
array $data,
string $fileType
): string {
return match($fileType) {
self::JSON_TYPE => $this->generateJsonContent($data),
self::CSV_TYPE => $this->generateCSVContent($data),
default: throw new UnexpectedContentType(),
};
}
private function generateCSVContent(array $data): string
{
$stream = fopen(‘php://memory’);
foreach ($data as $line) {
fputcsv($stream, $data, ‘;’);
}
$content = ‘’;
while (false === feof($stream)) {
$content .= fread($stream, 1024);
}
fclose($stream);
return $content;
}
private function generateJsonContent(array $data): string
{
return json_encode($data);
}
// . . .
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment