|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Odiseo\SyliusReportPlugin\Response; |
|
6
|
|
|
|
|
7
|
|
|
use Odiseo\SyliusReportPlugin\DataFetcher\Data; |
|
8
|
|
|
use Symfony\Component\HttpFoundation\Response; |
|
9
|
|
|
|
|
10
|
|
|
class CsvResponse extends Response |
|
11
|
|
|
{ |
|
12
|
|
|
|
|
13
|
|
|
protected ?string $data = null; |
|
14
|
|
|
protected string $filename = 'export.csv'; |
|
15
|
|
|
|
|
16
|
|
|
public function __construct(?Data $data = null, int $status = 200, array $headers = []) |
|
17
|
|
|
{ |
|
18
|
|
|
parent::__construct('', $status, $headers); |
|
19
|
|
|
$this->setData($data); |
|
|
|
|
|
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
|
|
public static function create(?Data $data = null, int $status = 200, array $headers = []) |
|
23
|
|
|
{ |
|
24
|
|
|
return new static($labels, $data, $status, $headers); |
|
|
|
|
|
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
public function setData(Data $data): self |
|
28
|
|
|
{ |
|
29
|
|
|
$output = fopen('php://temp', 'r+'); |
|
30
|
|
|
|
|
31
|
|
|
if ($output === false) { |
|
32
|
|
|
throw new \RuntimeException('Could not create a buffer for CSV output.'); |
|
33
|
|
|
} |
|
34
|
|
|
|
|
35
|
|
|
foreach ($data->getData() as $row) { |
|
36
|
|
|
fputcsv($output, $row); |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
rewind($output); |
|
40
|
|
|
$this->data = ''; |
|
41
|
|
|
|
|
42
|
|
|
while ($line = fgets($output)) { |
|
43
|
|
|
$this->data .= $line; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
$this->data .= fgets($output); |
|
47
|
|
|
|
|
48
|
|
|
return $this->update(); |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function getFilename(): string |
|
52
|
|
|
{ |
|
53
|
|
|
return $this->filename; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function setFilename(string $filename): self |
|
57
|
|
|
{ |
|
58
|
|
|
$this->filename = $filename; |
|
59
|
|
|
|
|
60
|
|
|
return $this->update(); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
protected function update(): self |
|
64
|
|
|
{ |
|
65
|
|
|
$this->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $this->filename)); |
|
66
|
|
|
if (!$this->headers->has('Content-Type')) { |
|
67
|
|
|
$this->headers->set('Content-Type', 'text/csv'); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return $this->setContent($this->data); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|