forked from clue/reactphp-csv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAssocDecoder.php
More file actions
117 lines (98 loc) · 2.99 KB
/
AssocDecoder.php
File metadata and controls
117 lines (98 loc) · 2.99 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
<?php
namespace Clue\React\Csv;
use Evenement\EventEmitter;
use React\Stream\ReadableStreamInterface;
use React\Stream\WritableStreamInterface;
use React\Stream\Util;
/**
* The AssocDecoder / Parser reads from a plain stream and emits assoc data arrays for each CSV record
*/
class AssocDecoder extends EventEmitter implements ReadableStreamInterface
{
private $input;
private $expected;
private $headers = array();
private $closed = false;
/**
* @param ReadableStreamInterface $input
* @param string $delimiter
* @param string $enclosure
* @param string $escapeChar
* @param int $maxlength
*/
public function __construct(ReadableStreamInterface $input, $delimiter = ',', $enclosure = '"', $escapeChar = '\\', $maxlength = 65536)
{
$this->input = new Decoder($input, $delimiter, $enclosure, $escapeChar, $maxlength);
if (!$input->isReadable()) {
$this->close();
return;
}
$this->input->on('data', array($this, 'handleData'));
$this->input->on('end', array($this, 'handleEnd'));
$this->input->on('error', array($this, 'handleError'));
$this->input->on('close', array($this, 'close'));
}
public function isReadable()
{
return !$this->closed;
}
public function close()
{
if ($this->closed) {
return;
}
$this->closed = true;
$this->input->close();
$this->emit('close');
$this->removeAllListeners();
}
public function pause()
{
$this->input->pause();
}
public function resume()
{
$this->input->resume();
}
public function pipe(WritableStreamInterface $dest, array $options = array())
{
Util::pipe($this, $dest, $options);
return $dest;
}
/** @internal */
public function handleData($data)
{
if ($this->expected === null) {
$this->headers = $data;
$this->expected = \count($data);
$this->emit('headers', array($data));
} else {
if (\count($data) !== $this->expected) {
$this->handleError(new \UnexpectedValueException(
'Expected record with ' . $this->expected . ' columns, but got ' . \count($data) . ' instead')
);
return;
}
$this->emit('data', array(
\array_combine($this->headers, $data)
));
}
}
/** @internal */
public function handleEnd()
{
if ($this->headers === array()) {
$this->handleError(new \UnderflowException('Stream ended without headers'));
}
if (!$this->closed) {
$this->emit('end');
$this->close();
}
}
/** @internal */
public function handleError(\Exception $error)
{
$this->emit('error', array($error));
$this->close();
}
}