1111
1212namespace Spiral \RoadRunner \Http ;
1313
14+ use Generator ;
1415use Spiral \RoadRunner \Payload ;
1516use Spiral \RoadRunner \WorkerInterface ;
17+ use Stringable ;
1618
1719/**
1820 * @psalm-import-type HeadersList from Request
@@ -83,12 +85,39 @@ public function waitRequest(): ?Request
8385 */
8486 public function respond (int $ status , string $ body , array $ headers = []): void
8587 {
86- $ headers = (string )\json_encode ([
88+ $ head = (string )\json_encode ([
8789 'status ' => $ status ,
8890 'headers ' => $ headers ?: (object )[],
8991 ], \JSON_THROW_ON_ERROR );
9092
91- $ this ->worker ->respond (new Payload ($ body , $ headers ));
93+ $ this ->worker ->respond (new Payload ($ body , $ head ));
94+ }
95+
96+ /**
97+ * Respond data using Streamed Output
98+ *
99+ * @param Generator<mixed, scalar|Stringable, mixed, Stringable|scalar|null> $body Body generator.
100+ * Each yielded value will be sent as a separated stream chunk.
101+ * Returned value will be sent as a last stream package.
102+ */
103+ public function respondStream (int $ status , Generator $ body , array $ headers = []): void
104+ {
105+ $ head = (string )\json_encode ([
106+ 'status ' => $ status ,
107+ 'headers ' => $ headers ?: (object )[],
108+ ], \JSON_THROW_ON_ERROR );
109+
110+ do {
111+ if (!$ body ->valid ()) {
112+ $ content = (string )$ body ->getReturn ();
113+ $ this ->worker ->respond (new Payload ($ content , $ head , true ));
114+ break ;
115+ }
116+ $ content = (string )$ body ->current ();
117+ $ this ->worker ->respond (new Payload ($ content , $ head , false ));
118+ $ body ->next ();
119+ $ head = null ;
120+ } while (true );
92121 }
93122
94123 /**
@@ -131,7 +160,7 @@ private function hydrateRequest(Request $request, array $context): void
131160 }
132161
133162 /**
134- * @param array<mixed, mixed> $headers
163+ * Remove all non-string and empty-string keys
135164 *
136165 * @return array<string, mixed>
137166 */
@@ -144,7 +173,7 @@ private function filterHeaders(array $headers): array
144173 unset($ headers [$ key ]);
145174 }
146175 }
147-
176+ /** @var array<string, mixed> $headers */
148177 return $ headers ;
149178 }
150179}
0 commit comments