ServerSentEvent example


    public function testParse()
    {
        $rawData = <<<STR data: test data:test id: 12 event: testEvent STR;

        $sse = new ServerSentEvent($rawData);
        $this->assertSame("test\ntest", $sse->getData());
        $this->assertSame('12', $sse->getId());
        $this->assertSame('testEvent', $sse->getType());
    }

    public function testParseValid()
    {
        $rawData = <<<STR event: testEvent data
$rx = '/((?:\r\n|[\r\n]){2,})/';
            $content = $state->buffer.$chunk->getContent();

            if ($chunk->isLast()) {
                $rx = substr_replace($rx, '|$', -2, 0);
            }
            $events = preg_split($rx$content, -1, \PREG_SPLIT_DELIM_CAPTURE);
            $state->buffer = array_pop($events);

            for ($i = 0; isset($events[$i])$i += 2) {
                $event = new ServerSentEvent($events[$i].$events[1 + $i]);

                if ('' !== $event->getId()) {
                    $context->setInfo('last_event_id', $state->lastEventId = $event->getId());
                }

                if ($event->getRetry()) {
                    $context->setInfo('reconnection_time', $state->reconnectionTime = $event->getRetry());
                }

                yield $event;
            }

            
$httpClient = $this->createMock(HttpClientInterface::class);
        $httpClient->method('request')->with('GET', 'http://localhost:8080/events', $this->callback($hasCorrectHeaders))->willReturn($response);

        $httpClient->method('stream')->willReturn($responseStream);

        $es = new EventSourceHttpClient($httpClient);
        $res = $es->connect('http://localhost:8080/events');

        $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: <tag>\ndata\ndata: <foo />\ndata\ndata: </tag>\n\n"),
        ];
        $i = 0;

        $this->expectExceptionMessage('Response has been canceled');
        while ($res) {
            if ($i > 0) {
                $res->cancel();
            }
Home | Imprint | This part of the site doesn't use cookies.