Completed
Push — master ( 008e8b...1915a6 )
by Issei
13s
created

StreamedCsvResponse::encodeRow()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 3
cts 3
cp 1
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
nop 2
crap 1
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 10
    public function __construct($rows, $filename)
28
    {
29 10
        if (!is_array($rows) && !$rows instanceof \Traversable) {
30 1
            throw new \InvalidArgumentException('$rows should be an array or an instance of \Traversable.');
31
        }
32
33 9
        $this->rows = $rows;
34
35 9
        parent::__construct(array($this, 'output'), 200, array(
36 9
            'Content-Type' => 'text/csv',
37 9
        ));
38
39
        try {
40 9
            $disposition = $this->headers->makeDisposition('attachment', $filename, !preg_match('/^[\x20-\x7e]*$/', $filename) ? 'Download.csv' : '');
41 9
        } catch (\InvalidArgumentException $e) {
42 1
            $disposition = $this->headers->makeDisposition('attachment', 'Download.csv');
43
        }
44
45 9
        $this->headers->set('Content-Disposition', $disposition);
46 9
    }
47
48
    /**
49
     * Outputs the result.
50
     */
51 6
    public function output()
52
    {
53 6
        set_time_limit(0);
54
55 6
        $charset = $this->charset;
56 6
57 3
        $writer = new CsvWriter($charset ? function ($column) use ($charset) {
58 3
            return mb_convert_encoding($column, $charset);
59
        } : null);
60 6
61 6
        foreach ($this->rows as $row) {
62 6
            $writer->writeRow($row);
63
        }
64
    }
65
}
66