1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Graze\CsvToken\Tokeniser; |
4
|
|
|
|
5
|
|
|
use Graze\CsvToken\Csv\CsvConfigurationInterface; |
6
|
|
|
use Iterator; |
7
|
|
|
use Psr\Http\Message\StreamInterface; |
8
|
|
|
|
9
|
|
|
class StreamTokeniser implements TokeniserInterface |
10
|
|
|
{ |
11
|
|
|
use TypeBuilder; |
12
|
|
|
use StateBuilder; |
13
|
|
|
|
14
|
|
|
/** @var int */ |
15
|
|
|
private $maxTypeLength; |
16
|
|
|
/** @var StreamInterface */ |
17
|
|
|
private $stream; |
18
|
|
|
/** @var State */ |
19
|
|
|
private $state; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Tokeniser constructor. |
23
|
|
|
* |
24
|
|
|
* @param CsvConfigurationInterface $config |
25
|
|
|
* @param StreamInterface $stream |
26
|
|
|
*/ |
27
|
19 |
|
public function __construct(CsvConfigurationInterface $config, StreamInterface $stream) |
28
|
|
|
{ |
29
|
19 |
|
$types = $this->getTypes($config); |
30
|
19 |
|
$this->state = $this->buildStates($types); |
31
|
19 |
|
$this->maxTypeLength = count($types) > 0 ? strlen(array_keys($types)[0]) : 1; |
32
|
19 |
|
$this->stream = $stream; |
33
|
19 |
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Loop through the stream, pulling maximum type length each time, find the largest type that matches and create a |
37
|
|
|
* token, then move on length characters |
38
|
|
|
* |
39
|
|
|
* @return Iterator |
40
|
|
|
*/ |
41
|
18 |
|
public function getTokens() |
42
|
|
|
{ |
43
|
18 |
|
$this->stream->rewind(); |
44
|
18 |
|
$position = $this->stream->tell(); |
45
|
18 |
|
$buffer = $this->stream->read($this->maxTypeLength); |
46
|
|
|
|
47
|
|
|
/** @var Token $last */ |
48
|
18 |
|
$last = null; |
49
|
|
|
|
50
|
18 |
|
while (strlen($buffer) > 0) { |
51
|
16 |
|
$token = $this->state->match($position, $buffer); |
52
|
16 |
|
$this->state = $this->state->getNextState($token->getType()); |
53
|
|
|
|
54
|
16 |
|
$len = $token->getLength(); |
55
|
|
|
|
56
|
|
|
// merge tokens together to condense T_CONTENT tokens |
57
|
16 |
|
if ($token->getType() == Token::T_CONTENT) { |
58
|
16 |
|
$last = (!is_null($last)) ? $last->addContent($token->getContent()) : $token; |
59
|
|
|
} else { |
60
|
15 |
|
if (!is_null($last)) { |
61
|
14 |
|
yield $last; |
62
|
14 |
|
$last = null; |
63
|
|
|
} |
64
|
15 |
|
yield $token; |
65
|
|
|
} |
66
|
|
|
|
67
|
16 |
|
$position += $len; |
68
|
16 |
|
$buffer = substr($buffer, $len) . $this->stream->read($len); |
69
|
|
|
} |
70
|
|
|
|
71
|
17 |
|
if (!is_null($last)) { |
72
|
5 |
|
yield $last; |
73
|
|
|
} |
74
|
|
|
|
75
|
17 |
|
$this->stream->close(); |
76
|
17 |
|
} |
77
|
|
|
} |
78
|
|
|
|