Passed
Push — master ( 75715f...53a757 )
by Andy
05:10
created

Writer::getCsvString()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 0
cts 0
cp 0
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 1
crap 2
1
<?php
2
3
namespace Palmtree\Csv;
4
5
/**
6
 * Writes an array to a CSV file.
7
 */
8
class Writer extends AbstractCsv
9
{
10
    /** @var string */
11
    protected $openMode = 'w+';
12
13
    public static function write($file, $data)
14
    {
15
        $writer = new static($file);
16
        $writer->setData($data);
17
        $writer->closeDocument();
18
    }
19
20
    /**
21
     * Sets headers and all rows on the CSV file and
22
     * then closes the file handle.
23
     *
24
     * @param $data
25
     *
26
     * @return $this
27
     */
28
    public function setData($data)
29
    {
30
        if ($this->hasHeaders()) {
31
            $this->setHeaders(array_keys(reset($data)));
32
        }
33
34
        $this->addRows($data);
35
36
        return $this;
37
    }
38
39
    /**
40
     * @param array $headers
41
     *
42
     * @return $this
43
     */
44
    public function setHeaders(array $headers)
45
    {
46
        $this->createDocument();
47
48
        $this->addRow($headers);
49
50
        return $this;
51
    }
52
53
    /**
54
     * Adds multiple rows of data to the CSV file.
55
     *
56
     * @param array $rows
57
     */
58
    public function addRows($rows)
59
    {
60
        foreach ($rows as $row) {
61
            $this->addRow($row);
62
        }
63
    }
64
65
    /**
66
     * Adds a row of data to the CSV file.
67
     *
68
     * @param array $row Row of data to add to the file.
69
     *
70
     * @return bool Whether the row was written to the file.
71
     */
72
    public function addRow($row)
73
    {
74
        $result = $this->getDocument()->fputcsv($row);
75
76
        if ($result === false) {
77
            // @todo: handle error
78
            return false;
79
        }
80
81
        return true;
82
    }
83
}
84