Files
timebank-cc-public/app/Http/Controllers/PollResultsExportController.php

48 lines
1.6 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Helpers\ProfileAuthorizationHelper;
use App\Models\Admin;
use App\Models\Bank;
use App\Models\Poll;
use App\Polls\ResultsCsv;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Log;
/**
* Poll results as a CSV download. A plain HTTP route (not a Livewire action) so the file is
* streamed instead of buffered in memory.
*/
class PollResultsExportController extends Controller
{
public function __invoke(Poll $poll)
{
// Admin (or central bank) profile allowed to see who voted
$profile = getActiveProfile();
if (!$profile || !($profile instanceof Admin || ($profile instanceof Bank && $profile->level === 0))) {
abort(403);
}
ProfileAuthorizationHelper::authorize($profile);
if (!Gate::allows('export polls')) {
abort(403);
}
Log::info('Poll results exported', ['poll_id' => $poll->id, 'user_id' => auth('web')->id()]);
$csv = new ResultsCsv($poll, App::getLocale());
$filename = 'poll-' . $poll->id . '-results-' . now()->format('Y-m-d') . '.csv';
return response()->streamDownload(function () use ($csv) {
$out = fopen('php://output', 'w');
fwrite($out, "\xEF\xBB\xBF"); // UTF-8 BOM, so Excel shows accents correctly
fputcsv($out, $csv->header());
foreach ($csv->rows() as $row) {
fputcsv($out, $row);
}
fclose($out);
}, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']);
}
}