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

StreamedCsvResponse   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
lcom 1
cbo 4
dl 0
loc 48
ccs 18
cts 18
cp 1
rs 10
c 1
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 18 3
A output() 0 10 2
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