Completed
Push — master ( 4d01c3...1587a2 )
by Issei
12s
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 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.4285
cc 3
eloc 10
nc 2
nop 2
crap 3
1
<?php
2
3
namespace Issei;
4
5
use Issei\StreamedCsvResponse\Assert;
6
use Issei\StreamedCsvResponse\CsvWriter;
7
use Symfony\Component\HttpFoundation\StreamedResponse;
8
9
/**
10
 * Represents a CSV format file as streamed HTTP response.
11
 *
12
 * @author Issei Murasawa <[email protected]>
13
 */
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()
52
    {
53 10
        set_time_limit(0);
54
55 10
        $writer = new CsvWriter($this->charset);
56
57 10
        foreach ($this->rows as $row) {
58 5
            $writer->writeRow($row);
59 10
        }
60
    }
61
}
62