1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Palmtree\Csv; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Writes an array to a CSV file. |
7
|
|
|
*/ |
8
|
|
|
class Writer extends AbstractCsvDocument |
9
|
|
|
{ |
10
|
|
|
/** @var array */ |
11
|
|
|
private $headers = []; |
12
|
|
|
|
13
|
|
|
public static function write(string $filePath, array $data): void |
14
|
|
|
{ |
15
|
|
|
$writer = new self($filePath); |
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
|
|
|
* Uses the first row's keys as headers. |
25
|
|
|
*/ |
26
|
|
|
public function setData(array $data): self |
27
|
|
|
{ |
28
|
|
|
if ($this->hasHeaders) { |
29
|
|
|
$this->setHeaders(\array_keys(\reset($data))); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$this->addRows($data); |
33
|
|
|
|
34
|
|
|
return $this; |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
public function setHeaders(array $headers): self |
38
|
|
|
{ |
39
|
2 |
|
$this->headers = $headers; |
40
|
|
|
|
41
|
2 |
|
$this->addRow($this->headers); |
42
|
|
|
|
43
|
2 |
|
return $this; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function addHeader(string $header): self |
47
|
|
|
{ |
48
|
|
|
$headers = $this->headers; |
49
|
|
|
|
50
|
|
|
$headers[] = $header; |
51
|
|
|
|
52
|
|
|
$this->setHeaders($headers); |
53
|
|
|
|
54
|
|
|
return $this; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* Adds multiple rows of data to the CSV file. |
59
|
|
|
*/ |
60
|
|
|
public function addRows(array $rows): void |
61
|
|
|
{ |
62
|
|
|
foreach ($rows as $row) { |
63
|
|
|
$this->addRow($row); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Adds a row of data to the CSV file. |
69
|
|
|
* |
70
|
|
|
* @param array $row Row of data to add to the file. |
71
|
|
|
* |
72
|
|
|
* @return bool Whether the row was written to the file. |
73
|
|
|
*/ |
74
|
2 |
|
public function addRow(array $row): bool |
75
|
|
|
{ |
76
|
2 |
|
$result = $this->getDocument()->fwriteCsv($row); |
77
|
|
|
|
78
|
2 |
|
if ($result === 0) { |
79
|
|
|
// @todo: handle error |
80
|
|
|
return false; |
81
|
|
|
} |
82
|
|
|
|
83
|
2 |
|
return true; |
84
|
|
|
} |
85
|
|
|
|
86
|
2 |
|
public function getContents(): string |
87
|
|
|
{ |
88
|
2 |
|
$this->getDocument()->trimFinalLineEnding(); |
89
|
2 |
|
$this->getDocument()->fseek(0); |
90
|
|
|
|
91
|
2 |
|
$data = $this->getDocument()->fread($this->getDocument()->getSize()); |
92
|
|
|
|
93
|
2 |
|
if ($data === false) { |
94
|
|
|
return ''; |
95
|
|
|
} |
96
|
|
|
|
97
|
2 |
|
return $data; |
98
|
|
|
} |
99
|
|
|
|
100
|
2 |
|
protected function getOpenMode(): string |
101
|
|
|
{ |
102
|
2 |
|
return 'w+'; |
103
|
|
|
} |
104
|
|
|
} |
105
|
|
|
|