Completed
Push — refactoring ( bfbba7...4b6f46 )
by Issei
02:22
created

StreamedCsvResponse::__construct()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 3

Importance

Changes 0
Metric Value
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 10
nc 2
nop 2
crap 3
1
<?php
2
3
namespace Issei;
4
5
use Symfony\Component\HttpFoundation\StreamedResponse;
6
7
/**
8
 * Represents a CSV format file as streamed HTTP response.
9
 *
10
 * @author Issei Murasawa <[email protected]>
11
 */
12
class StreamedCsvResponse extends StreamedResponse
13
{
14
    /**
15
     * @var array|\Traversable
16
     */
17
    private $rows;
18
19
    /**
20
     * Constructor.
21
     *
22
     * @param array|\Traversable $rows     An iterable representing the csv rows.
23
     * @param string             $filename An filename the client downloads.
24
     *
25
     * @throws \InvalidArgumentException
26
     */
27 14
    public function __construct($rows, $filename)
28
    {
29 14
        Assert::isIterable($rows, '$rows should be an array or an instance of \Traversable.');
30
31 13
        $this->rows = $rows;
32
33 13
        parent::__construct(array($this, 'output'), 200, array(
34 13
            'Content-Type' => 'text/csv',
35 13
        ));
36
37
        try {
38 13
            $disposition = $this->headers->makeDisposition('attachment', $filename, !preg_match('/^[\x20-\x7e]*$/', $filename) ? 'Download.csv' : '');
39 13
        } catch (\InvalidArgumentException $e) {
40 1
            $disposition = $this->headers->makeDisposition('attachment', 'Download.csv');
41
        }
42
43 13
        $this->headers->set('Content-Disposition', $disposition);
44 13
    }
45
46
    /**
47
     * Outputs the result.
48
     */
49 10
    public function output()
50
    {
51 10
        set_time_limit(0);
52
53 10
        $writer = new CsvWriter($this->charset);
54
55 10
        foreach ($this->rows as $row) {
56 10
            $writer->writeRow($row);
57 10
        }
58 10
    }
59
}
60