|
8 | 8 | use React\Stream\Util;
|
9 | 9 |
|
10 | 10 | /**
|
11 |
| - * Read the stream line wise. This class is a duplex stream so a writeable and readable |
12 |
| - * stream at the same time |
| 11 | + * Read the stream line wise. This class is a duplex stream so a writeable and readable |
| 12 | + * stream at the same time |
13 | 13 | */
|
14 | 14 | class LineReader extends EventEmitter implements ReadableStreamInterface, WritableStreamInterface
|
15 | 15 | {
|
16 | 16 | private $closed = false;
|
17 | 17 | private $buffer = '';
|
18 |
| - |
| 18 | + private $eol; |
| 19 | + |
19 | 20 | /**
|
20 |
| - * Reads the incomg data until the new line delimiter occures, |
21 |
| - * if there is no delimiter in the chunk the data will be buffered until |
| 21 | + * @param string $eol - delimiter that defines the end of line |
| 22 | + */ |
| 23 | + public function __construct($eol = PHP_EOL) |
| 24 | + { |
| 25 | + $this->eol = $eol; |
| 26 | + } |
| 27 | + |
| 28 | + /** |
| 29 | + * Reads the incomg data until the new line delimiter occures, |
| 30 | + * if there is no delimiter in the chunk the data will be buffered until |
22 | 31 | * the next data chunk comes in
|
23 | 32 | *
|
24 | 33 | * @param string $chunk - string entered by the input stream
|
25 | 34 | */
|
26 | 35 | public function write($chunk)
|
27 | 36 | {
|
28 |
| - for ($i = 0; $i < strlen($chunk); $i++) { |
29 |
| - $this->buffer .= $chunk[$i]; |
30 |
| - |
31 |
| - if ($chunk[$i] == PHP_EOL) { |
32 |
| - $this->emit('data', array($this->buffer)); |
33 |
| - $this->buffer = ''; |
| 37 | + $this->buffer .= $chunk; |
| 38 | + while ($this->buffer !== "") { |
| 39 | + $position = strpos($this->buffer, $this->eol); |
| 40 | + |
| 41 | + if ($position === false) { |
| 42 | + return; |
34 | 43 | }
|
| 44 | + |
| 45 | + $data = substr($this->buffer, 0, $position + strlen($this->eol)); |
| 46 | + $this->emit('data', array($data)); |
| 47 | + $this->buffer = substr($this->buffer, $position + strlen($this->eol)); |
35 | 48 | }
|
36 | 49 | }
|
37 | 50 |
|
@@ -74,7 +87,7 @@ public function close()
|
74 | 87 | $this->emit('close');
|
75 | 88 | $this->removeAllListeners();
|
76 | 89 | }
|
77 |
| - |
| 90 | + |
78 | 91 | public function isWritable()
|
79 | 92 | {
|
80 | 93 | return !$this->closed;
|
|
0 commit comments