Commit 94c6cad1 authored by Maik Messerschmidt's avatar Maik Messerschmidt
Browse files

Added route, which let's you download all data as csv.

parent 8cf07da3
......@@ -6,6 +6,8 @@ use App\Experiment;
use App\Result;
use App\Logic\IPAnonymizer;
use League\Csv\Writer;
use Illuminate\Http\Request;
use Str;
use Log;
......@@ -84,6 +86,58 @@ class ResultController extends Controller
]);
}
// Returns object obj with obj->header: array with header info
// obj->rows: arrays with data.
//
// @param $results Collection of Result
private function getResults($results) {
$header = collect($results->first()->data ?? [])
->map(function($entry) {
return array_keys($entry);
})
->flatten()
->unique();
$all_rows = collect();
foreach ($results as $result) {
$rows = collect($result->data ?? [])
->map(function($row) use ($header) {
foreach ($header as $key) {
// Fill empty columns with N/A
$row[$key] = $row[$key] ?? config('experiment.n-a-text');
// Replace arrays with json
if (is_array($row[$key]))
$row[$key] = json_encode($row[$key]);
}
return $row;
});
$all_rows = $all_rows->concat($rows);
}
return (object) [
'header' => $header->toArray(),
'rows' => $all_rows->toArray(),
];
}
public function showAllCSV() {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Type: application/force-download');
header('Content-Disposition: attachment; filename=results.csv');
$data = $this->getResults(Result::all());
$csv = Writer::createFromString('');
$csv->insertOne($data->header);
$csv->insertAll($data->rows);
return $csv->getContent();
}
/**
* Display the result as json.
*/
......
......@@ -56,4 +56,6 @@
</tbody>
</table>
<a href="{{ route('results.show-all-csv') }}">Download all results as CSV</a>
@endsection
......@@ -22,6 +22,9 @@ Route::middleware(['web', 'auth'])->group(function() {
Route::get('/admin/results/show-json/{result}', 'ResultController@showJson')
->name('results.show-json');
Route::get('/admin/results/show-all-csv', 'ResultController@showAllCSV')
->name('results.show-all-csv');
Route::get('/admin/results/partial', 'ResultController@indexPartial')
->name('results.index.partial');
Route::resource('/admin/results', 'ResultController');
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment