| 1 | <?php |
||
| 14 | class StreamedCsvResponse extends StreamedResponse |
||
| 15 | { |
||
| 16 | /** |
||
| 17 | * @var array|\Traversable |
||
| 18 | */ |
||
| 19 | private $rows; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * Constructor. |
||
| 23 | * |
||
| 24 | * @param array|\Traversable $rows An iterable representing the csv rows. |
||
| 25 | * @param string $filename An filename the client downloads. |
||
| 26 | * |
||
| 27 | 14 | * @throws \InvalidArgumentException |
|
| 28 | */ |
||
| 29 | 14 | public function __construct($rows, $filename) |
|
| 30 | 1 | { |
|
| 31 | Assert::isIterable($rows, '$rows should be an array or an instance of \Traversable.'); |
||
| 32 | |||
| 33 | 13 | $this->rows = $rows; |
|
| 34 | |||
| 35 | 13 | parent::__construct(array($this, 'output'), 200, array( |
|
| 36 | 13 | 'Content-Type' => 'text/csv', |
|
| 37 | 13 | )); |
|
| 38 | |||
| 39 | try { |
||
| 40 | 13 | $disposition = $this->headers->makeDisposition('attachment', $filename, !preg_match('/^[\x20-\x7e]*$/', $filename) ? 'Download.csv' : ''); |
|
| 41 | 13 | } catch (\InvalidArgumentException $e) { |
|
| 42 | 1 | $disposition = $this->headers->makeDisposition('attachment', 'Download.csv'); |
|
| 43 | } |
||
| 44 | |||
| 45 | 13 | $this->headers->set('Content-Disposition', $disposition); |
|
| 46 | 13 | } |
|
| 47 | |||
| 48 | /** |
||
| 49 | * Outputs the result. |
||
| 50 | */ |
||
| 51 | 10 | public function output() |
|
| 61 | } |
||
| 62 |