StreamedCsvResponse   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 48
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

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

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 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
     * @throws \InvalidArgumentException
28
     */
29 14
    public function __construct($rows, $filename)
30
    {
31 14
        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
        ));
38
39
        try {
40 13
            $disposition = $this->headers->makeDisposition('attachment', $filename, !preg_match('/^[\x20-\x7e]*$/', $filename) ? 'Download.csv' : '');
41 1
        } 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 10
            $writer->writeRow($row);
59
        }
60 10
    }
61
}
62