14
14
/**
15
15
* StreamedResponse represents a streamed HTTP response.
16
16
*
17
- * A StreamedResponse uses a callback for its content.
17
+ * A StreamedResponse uses a callback or an iterable of strings for its content.
18
18
*
19
19
* The callback should use the standard PHP functions like echo
20
20
* to stream the response back to the client. The flush() function
@@ -32,19 +32,36 @@ class StreamedResponse extends Response
32
32
private bool $ headersSent = false ;
33
33
34
34
/**
35
- * @param int $status The HTTP status code (200 "OK" by default)
35
+ * @param callable|iterable<string>|null $callbackOrChunks
36
+ * @param int $status The HTTP status code (200 "OK" by default)
36
37
*/
37
- public function __construct (? callable $ callback = null , int $ status = 200 , array $ headers = [])
38
+ public function __construct (callable | iterable | null $ callbackOrChunks = null , int $ status = 200 , array $ headers = [])
38
39
{
39
40
parent ::__construct (null , $ status , $ headers );
40
41
41
- if (null !== $ callback ) {
42
- $ this ->setCallback ($ callback );
42
+ if (\is_callable ($ callbackOrChunks )) {
43
+ $ this ->setCallback ($ callbackOrChunks );
44
+ } elseif (null !== $ callbackOrChunks ) {
45
+ $ this ->setChunks ($ callbackOrChunks );
43
46
}
44
47
$ this ->streamed = false ;
45
48
$ this ->headersSent = false ;
46
49
}
47
50
51
+ /**
52
+ * @param iterable<string> $chunks
53
+ */
54
+ public function setChunks (iterable $ chunks ): static
55
+ {
56
+ $ this ->callback = static function () use ($ chunks ): void {
57
+ foreach ($ chunks as $ chunk ) {
58
+ echo $ chunk ;
59
+ }
60
+ };
61
+
62
+ return $ this ;
63
+ }
64
+
48
65
/**
49
66
* Sets the PHP callback associated with this Response.
50
67
*
0 commit comments