Skip to content

Commit

Permalink
pkp#10145 consider TSV as API response
Browse files Browse the repository at this point in the history
  • Loading branch information
bozana committed Jul 1, 2024
1 parent 203067f commit 2cf7a8a
Showing 1 changed file with 21 additions and 8 deletions.
29 changes: 21 additions & 8 deletions classes/core/PKPRoutingProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
use Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull;
use Illuminate\Foundation\Http\Middleware\TrimStrings;
use Illuminate\Foundation\Http\Middleware\ValidatePostSize;
use Illuminate\Http\Request;
use Illuminate\Routing\Router;
use Illuminate\Routing\RoutingServiceProvider;
use Illuminate\Support\Facades\Response;
Expand All @@ -34,6 +33,9 @@

class PKPRoutingProvider extends RoutingServiceProvider
{
public const RESPONSE_CSV = 'text/csv';
public const RESPONSE_TSV = 'text/tab-separated-values';

protected static $globalMiddleware = [
AllowCrossOrigin::class,
SetupContextBasedOnRequestUrl::class,
Expand Down Expand Up @@ -79,28 +81,39 @@ public function register()
*/
public function boot()
{
Response::macro('withCSV', function (array $rows, array $columns, int $maxRows) {
Response::macro('withCSV', function (array $rows, array $columns, int $maxRows, string $mimeType = PKPRoutingProvider::RESPONSE_CSV) {
$fileEnding = '.csv';
if ($mimeType == PKPRoutingProvider::RESPONSE_TSV) {
$fileEnding = '.tsv';
}
return response()->stream(
function () use ($rows, $columns) {
function () use ($rows, $columns, $mimeType) {
$separator = ',' ;
if ($mimeType == PKPRoutingProvider::RESPONSE_TSV) {
$separator = "\t";
}

$fp = fopen('php://output', 'wt');

// Adds BOM (byte order mark) to enforce the UTF-8 format
fwrite($fp, "\xEF\xBB\xBF");

fputcsv($fp, ['']);
fputcsv($fp, $columns);
if (!empty($columns)) {
fputcsv($fp, [''], $separator);
fputcsv($fp, $columns, $separator);
}

foreach ($rows as $row) {
fputcsv($fp, $row);
fputcsv($fp, $row, $separator);
}

fclose($fp);
},
\Illuminate\Http\Response::HTTP_OK,
[
'content-type' => 'text/csv',
'content-type' => $mimeType,
'X-Total-Count' => $maxRows,
'content-disposition' => 'attachment; filename="user-report-' . date('Y-m-d') . '.csv"',
'content-disposition' => 'attachment; filename="user-report-' . date('Y-m-d') . $fileEnding . '"',
]
);
});
Expand Down

0 comments on commit 2cf7a8a

Please sign in to comment.