Passed
Branch feature/php7 (3e8a2f)
by Andy
04:54
created

Writer::setData()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 9
ccs 0
cts 5
cp 0
rs 10
cc 2
nc 2
nop 1
crap 6
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 array */
11
    private $headers = [];
12
13
    public function getOpenMode(): string
14
    {
15
        return 'w+';
16
    }
17
18
    public static function write($file, $data): void
19
    {
20
        $writer = new static($file);
21
        $writer->setData($data);
22
        $writer->closeDocument();
23
    }
24
25
    /**
26
     * Sets headers and all rows on the CSV file and
27
     * then closes the file handle.
28
     *
29
     * Uses the first row's keys as headers.
30
     */
31
    public function setData(array $data): self
32
    {
33
        if ($this->hasHeaders) {
34
            $this->setHeaders(\array_keys(\reset($data)));
35
        }
36
37
        $this->addRows($data);
38
39
        return $this;
40
    }
41
42
    public function setHeaders(array $headers): self
43
    {
44
        $this->createDocument();
45
46
        $this->headers = $headers;
47
48
        $this->addRow($this->headers);
49
50
        return $this;
51
    }
52
53
    public function addHeader(string $header): self
54
    {
55
        $headers = $this->headers;
56
57
        $headers[] = $header;
58
59
        $this->setHeaders($headers);
60
61
        return $this;
62
    }
63
64
    /**
65
     * Adds multiple rows of data to the CSV file.
66
     */
67
    public function addRows(array $rows): void
68
    {
69
        foreach ($rows as $row) {
70
            $this->addRow($row);
71
        }
72
    }
73
74
    /**
75
     * Adds a row of data to the CSV file.
76
     *
77
     * @param array $row Row of data to add to the file.
78
     *
79
     * @return bool Whether the row was written to the file.
80
     */
81
    public function addRow(array $row): bool
82
    {
83
        $result = $this->getDocument()->fwriteCsv($row);
84
85
        if ($result === false) {
86
            // @todo: handle error
87
            return false;
88
        }
89
90
        return true;
91
    }
92
93
    /**
94
     * @return string
95
     */
96
    public function getContents()
97
    {
98
        $this->getDocument()->trimFinalLineEnding();
99
        $this->getDocument()->fseek(0);
100
101
        return $this->getDocument()->fread($this->getDocument()->getSize());
102
    }
103
}
104