File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change @@ -115,6 +115,47 @@ public function save(string $file, array $options = []): self
115
115
return $ this ;
116
116
}
117
117
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
+
118
159
/**
119
160
* Set the collection's options.
120
161
*
You can’t perform that action at this time.
0 commit comments