Completed
Push — master ( 4d01c3...1587a2 )
by Issei
12s
created

CsvWriter::formatCell()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
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 null
21
     */
22
    private $encodeTo;
23
24
    public function __construct($encodeTo = null)
25
    {
26
        $this->out = fopen('php://output', 'wt');
27
28
        if (null !== $encodeTo && 'UTF-8' !== strtoupper($encodeTo)) {
29
            $this->encodeTo = $encodeTo;
30
        }
31
    }
32
33
    public function __destruct()
34
    {
35
        fclose($this->out);
36
    }
37
38
    /**
39
     * Writes the csv to stdout.
40
     *
41
     * @param array|\Traversable $row
42
     */
43
    public function writeRow($row)
44
    {
45
        Assert::isIterable($row, 'Every value of $rows should be an array or an instance of \Traversable.');
46
47
        $separator = '';
48
49
        foreach ($row as $cell) {
50
            fwrite($this->out, $separator . $this->formatCell($cell));
51
52
            if ('' === $separator) {
53
                $separator = ',';
54
            }
55
        }
56
57
        fwrite($this->out, "\r\n");
58
    }
59
60
    /**
61
     * Returns the formatted cell.
62
     *
63
     * @param string $cell
64
     *
65
     * @return string
66
     */
67
    private function formatCell($cell)
68
    {
69
        // auto encoding
70
        if (null !== $this->encodeTo) {
71
            $cell = mb_convert_encoding($cell, $this->encodeTo, 'UTF-8');
72
        }
73
74
        // enclosing
75
        return '"' . str_replace('"', '""', $cell) . '"';
76
    }
77
}
78