1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Created by PhpStorm. |
4
|
|
|
* User: sheldon |
5
|
|
|
* Date: 18-4-10 |
6
|
|
|
* Time: 上午11:30. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace Yeelight\Services\Exporters; |
10
|
|
|
|
11
|
|
|
use Illuminate\Database\Eloquent\Model; |
12
|
|
|
use Illuminate\Support\Collection; |
13
|
|
|
use Illuminate\Support\Str; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Class CsvExporter |
17
|
|
|
* |
18
|
|
|
* @category Yeelight |
19
|
|
|
* |
20
|
|
|
* @package Yeelight\Services\Exporters |
21
|
|
|
* |
22
|
|
|
* @author Sheldon Lee <[email protected]> |
23
|
|
|
* |
24
|
|
|
* @license https://opensource.org/licenses/MIT MIT |
25
|
|
|
* |
26
|
|
|
* @link https://www.yeelight.com |
27
|
|
|
*/ |
28
|
|
|
class CsvExporter extends AbstractExporter |
29
|
|
|
{ |
30
|
|
|
/** |
31
|
|
|
* {@inheritdoc} |
32
|
|
|
*/ |
33
|
|
|
public function export() |
34
|
|
|
{ |
35
|
|
|
$filename = $this->getTable().'.csv'; |
36
|
|
|
|
37
|
|
|
$headers = [ |
38
|
|
|
'Content-Encoding' => 'UTF-8', |
39
|
|
|
'Content-Type' => 'text/csv;charset=UTF-8', |
40
|
|
|
'Content-Disposition' => "attachment; filename=\"$filename\"", |
41
|
|
|
]; |
42
|
|
|
|
43
|
|
|
response()->stream(function () { |
|
|
|
|
44
|
|
|
$handle = fopen('php://output', 'w'); |
45
|
|
|
|
46
|
|
|
$titles = []; |
47
|
|
|
|
48
|
|
|
$this->chunk(function ($records) use ($handle, &$titles) { |
49
|
|
|
if (empty($titles)) { |
50
|
|
|
$titles = $this->getHeaderRowFromRecords($records); |
51
|
|
|
|
52
|
|
|
// Add CSV headers |
53
|
|
|
fputcsv($handle, $titles); |
|
|
|
|
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
foreach ($records as $record) { |
57
|
|
|
fputcsv($handle, $this->getFormattedRecord($record)); |
58
|
|
|
} |
59
|
|
|
}); |
60
|
|
|
|
61
|
|
|
// Close the output stream |
62
|
|
|
fclose($handle); |
|
|
|
|
63
|
|
|
}, 200, $headers)->send(); |
64
|
|
|
|
65
|
|
|
exit; |
|
|
|
|
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @param Collection $records |
70
|
|
|
* |
71
|
|
|
* @return array |
72
|
|
|
*/ |
73
|
|
|
public function getHeaderRowFromRecords(Collection $records): array |
74
|
|
|
{ |
75
|
|
|
$titles = collect(array_dot($records->first()->toArray()))->keys()->map( |
76
|
|
|
function ($key) { |
77
|
|
|
$key = str_replace('.', ' ', $key); |
78
|
|
|
|
79
|
|
|
return Str::ucfirst($key); |
80
|
|
|
} |
81
|
|
|
); |
82
|
|
|
|
83
|
|
|
return $titles->toArray(); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
/** |
87
|
|
|
* @param Model $record |
88
|
|
|
* |
89
|
|
|
* @return array |
90
|
|
|
*/ |
91
|
|
|
public function getFormattedRecord(Model $record) |
92
|
|
|
{ |
93
|
|
|
return array_dot($record->getAttributes()); |
94
|
|
|
} |
95
|
|
|
} |
96
|
|
|
|