1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of the TheAlternativeZurich/events project. |
5
|
|
|
* |
6
|
|
|
* (c) Florian Moser <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace App\Service; |
13
|
|
|
|
14
|
|
|
use App\Service\Interfaces\CsvServiceInterface; |
15
|
|
|
use Symfony\Component\HttpFoundation\Response; |
16
|
|
|
use Symfony\Component\HttpFoundation\StreamedResponse; |
17
|
|
|
|
18
|
|
|
class CsvService implements CsvServiceInterface |
19
|
|
|
{ |
20
|
|
|
const DELIMITER = "\t"; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* creates a response containing the data rendered as a csv. |
24
|
|
|
* |
25
|
|
|
* @param string $filename |
26
|
|
|
* @param string[][] $data |
27
|
|
|
* @param null $header |
|
|
|
|
28
|
|
|
* |
29
|
|
|
* @return Response |
30
|
|
|
*/ |
31
|
|
|
public function streamCsv($filename, $data, $header = null) |
32
|
|
|
{ |
33
|
|
|
$response = new StreamedResponse(); |
34
|
|
|
$response->setCallback(function () use ($header, $data) { |
35
|
|
|
$handle = fopen('php://output', 'w+'); |
36
|
|
|
if (false === $handle) { |
37
|
|
|
throw new \Exception('could not write to output'); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$this->writeContent($handle, $data, $header); |
41
|
|
|
|
42
|
|
|
fclose($handle); |
43
|
|
|
}); |
44
|
|
|
|
45
|
|
|
$response->setStatusCode(200); |
46
|
|
|
$response->headers->set('Content-Type', 'text/csv; charset=utf-8'); |
47
|
|
|
$response->headers->set('Content-Disposition', 'attachment; filename="'.$filename.'"'); |
48
|
|
|
|
49
|
|
|
return $response; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* @param $handle |
54
|
|
|
* @param string[][] $data |
55
|
|
|
* @param string[]|null $header |
56
|
|
|
*/ |
57
|
|
|
private function writeContent($handle, $data, $header) |
58
|
|
|
{ |
59
|
|
|
//UTF-8 BOM |
60
|
|
|
fwrite($handle, "\xEF\xBB\xBF"); |
61
|
|
|
//set delimiter to specified |
62
|
|
|
fwrite($handle, 'sep='.static::DELIMITER."\n"); |
63
|
|
|
|
64
|
|
|
if (\is_array($header)) { |
65
|
|
|
// Add the header of the CSV file |
66
|
|
|
fputcsv($handle, $header, static::DELIMITER); |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
//add the data |
70
|
|
|
foreach ($data as $row) { |
71
|
|
|
fputcsv( |
72
|
|
|
$handle, // The file pointer |
73
|
|
|
$row, // The fields |
74
|
|
|
static::DELIMITER // The delimiter |
75
|
|
|
); |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|