CsvWriter::__construct()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 5
cts 5
cp 1
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 3
1
<?php
2
3
namespace Issei\StreamedCsvResponse;
4
5
/**
6
 * Writes the csv row to stdout.
7
 *
8
 * {@internal Don't use this in user-land code }}
9
 *
10
 * @author Issei Murasawa <[email protected]>
11
 */
12
class CsvWriter
13
{
14
    /**
15
     * @var resource
16
     */
17
    private $out;
18
19
    /**
20
     * @var string|null
21
     */
22
    private $encodeTo;
23
24 11
    public function __construct($encodeTo = null)
25
    {
26 11
        $this->out = fopen('php://output', 'wt');
27
28 11
        if (null !== $encodeTo && 'UTF-8' !== strtoupper($encodeTo)) {
29 5
            $this->encodeTo = $encodeTo;
30
        }
31 11
    }
32
33 11
    public function __destruct()
34
    {
35 11
        fclose($this->out);
36 11
    }
37
38
    /**
39
     * Writes the csv to stdout.
40
     *
41
     * @param array|\Traversable $row
42
     */
43 11
    public function writeRow($row)
44
    {
45 11
        Assert::isIterable($row, 'Every value of $rows should be an array or an instance of \Traversable.');
46
47 10
        $separator = '';
48
49 10
        foreach ($row as $cell) {
50 10
            fwrite($this->out, $separator . $this->formatCell($cell));
51
52 10
            if ('' === $separator) {
53 10
                $separator = ',';
54
            }
55
        }
56
57 10
        fwrite($this->out, "\r\n");
58 10
    }
59
60
    /**
61
     * Returns the formatted cell.
62
     *
63
     * @param string $cell
64
     *
65
     * @return string
66
     */
67 10
    private function formatCell($cell)
68
    {
69
        // auto encoding
70 10
        if (null !== $this->encodeTo) {
71 5
            $cell = mb_convert_encoding($cell, $this->encodeTo, 'UTF-8');
72
        }
73
74
        // enclosing
75 10
        return '"' . str_replace('"', '""', $cell) . '"';
76
    }
77
}
78