-
-
Notifications
You must be signed in to change notification settings - Fork 339
/
Copy pathAbstractCsv.php
490 lines (422 loc) · 13 KB
/
AbstractCsv.php
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
<?php
/**
* League.Csv (https://csv.thephpleague.com)
*
* (c) Ignace Nyamagana Butera <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace League\Csv;
use Generator;
use RuntimeException;
use SplFileObject;
use Stringable;
use Throwable;
use function filter_var;
use function get_class;
use function rawurlencode;
use function sprintf;
use function str_replace;
use function str_split;
use function strcspn;
use function strlen;
use const FILTER_FLAG_STRIP_HIGH;
use const FILTER_FLAG_STRIP_LOW;
use const FILTER_UNSAFE_RAW;
/**
* An abstract class to enable CSV document loading.
*/
abstract class AbstractCsv implements ByteSequence
{
protected const STREAM_FILTER_MODE = STREAM_FILTER_READ;
/** @var array<string, bool> collection of stream filters. */
protected array $stream_filters = [];
protected ?Bom $input_bom = null;
protected ?Bom $output_bom = null;
protected string $delimiter = ',';
protected string $enclosure = '\\';
protected string $escape = '';
protected bool $is_input_bom_included = false;
/**
* @final This method should not be overwritten in child classes
*/
protected function __construct(protected readonly SplFileObject|Stream $document)
{
[$this->delimiter, $this->enclosure, $this->escape] = $this->document->getCsvControl();
$this->resetProperties();
}
/**
* Reset dynamic object properties to improve performance.
*/
protected function resetProperties(): void
{
}
/**
* @throws UnavailableStream
*/
public function __clone()
{
throw UnavailableStream::dueToForbiddenCloning(static::class);
}
/**
* Returns a new instance from a SplFileObject.
*/
public static function createFromFileObject(SplFileObject $file): static
{
return new static($file);
}
/**
* Returns a new instance from a PHP resource stream.
*
* @param resource $stream
*/
public static function createFromStream($stream): static
{
return new static(Stream::createFromResource($stream));
}
/**
* Returns a new instance from a string.
*/
public static function createFromString(Stringable|string $content = ''): static
{
return new static(Stream::createFromString((string) $content));
}
/**
* Returns a new instance from a file path.
*
* @param resource|null $context the resource context
*
* @throws UnavailableStream
*/
public static function createFromPath(string $path, string $open_mode = 'r+', $context = null): static
{
return new static(Stream::createFromPath($path, $open_mode, $context));
}
/**
* Returns the current field delimiter.
*/
public function getDelimiter(): string
{
return $this->delimiter;
}
/**
* Returns the current field enclosure.
*/
public function getEnclosure(): string
{
return $this->enclosure;
}
/**
* Returns the pathname of the underlying document.
*/
public function getPathname(): string
{
return $this->document->getPathname();
}
/**
* Returns the current field escape character.
*/
public function getEscape(): string
{
return $this->escape;
}
/**
* Returns the BOM sequence in use on Output methods.
*/
public function getOutputBOM(): string
{
return $this->output_bom?->value ?? '';
}
/**
* Returns the BOM sequence of the given CSV.
*/
public function getInputBOM(): string
{
if (null === $this->input_bom) {
$this->document->setFlags(SplFileObject::READ_CSV);
$this->input_bom = Bom::tryFromSequence($this->document);
}
return $this->input_bom?->value ?? '';
}
/**
* Tells whether the stream filter read capabilities can be used.
*/
public function supportsStreamFilterOnRead(): bool
{
return $this->document instanceof Stream
&& (static::STREAM_FILTER_MODE & STREAM_FILTER_READ) === STREAM_FILTER_READ;
}
/**
* Tells whether the stream filter write capabilities can be used.
*/
public function supportsStreamFilterOnWrite(): bool
{
return $this->document instanceof Stream
&& (static::STREAM_FILTER_MODE & STREAM_FILTER_WRITE) === STREAM_FILTER_WRITE;
}
/**
* Tells whether the specified stream filter is attached to the current stream.
*/
public function hasStreamFilter(string $filtername): bool
{
return $this->stream_filters[$filtername] ?? false;
}
/**
* Tells whether the BOM can be stripped if presents.
*/
public function isInputBOMIncluded(): bool
{
return $this->is_input_bom_included;
}
/**
* Returns the CSV document as a Generator of string chunk.
*
* @throws Exception if the number of bytes is less than 1
*/
public function chunk(int $length): Generator
{
if ($length < 1) {
throw InvalidArgument::dueToInvalidChunkSize($length, __METHOD__);
}
$this->document->rewind();
$this->document->setFlags(0);
if (-1 === $this->document->fseek(strlen($this->getInputBOM()))) {
throw new RuntimeException('Unable to seek the document.');
}
yield from str_split($this->getOutputBOM().$this->document->fread($length), $length);
while ($this->document->valid()) {
yield $this->document->fread($length);
}
}
/**
* Retrieves the CSV content.
*
* @throws Exception If the string representation can not be returned
*/
public function toString(): string
{
$raw = '';
foreach ($this->chunk(8192) as $chunk) {
$raw .= $chunk;
}
return $raw;
}
/**
* Outputs all data on the CSV file.
*
* Returns the number of characters read from the handle and passed through to the output.
*
* @throws Exception
*/
public function output(?string $filename = null): int
{
if (null !== $filename) {
$this->sendHeaders($filename);
}
$this->document->rewind();
$this->document->setFlags(0);
if (!$this->is_input_bom_included && -1 === $this->document->fseek(strlen($this->getInputBOM()))) {
throw new RuntimeException('Unable to seek the document.');
}
$stream = Stream::createFromString($this->getOutputBOM());
$stream->rewind();
$res1 = $stream->fpassthru();
if (false === $res1) {
throw new RuntimeException('Unable to output the document.');
}
$res2 = $this->document->fpassthru();
if (false === $res2) {
throw new RuntimeException('Unable to output the document.');
}
return $res1 + $res2;
}
/**
* Send the CSV headers.
*
* Adapted from Symfony\Component\HttpFoundation\ResponseHeaderBag::makeDisposition
*
* @throws Exception if the submitted header is invalid according to RFC 6266
*
* @see https://tools.ietf.org/html/rfc6266#section-4.3
*/
protected function sendHeaders(string $filename): void
{
if (strlen($filename) !== strcspn($filename, '\\/')) {
throw InvalidArgument::dueToInvalidHeaderFilename($filename);
}
$flag = FILTER_FLAG_STRIP_LOW;
if (1 === preg_match('/[^\x20-\x7E]/', $filename)) {
$flag |= FILTER_FLAG_STRIP_HIGH;
}
/** @var string $filtered_name */
$filtered_name = filter_var($filename, FILTER_UNSAFE_RAW, $flag);
$filename_fallback = str_replace('%', '', $filtered_name);
$disposition = sprintf('attachment; filename="%s"', str_replace('"', '\\"', $filename_fallback));
if ($filename !== $filename_fallback) {
$disposition .= sprintf("; filename*=utf-8''%s", rawurlencode($filename));
}
header('Content-Type: text/csv');
header('Content-Transfer-Encoding: binary');
header('Content-Description: File Transfer');
header('Content-Disposition: '.$disposition);
}
/**
* Sets the field delimiter.
*
* @throws InvalidArgument If the Csv control character is not one character only.
*/
public function setDelimiter(string $delimiter): static
{
if ($delimiter === $this->delimiter) {
return $this;
}
if (1 !== strlen($delimiter)) {
throw InvalidArgument::dueToInvalidDelimiterCharacter($delimiter, __METHOD__);
}
$this->delimiter = $delimiter;
$this->resetProperties();
return $this;
}
/**
* Sets the field enclosure.
*
* @throws InvalidArgument If the Csv control character is not one character only.
*/
public function setEnclosure(string $enclosure): static
{
if ($enclosure === $this->enclosure) {
return $this;
}
if (1 !== strlen($enclosure)) {
throw InvalidArgument::dueToInvalidEnclosureCharacter($enclosure, __METHOD__);
}
$this->enclosure = $enclosure;
$this->resetProperties();
return $this;
}
/**
* Sets the field escape character.
*
* @throws InvalidArgument If the Csv control character is not one character only.
*/
public function setEscape(string $escape): static
{
if ($escape === $this->escape) {
return $this;
}
if ('' !== $escape && 1 !== strlen($escape)) {
throw InvalidArgument::dueToInvalidEscapeCharacter($escape, __METHOD__);
}
$this->escape = $escape;
$this->resetProperties();
return $this;
}
/**
* Enables BOM Stripping.
*/
public function skipInputBOM(): static
{
$this->is_input_bom_included = false;
return $this;
}
/**
* Disables skipping Input BOM.
*/
public function includeInputBOM(): static
{
$this->is_input_bom_included = true;
return $this;
}
/**
* Sets the BOM sequence to prepend the CSV on output.
*
* @throws InvalidArgument if the given non-empty string is not a valid BOM sequence
*/
public function setOutputBOM(Bom|string|null $str): static
{
try {
$this->output_bom = match (true) {
$str instanceof Bom => $str,
null === $str,
'' === $str => null,
default => Bom::fromSequence($str),
};
return $this;
} catch (Throwable $exception) {
throw InvalidArgument::dueToInvalidBOMCharacter(__METHOD__, $exception);
}
}
/**
* Append a stream filter.
*
* @throws InvalidArgument If the stream filter API can not be appended
* @throws UnavailableFeature If the stream filter API can not be used
*/
public function addStreamFilter(string $filtername, null|array $params = null): static
{
if (!$this->document instanceof Stream) {
throw UnavailableFeature::dueToUnsupportedStreamFilterApi(get_class($this->document));
}
$this->document->appendFilter($filtername, static::STREAM_FILTER_MODE, $params);
$this->stream_filters[$filtername] = true;
$this->resetProperties();
$this->input_bom = null;
return $this;
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated since version 9.7.0
* @see AbstractCsv::supportsStreamFilterOnRead
* @see AbstractCsv::supportsStreamFilterOnWrite
* @codeCoverageIgnore
*
* Returns the stream filter mode.
*/
public function getStreamFilterMode(): int
{
return static::STREAM_FILTER_MODE;
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated since version 9.7.0
* @see AbstractCsv::supportsStreamFilterOnRead
* @see AbstractCsv::supportsStreamFilterOnWrite
* @codeCoverageIgnore
*
* Tells whether the stream filter capabilities can be used.
*/
public function supportsStreamFilter(): bool
{
return $this->document instanceof Stream;
}
/**
* Retrieves the CSV content.
*
* DEPRECATION WARNING! This method will be removed in the next major point release
*
* @deprecated since version 9.7.0
* @see AbstractCsv::toString
* @codeCoverageIgnore
*/
public function getContent(): string
{
return $this->toString();
}
/**
* DEPRECATION WARNING! This method will be removed in the next major point release.
*
* @deprecated since version 9.1.0
* @see AbstractCsv::toString
* @codeCoverageIgnore
*
* Retrieves the CSV content
*/
public function __toString(): string
{
return $this->toString();
}
}