Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/EventStreamResponse.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation;
13
14 /**
15 * Represents a streaming HTTP response for sending server events
16 * as part of the Server-Sent Events (SSE) streaming technique.
17 *
18 * To broadcast events to multiple users at once, for long-running
19 * connections and for high-traffic websites, prefer using the Mercure
20 * Symfony Component, which relies on Software designed for these use
21 * cases: https://symfony.com/doc/current/mercure.html
22 *
23 * @see ServerEvent
24 *
25 * @author Yonel Ceruto <[email protected]>
26 *
27 * Example usage:
28 *
29 * return new EventStreamResponse(function () {
30 * yield new ServerEvent(time());
31 *
32 * sleep(1);
33 *
34 * yield new ServerEvent(time());
35 * });
36 */
37 class EventStreamResponse extends StreamedResponse
38 {
39 /**
40 * @param int|null $retry The number of milliseconds the client should wait
41 * before reconnecting in case of network failure
42 */
43 public function __construct(?callable $callback = null, int $status = 200, array $headers = [], private ?int $retry = null)
44 {
45 $headers += [
46 'Connection' => 'keep-alive',
47 'Content-Type' => 'text/event-stream',
48 'Cache-Control' => 'private, no-cache, no-store, must-revalidate, max-age=0',
49 'X-Accel-Buffering' => 'no',
50 'Pragma' => 'no-cache',
51 'Expires' => '0',
52 ];
53
54 parent::__construct($callback, $status, $headers);
55 }
56
57 public function setCallback(callable $callback): static
58 {
59 if ($this->callback) {
60 return parent::setCallback($callback);
61 }
62
63 $this->callback = function () use ($callback) {
64 if (is_iterable($events = $callback($this))) {
65 foreach ($events as $event) {
66 $this->sendEvent($event);
67
68 if (connection_aborted()) {
69 break;
70 }
71 }
72 }
73 };
74
75 return $this;
76 }
77
78 /**
79 * Sends a server event to the client.
80 *
81 * @return $this
82 */
83 public function sendEvent(ServerEvent $event): static
84 {
85 if ($this->retry > 0 && !$event->getRetry()) {
86 $event->setRetry($this->retry);
87 }
88
89 foreach ($event as $part) {
90 echo $part;
91
92 if (!\in_array(\PHP_SAPI, ['cli', 'phpdbg', 'embed'], true)) {
93 static::closeOutputBuffers(0, true);
94 flush();
95 }
96 }
97
98 return $this;
99 }
100
101 public function getRetry(): ?int
102 {
103 return $this->retry;
104 }
105
106 public function setRetry(int $retry): void
107 {
108 $this->retry = $retry;
109 }
110 }