|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Encore\Admin\Grid\Exporters; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Database\Eloquent\Model; |
|
6
|
|
|
use Illuminate\Support\Collection; |
|
7
|
|
|
use Illuminate\Support\Str; |
|
8
|
|
|
|
|
9
|
|
|
class CsvExporter extends AbstractExporter |
|
10
|
|
|
{ |
|
11
|
|
|
/** |
|
12
|
|
|
* {@inheritdoc} |
|
13
|
|
|
*/ |
|
14
|
|
|
public function export() |
|
15
|
|
|
{ |
|
16
|
|
|
$filename = $this->getTable().'.csv'; |
|
17
|
|
|
|
|
18
|
|
|
$headers = [ |
|
19
|
|
|
'Content-Encoding' => 'UTF-8', |
|
20
|
|
|
'Content-Type' => 'text/csv;charset=UTF-8', |
|
21
|
|
|
'Content-Disposition' => "attachment; filename=\"$filename\"", |
|
22
|
|
|
]; |
|
23
|
|
|
|
|
24
|
|
|
response()->stream(function () { |
|
25
|
|
|
$handle = fopen('php://output', 'w'); |
|
26
|
|
|
|
|
27
|
|
|
$titles = []; |
|
28
|
|
|
|
|
29
|
|
|
$this->chunk(function ($records) use ($handle, &$titles) { |
|
30
|
|
|
if (empty($titles)) { |
|
31
|
|
|
$titles = $this->getHeaderRowFromRecords($records); |
|
32
|
|
|
|
|
33
|
|
|
// Add CSV headers |
|
34
|
|
|
fputcsv($handle, $titles); |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
foreach ($records as $record) { |
|
38
|
|
|
fputcsv($handle, $this->getFormattedRecord($record)); |
|
39
|
|
|
} |
|
40
|
|
|
}); |
|
41
|
|
|
|
|
42
|
|
|
// Close the output stream |
|
43
|
|
|
fclose($handle); |
|
44
|
|
|
}, 200, $headers)->send(); |
|
45
|
|
|
|
|
46
|
|
|
exit; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @param Collection $records |
|
51
|
|
|
* |
|
52
|
|
|
* @return array |
|
53
|
|
|
*/ |
|
54
|
|
|
public function getHeaderRowFromRecords(Collection $records): array |
|
55
|
|
|
{ |
|
56
|
|
|
$titles = collect(array_dot($records->first()->toArray()))->keys()->map( |
|
57
|
|
|
function ($key) { |
|
58
|
|
|
$key = str_replace('.', ' ', $key); |
|
59
|
|
|
|
|
60
|
|
|
return Str::ucfirst($key); |
|
61
|
|
|
} |
|
62
|
|
|
); |
|
63
|
|
|
|
|
64
|
|
|
return $titles->toArray(); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** |
|
68
|
|
|
* @param Model $record |
|
69
|
|
|
* |
|
70
|
|
|
* @return array |
|
71
|
|
|
*/ |
|
72
|
|
|
public function getFormattedRecord(Model $record) |
|
73
|
|
|
{ |
|
74
|
|
|
return array_dot($record->getAttributes()); |
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|