Skip to content

Commit 92d4f52

Browse files
authored
Merge pull request #112 from clue-labs/empty-write
Ignore empty writes to not mess up chunked transfer encoding
2 parents 846a32d + 4734b05 commit 92d4f52

2 files changed

Lines changed: 36 additions & 5 deletions

File tree

src/Response.php

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -201,15 +201,19 @@ public function write($data)
201201
throw new \Exception('Response head has not yet been written.');
202202
}
203203

204+
// prefix with chunk length for chunked transfer encoding
204205
if ($this->chunkedEncoding) {
205206
$len = strlen($data);
206-
$chunk = dechex($len)."\r\n".$data."\r\n";
207-
$flushed = $this->conn->write($chunk);
208-
} else {
209-
$flushed = $this->conn->write($data);
207+
208+
// skip empty chunks
209+
if ($len === 0) {
210+
return true;
211+
}
212+
213+
$data = dechex($len) . "\r\n" . $data . "\r\n";
210214
}
211215

212-
return $flushed;
216+
return $this->conn->write($data);
213217
}
214218

215219
public function end($data = null)

tests/ResponseTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,33 @@ public function testResponseBodyShouldBeChunkedCorrectly()
149149
$response->end();
150150
}
151151

152+
public function testResponseBodyShouldSkipEmptyChunks()
153+
{
154+
$conn = $this
155+
->getMockBuilder('React\Socket\ConnectionInterface')
156+
->getMock();
157+
$conn
158+
->expects($this->at(4))
159+
->method('write')
160+
->with("5\r\nHello\r\n");
161+
$conn
162+
->expects($this->at(5))
163+
->method('write')
164+
->with("5\r\nWorld\r\n");
165+
$conn
166+
->expects($this->at(6))
167+
->method('write')
168+
->with("0\r\n\r\n");
169+
170+
$response = new Response($conn);
171+
$response->writeHead();
172+
173+
$response->write('Hello');
174+
$response->write('');
175+
$response->write('World');
176+
$response->end();
177+
}
178+
152179
public function testResponseShouldEmitEndOnStreamEnd()
153180
{
154181
$ended = false;

0 commit comments

Comments
 (0)