Created
December 6, 2023 13:55
-
-
Save tsh-code/4cff8590fbce0c41473dccef630571d5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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