Skip to content

Commit f603ee0

Browse files
committed
Add push function
1 parent 648a3f6 commit f603ee0

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

src/CsvCollection.php

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,47 @@ public function save(string $file, array $options = []): self
115115
return $this;
116116
}
117117

118+
/**
119+
* Push an item into the collection and save the item to the csv file.
120+
*
121+
* @param string|null $file
122+
* @param array $line
123+
* @param array $options
124+
* @return \App\CsvCollection
125+
*/
126+
public function push(string $file, array $line, array $options = []): self
127+
{
128+
$options = array_merge(
129+
$this->options, $options
130+
);
131+
132+
$resource = fopen($file, 'a');
133+
134+
// Lock the file.
135+
if (! flock($resource, LOCK_EX)) {
136+
throw new IOException("Could not lock file");
137+
}
138+
139+
$write = static fn(array $line) => fputcsv(
140+
$resource, $line,
141+
$options['delimiter'],
142+
$options['enclosure'],
143+
$options['escape'],
144+
);
145+
146+
if ($options['header'] && $this->open($file)->count() === 0) {
147+
$write(array_keys($line));
148+
}
149+
150+
$write($line);
151+
152+
// Unlock the file.
153+
flock($resource, LOCK_UN);
154+
fclose($resource);
155+
156+
return $this->open($file, $options);
157+
}
158+
118159
/**
119160
* Set the collection's options.
120161
*

0 commit comments

Comments
 (0)