Writer::addHeader()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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