4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\HttpFoundation;
15 * StreamedResponse represents a streamed HTTP response.
17 * A StreamedResponse uses a callback for its content.
19 * The callback should use the standard PHP functions like echo
20 * to stream the response back to the client. The flush() method
21 * can also be used if needed.
25 * @author Fabien Potencier <fabien@symfony.com>
27 class StreamedResponse extends Response
36 * @param callable|null $callback A valid PHP callback or null to set it later
37 * @param int $status The response status code
38 * @param array $headers An array of response headers
40 public function __construct($callback = null, $status = 200, $headers = array())
42 parent::__construct(null, $status, $headers);
44 if (null !== $callback) {
45 $this->setCallback($callback);
47 $this->streamed = false;
48 $this->headersSent = false;
52 * Factory method for chainability.
54 * @param callable|null $callback A valid PHP callback or null to set it later
55 * @param int $status The response status code
56 * @param array $headers An array of response headers
60 public static function create($callback = null, $status = 200, $headers = array())
62 return new static($callback, $status, $headers);
66 * Sets the PHP callback associated with this Response.
68 * @param callable $callback A valid PHP callback
70 * @throws \LogicException
72 public function setCallback($callback)
74 if (!is_callable($callback)) {
75 throw new \LogicException('The Response callback must be a valid PHP callable.');
77 $this->callback = $callback;
83 * This method only sends the headers once.
85 public function sendHeaders()
87 if ($this->headersSent) {
91 $this->headersSent = true;
93 parent::sendHeaders();
99 * This method only sends the content once.
101 public function sendContent()
103 if ($this->streamed) {
107 $this->streamed = true;
109 if (null === $this->callback) {
110 throw new \LogicException('The Response callback must not be null.');
113 call_user_func($this->callback);
119 * @throws \LogicException when the content is not null
121 public function setContent($content)
123 if (null !== $content) {
124 throw new \LogicException('The content cannot be set on a StreamedResponse instance.');
133 public function getContent()