-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathCsvFile.php
More file actions
465 lines (415 loc) · 11 KB
/
CsvFile.php
File metadata and controls
465 lines (415 loc) · 11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php
namespace Keboola\Csv;
class CsvFile extends \SplFileInfo implements \Iterator
{
const DEFAULT_DELIMITER = ',';
const DEFAULT_ENCLOSURE = '"';
const DEFAULT_ESCAPED_BY = "";
/**
* @var string
*/
protected $delimiter;
/**
* @var string
*/
protected $enclosure;
/**
* @var string
*/
protected $escapedBy;
/**
* @var int
*/
protected $skipLines;
/**
* @var resource
*/
protected $filePointer;
/**
* @var int
*/
protected $rowCounter = 0;
/**
* @var array|null|false
*/
protected $currentRow;
/**
* @var string
*/
protected $lineBreak;
/**
* CsvFile constructor.
* @param string $fileName
* @param string $delimiter
* @param string $enclosure
* @param string $escapedBy
* @param int $skipLines
* @throws InvalidArgumentException
*/
public function __construct(
$fileName,
$delimiter = self::DEFAULT_DELIMITER,
$enclosure = self::DEFAULT_ENCLOSURE,
$escapedBy = self::DEFAULT_ESCAPED_BY,
$skipLines = 0
) {
parent::__construct($fileName);
$this->escapedBy = $escapedBy;
$this->setDelimiter($delimiter);
$this->setEnclosure($enclosure);
$this->setSkipLines($skipLines);
}
public function __destruct()
{
$this->closeFile();
}
/**
* @param integer $skipLines
* @return CsvFile
* @throws InvalidArgumentException
*/
protected function setSkipLines($skipLines)
{
$this->validateSkipLines($skipLines);
$this->skipLines = $skipLines;
return $this;
}
/**
* @param integer $skipLines
* @throws InvalidArgumentException
*/
protected function validateSkipLines($skipLines)
{
if (!is_int($skipLines) || $skipLines < 0) {
throw new InvalidArgumentException(
"Number of lines to skip must be a positive integer. \"$skipLines\" received.",
Exception::INVALID_PARAM,
null,
Exception::INVALID_PARAM_STR
);
}
}
/**
* @param string $delimiter
* @return CsvFile
* @throws InvalidArgumentException
*/
protected function setDelimiter($delimiter)
{
$this->validateDelimiter($delimiter);
$this->delimiter = $delimiter;
return $this;
}
/**
* @param string $delimiter
* @throws InvalidArgumentException
*/
protected function validateDelimiter($delimiter)
{
if (strlen($delimiter) > 1) {
throw new InvalidArgumentException(
"Delimiter must be a single character. \"$delimiter\" received",
Exception::INVALID_PARAM,
null,
Exception::INVALID_PARAM_STR
);
}
if (strlen($delimiter) == 0) {
throw new InvalidArgumentException(
"Delimiter cannot be empty.",
Exception::INVALID_PARAM,
null,
Exception::INVALID_PARAM_STR
);
}
}
/**
* @param string $enclosure
* @return $this
* @throws InvalidArgumentException
*/
protected function setEnclosure($enclosure)
{
$this->validateEnclosure($enclosure);
$this->enclosure = $enclosure;
return $this;
}
/**
* @param string $enclosure
* @throws InvalidArgumentException
*/
protected function validateEnclosure($enclosure)
{
if (strlen($enclosure) > 1) {
throw new InvalidArgumentException(
"Enclosure must be a single character. \"$enclosure\" received",
Exception::INVALID_PARAM,
null,
Exception::INVALID_PARAM_STR
);
}
}
/**
* @return string
* @throws Exception
*/
protected function detectLineBreak()
{
rewind($this->getFilePointer());
$sample = fread($this->getFilePointer(), 10000);
rewind($this->getFilePointer());
$possibleLineBreaks = [
"\r\n", // win
"\r", // mac
"\n", // unix
];
$lineBreaksPositions = [];
foreach ($possibleLineBreaks as $lineBreak) {
$position = strpos($sample, $lineBreak);
if ($position === false) {
continue;
}
$lineBreaksPositions[$lineBreak] = $position;
}
asort($lineBreaksPositions);
reset($lineBreaksPositions);
return empty($lineBreaksPositions) ? "\n" : key($lineBreaksPositions);
}
/**
* @return array|false|null
* @throws Exception
* @throws InvalidArgumentException
*/
protected function readLine()
{
$this->validateLineBreak();
// allow empty enclosure hack
$enclosure = !$this->getEnclosure() ? chr(0) : $this->getEnclosure();
$escapedBy = !$this->escapedBy ? chr(0) : $this->escapedBy;
return fgetcsv($this->getFilePointer(), null, $this->getDelimiter(), $enclosure, $escapedBy);
}
/**
* @param string $mode
* @return resource
* @throws Exception
*/
protected function getFilePointer($mode = 'r')
{
if (!is_resource($this->filePointer)) {
$this->openCsvFile($mode);
}
return $this->filePointer;
}
/**
* @param string $mode
* @throws Exception
*/
protected function openCsvFile($mode)
{
if ($mode == 'r' && !is_file($this->getPathname())) {
throw new Exception(
"Cannot open file {$this->getPathname()}",
Exception::FILE_NOT_EXISTS,
null,
Exception::FILE_NOT_EXISTS_STR
);
}
$this->filePointer = @fopen($this->getPathname(), $mode);
if (!$this->filePointer) {
throw new Exception(
"Cannot open file {$this->getPathname()} " . error_get_last()['message'],
Exception::FILE_NOT_EXISTS,
null,
Exception::FILE_NOT_EXISTS_STR
);
}
}
protected function closeFile()
{
if (is_resource($this->filePointer)) {
fclose($this->filePointer);
}
}
/**
* @return string
*/
public function getDelimiter()
{
return $this->delimiter;
}
/**
* @return string
*/
public function getEnclosure()
{
return $this->enclosure;
}
/**
* @return string
*/
public function getEscapedBy()
{
return $this->escapedBy;
}
/**
* @return int
*/
public function getColumnsCount()
{
return count($this->getHeader());
}
/**
* @return array
*/
public function getHeader()
{
$this->rewind();
$current = $this->current();
if (is_array($current)) {
return $current;
}
return [];
}
/**
* @param array $row
* @throws Exception
*/
public function writeRow(array $row)
{
$str = $this->rowToStr($row);
$ret = fwrite($this->getFilePointer('w+'), $str);
/* According to http://php.net/fwrite the fwrite() function
should return false on error. However not writing the full
string (which may occur e.g. when disk is full) is not considered
as an error. Therefore both conditions are necessary. */
if (($ret === false) || (($ret === 0) && (strlen($str) > 0))) {
throw new Exception(
"Cannot write to CSV file " . $this->getPathname() .
($ret === false && error_get_last() ? 'Error: ' . error_get_last()['message'] : '') .
' Return: ' . json_encode($ret) .
' To write: ' . strlen($str) . ' Written: ' . $ret,
Exception::WRITE_ERROR,
null,
Exception::WRITE_ERROR_STR
);
}
}
/**
* @param array $row
* @return string
* @throws Exception
*/
public function rowToStr(array $row)
{
$return = [];
foreach ($row as $column) {
if (!(
is_scalar($column)
|| is_null($column)
|| (
is_object($column)
&& method_exists($column, '__toString')
)
)) {
$type = gettype($column);
throw new Exception(
"Cannot write {$type} into a column",
Exception::WRITE_ERROR,
null,
Exception::WRITE_ERROR_STR,
['column' => $column]
);
}
$return[] = $this->getEnclosure() .
str_replace($this->getEnclosure(), str_repeat($this->getEnclosure(), 2), $column) .
$this->getEnclosure();
}
return implode($this->getDelimiter(), $return) . "\n";
}
/**
* @return string
* @throws Exception
*/
public function getLineBreak()
{
if (!$this->lineBreak) {
$this->lineBreak = $this->detectLineBreak();
}
return $this->lineBreak;
}
/**
* @return string
* @throws Exception
*/
public function getLineBreakAsText()
{
return trim(json_encode($this->getLineBreak()), '"');
}
/**
* @return string
* @throws InvalidArgumentException
*/
public function validateLineBreak()
{
try {
$lineBreak = $this->getLineBreak();
} catch (Exception $e) {
throw new InvalidArgumentException(
"Failed to detect line break: " . $e->getMessage(),
Exception::INVALID_PARAM,
$e,
Exception::INVALID_PARAM_STR
);
}
if (in_array($lineBreak, ["\r\n", "\n", "\r"])) {
return $lineBreak;
}
throw new InvalidArgumentException(
"Invalid line break. Please use unix \\n or win \\r\\n or Mac \\r line breaks.",
Exception::INVALID_PARAM,
null,
Exception::INVALID_PARAM_STR
);
}
/**
* @inheritdoc
*/
public function current()
{
return $this->currentRow;
}
/**
* @inheritdoc
*/
public function next()
{
$this->currentRow = $this->readLine();
$this->rowCounter++;
}
/**
* @inheritdoc
*/
public function key()
{
return $this->rowCounter;
}
/**
* @inheritdoc
*/
public function valid()
{
return $this->currentRow !== false;
}
/**
* @inheritdoc
*/
public function rewind()
{
rewind($this->getFilePointer());
for ($i = 0; $i < $this->skipLines; $i++) {
$this->readLine();
}
$this->currentRow = $this->readLine();
$this->rowCounter = 0;
}
}