Completed
Push — master ( 008e8b...1915a6 )
by Issei
13s
created

CsvWriter::__destruct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
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 callable
21
     */
22
    private $columnFilter;
23
24
    public function __construct($columnFilter = null)
25
    {
26
        $this->out = fopen('php://output', 'wt');
27
        $this->columnFilter = $columnFilter;
28
    }
29
30
    public function __destruct()
31
    {
32
        fclose($this->out);
33
    }
34
35
    /**
36
     * WRites the csv to stdout.
37
     *
38
     * @param array|\Traversable $row
39
     */
40
    public function writeRow($row)
41
    {
42
        if (!is_array($row) && !$row instanceof \Traversable) {
43
            throw new \InvalidArgumentException('Every value of $rows should be an array or an instance of \Traversable.');
44
        }
45
46
        $startedTraverse = false;
47
48
        foreach ($row as $column) {
49
            if ($startedTraverse) {
50
                fwrite($this->out, ',');
51
            } else {
52
                $startedTraverse = true;
53
            }
54
55
            if ($this->columnFilter) {
56
                $column = call_user_func($this->columnFilter, $column);
57
            }
58
59
            fwrite($this->out, self::encloseColumn($column));
60
        }
61
62
        fwrite($this->out, "\r\n");
63
    }
64
65
    /**
66
     * Encloses the column value.
67
     *
68
     * @param string $column
69
     *
70
     * @return string
71
     */
72
    private static function encloseColumn($column)
73
    {
74
        return '"' . str_replace('"', '""', $column) . '"';
75
    }
76
}
77