Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions src/Server.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,14 @@ public function handleConnection(ConnectionInterface $conn)
});

$conn->on('data', $listener);
$parser->on('error', function() use ($conn, $listener, $that) {
// TODO: return 400 response
$parser->on('error', function(\Exception $e) use ($conn, $listener, $that) {
$conn->removeListener('data', $listener);
$that->emit('error', func_get_args());
$that->emit('error', array($e));

$that->writeError(
$conn,
400
);
});
}

Expand Down Expand Up @@ -123,4 +127,20 @@ public function handleRequest(ConnectionInterface $conn, Request $request)

$this->emit('request', array($request, $response));
}

/** @internal */
public function writeError(ConnectionInterface $conn, $code)
{
$message = 'Error ' . $code;
if (isset(ResponseCodes::$statusTexts[$code])) {
$message .= ': ' . ResponseCodes::$statusTexts[$code];
}

$response = new Response($conn);
$response->writeHead($code, array(
'Content-Length' => strlen($message),
'Content-Type' => 'text/plain'
));
$response->end($message);
}
}
34 changes: 32 additions & 2 deletions tests/ServerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,6 @@ public function testParserErrorEmitted()
{
$error = null;
$server = new Server($this->socket);
$server->on('headers', $this->expectCallableNever());
$server->on('error', function ($message) use (&$error) {
$error = $message;
});
Expand All @@ -218,7 +217,38 @@ public function testParserErrorEmitted()
$this->connection->emit('data', array($data));

$this->assertInstanceOf('OverflowException', $error);
$this->connection->expects($this->never())->method('write');
}

public function testRequestInvalidWillEmitErrorAndSendErrorResponse()
{
$error = null;
$server = new Server($this->socket);
$server->on('error', function ($message) use (&$error) {
$error = $message;
});

$buffer = '';

$this->connection
->expects($this->any())
->method('write')
->will(
$this->returnCallback(
function ($data) use (&$buffer) {
$buffer .= $data;
}
)
);

$this->socket->emit('connection', array($this->connection));

$data = "bad request\r\n\r\n";
$this->connection->emit('data', array($data));

$this->assertInstanceOf('InvalidArgumentException', $error);

$this->assertContains("HTTP/1.1 400 Bad Request\r\n", $buffer);
$this->assertContains("\r\n\r\nError 400: Bad Request", $buffer);
}

private function createGetRequest()
Expand Down