1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of graze/data-file |
4
|
|
|
* |
5
|
|
|
* Copyright (c) 2016 Nature Delivered Ltd. <https://www.graze.com> |
6
|
|
|
* |
7
|
|
|
* For the full copyright and license information, please view the LICENSE |
8
|
|
|
* file that was distributed with this source code. |
9
|
|
|
* |
10
|
|
|
* @license https://github.com/graze/data-file/blob/master/LICENSE.md |
11
|
|
|
* @link https://github.com/graze/data-file |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Graze\DataFile\Format\Parser; |
15
|
|
|
|
16
|
|
|
use Graze\CsvToken\Csv\CsvConfiguration; |
17
|
|
|
use Graze\CsvToken\Parser; |
18
|
|
|
use Graze\CsvToken\Tokeniser\StreamTokeniser; |
19
|
|
|
use Graze\DataFile\Format\CsvFormatInterface; |
20
|
|
|
use Iterator; |
21
|
|
|
use LimitIterator; |
22
|
|
|
use Psr\Http\Message\StreamInterface; |
23
|
|
|
|
24
|
|
|
class CsvParser implements ParserInterface |
25
|
|
|
{ |
26
|
|
|
/** @var CsvFormatInterface */ |
27
|
|
|
private $csvFormat; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* @param CsvFormatInterface $csvFormat |
31
|
|
|
*/ |
32
|
5 |
|
public function __construct(CsvFormatInterface $csvFormat) |
33
|
|
|
{ |
34
|
5 |
|
$this->csvFormat = $csvFormat; |
35
|
5 |
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @param StreamInterface $stream |
39
|
|
|
* |
40
|
|
|
* @return Iterator |
41
|
|
|
*/ |
42
|
5 |
|
public function parse(StreamInterface $stream) |
43
|
|
|
{ |
44
|
5 |
|
$configuration = new CsvConfiguration([ |
45
|
5 |
|
CsvConfiguration::OPTION_DELIMITER => $this->csvFormat->getDelimiter(), |
46
|
5 |
|
CsvConfiguration::OPTION_QUOTE => $this->csvFormat->getQuoteCharacter(), |
47
|
5 |
|
CsvConfiguration::OPTION_ESCAPE => $this->csvFormat->getEscapeCharacter(), |
48
|
5 |
|
CsvConfiguration::OPTION_DOUBLE_QUOTE => $this->csvFormat->isDoubleQuote(), |
49
|
5 |
|
CsvConfiguration::OPTION_NEW_LINE => $this->csvFormat->getLineTerminator(), |
50
|
5 |
|
CsvConfiguration::OPTION_NULL => $this->csvFormat->getNullOutput(), |
51
|
5 |
|
]); |
52
|
5 |
|
$tokeniser = new StreamTokeniser($configuration, $stream); |
53
|
5 |
|
$parser = new Parser(); |
54
|
5 |
|
return $this->parseIterator( |
55
|
5 |
|
$parser->parse($tokeniser->getTokens()) |
56
|
5 |
|
); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Parse a supplied iterator |
61
|
|
|
* |
62
|
|
|
* @param Iterator $iterator |
63
|
|
|
* |
64
|
|
|
* @return Iterator |
65
|
|
|
*/ |
66
|
5 |
|
private function parseIterator(Iterator $iterator) |
67
|
|
|
{ |
68
|
5 |
|
if ($this->csvFormat->hasHeaders() || $this->csvFormat->getLimit() !== -1) { |
69
|
2 |
|
$iterator = new LimitIterator($iterator, $this->csvFormat->getHeaders(), $this->csvFormat->getLimit()); |
70
|
2 |
|
} |
71
|
5 |
|
return $iterator; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|