From 2c095d8296c273b1799b43d5e222a92bd30310c7 Mon Sep 17 00:00:00 2001 From: Thomas Calvet Date: Mon, 11 Mar 2024 18:57:08 +0100 Subject: [PATCH] [HttpClient][EventSourceHttpClient] Fix consuming SSEs with \r\n separator --- .../HttpClient/EventSourceHttpClient.php | 2 +- .../Tests/EventSourceHttpClientTest.php | 21 ++++++++++++------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/Symfony/Component/HttpClient/EventSourceHttpClient.php b/src/Symfony/Component/HttpClient/EventSourceHttpClient.php index e801c1c4f39c7..89d12e87764fa 100644 --- a/src/Symfony/Component/HttpClient/EventSourceHttpClient.php +++ b/src/Symfony/Component/HttpClient/EventSourceHttpClient.php @@ -121,7 +121,7 @@ public function request(string $method, string $url, array $options = []): Respo return; } - $rx = '/((?:\r\n|[\r\n]){2,})/'; + $rx = '/((?:\r\n){2,}|\r{2,}|\n{2,})/'; $content = $state->buffer.$chunk->getContent(); if ($chunk->isLast()) { diff --git a/src/Symfony/Component/HttpClient/Tests/EventSourceHttpClientTest.php b/src/Symfony/Component/HttpClient/Tests/EventSourceHttpClientTest.php index 72eb74fb9f289..36c9d655f63c7 100644 --- a/src/Symfony/Component/HttpClient/Tests/EventSourceHttpClientTest.php +++ b/src/Symfony/Component/HttpClient/Tests/EventSourceHttpClientTest.php @@ -27,9 +27,14 @@ */ class EventSourceHttpClientTest extends TestCase { - public function testGetServerSentEvents() + /** + * @testWith ["\n"] + * ["\r"] + * ["\r\n"] + */ + public function testGetServerSentEvents(string $sep) { - $data = << false, 'http_method' => 'GET', 'url' => 'http://localhost:8080/events', 'response_headers' => ['content-type: text/event-stream']]); @@ -83,11 +88,11 @@ public function testGetServerSentEvents() $expected = [ new FirstChunk(), - new ServerSentEvent("event: builderror\nid: 46\ndata: {\"foo\": \"bar\"}\n\n"), - new ServerSentEvent("event: reload\nid: 47\ndata: {}\n\n"), - new ServerSentEvent("event: reload\nid: 48\ndata: {}\n\n"), - new ServerSentEvent("data: test\ndata:test\nid: 49\nevent: testEvent\n\n\n"), - new ServerSentEvent("id: 50\ndata: \ndata\ndata: \ndata\ndata: \n\n"), + new ServerSentEvent(str_replace("\n", $sep, "event: builderror\nid: 46\ndata: {\"foo\": \"bar\"}\n\n")), + new ServerSentEvent(str_replace("\n", $sep, "event: reload\nid: 47\ndata: {}\n\n")), + new ServerSentEvent(str_replace("\n", $sep, "event: reload\nid: 48\ndata: {}\n\n")), + new ServerSentEvent(str_replace("\n", $sep, "data: test\ndata:test\nid: 49\nevent: testEvent\n\n\n")), + new ServerSentEvent(str_replace("\n", $sep, "id: 50\ndata: \ndata\ndata: \ndata\ndata: \n\n")), ]; $i = 0;