Completed
Push — refactoring ( 8b74b5...bfbba7 )
by Issei
02:15
created

CsvWriter::formatCell()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 10
ccs 5
cts 5
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 1
crap 2
1
<?php
2
3
namespace Issei;
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 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 5
        }
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
        if (!is_array($row) && !$row instanceof \Traversable) {
46 1
            throw new \InvalidArgumentException('Every value of $rows should be an array or an instance of \Traversable.');
47
        }
48
49 10
        $separator = '';
50
51 10
        foreach ($row as $cell) {
52 10
            fwrite($this->out, $separator . $this->formatCell($cell));
53
54 10
            if ('' === $separator) {
55 10
                $separator = ',';
56 10
            }
57 10
        }
58
59 10
        fwrite($this->out, "\r\n");
60 10
    }
61
62
    /**
63
     * Returns the formatted cell.
64
     *
65
     * @param string $cell
66
     *
67
     * @return string
68
     */
69 10
    private function formatCell($cell)
70
    {
71
        // auto encoding
72 10
        if (null !== $this->encodeTo) {
73 5
            $cell = mb_convert_encoding($cell, $this->encodeTo, 'UTF-8');
74 5
        }
75
76
        // enclosing
77 10
        return '"' . str_replace('"', '""', $cell) . '"';
78
    }
79
}
80