Completed
Branch refactoring (063763)
by Issei
01:46
created

CsvWriter::encloseColumn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
cc 1
eloc 2
nc 1
nop 1
crap 1
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
        $startedTraverse = false;
50
51 10
        foreach ($row as $cell) {
52 10
            if ($startedTraverse) {
53 10
                fwrite($this->out, ',');
54 10
            } else {
55 10
                $startedTraverse = true;
56
            }
57
58 10
            if (null !== $this->encodeTo) {
59 5
                $cell = mb_convert_encoding($cell, $this->encodeTo, 'UTF-8');
60 5
            }
61
62 10
            fwrite($this->out, '"' . str_replace('"', '""', $cell) . '"');
63 10
        }
64
65 10
        fwrite($this->out, "\r\n");
66 10
    }
67
}
68