1: <?php
2:
3: /*
4: * This file is part of the Symfony package.
5: *
6: * (c) Fabien Potencier <fabien@symfony.com>
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: * StreamedResponse represents a streamed HTTP response.
16: *
17: * A StreamedResponse uses a callback for its content.
18: *
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.
22: *
23: * @see flush()
24: *
25: * @author Fabien Potencier <fabien@symfony.com>
26: *
27: * @api
28: */
29: class StreamedResponse extends Response
30: {
31: protected $callback;
32: protected $streamed;
33:
34: /**
35: * Constructor.
36: *
37: * @param callable|null $callback A valid PHP callback or null to set it later
38: * @param int $status The response status code
39: * @param array $headers An array of response headers
40: *
41: * @api
42: */
43: public function __construct($callback = null, $status = 200, $headers = array())
44: {
45: parent::__construct(null, $status, $headers);
46:
47: if (null !== $callback) {
48: $this->setCallback($callback);
49: }
50: $this->streamed = false;
51: }
52:
53: /**
54: * Factory method for chainability
55: *
56: * @param callable|null $callback A valid PHP callback or null to set it later
57: * @param int $status The response status code
58: * @param array $headers An array of response headers
59: *
60: * @return StreamedResponse
61: */
62: public static function create($callback = null, $status = 200, $headers = array())
63: {
64: return new static($callback, $status, $headers);
65: }
66:
67: /**
68: * Sets the PHP callback associated with this Response.
69: *
70: * @param callable $callback A valid PHP callback
71: *
72: * @throws \LogicException
73: */
74: public function setCallback($callback)
75: {
76: if (!is_callable($callback)) {
77: throw new \LogicException('The Response callback must be a valid PHP callable.');
78: }
79: $this->callback = $callback;
80: }
81:
82: /**
83: * {@inheritdoc}
84: *
85: * This method only sends the content once.
86: */
87: public function sendContent()
88: {
89: if ($this->streamed) {
90: return;
91: }
92:
93: $this->streamed = true;
94:
95: if (null === $this->callback) {
96: throw new \LogicException('The Response callback must not be null.');
97: }
98:
99: call_user_func($this->callback);
100: }
101:
102: /**
103: * {@inheritdoc}
104: *
105: * @throws \LogicException when the content is not null
106: */
107: public function setContent($content)
108: {
109: if (null !== $content) {
110: throw new \LogicException('The content cannot be set on a StreamedResponse instance.');
111: }
112: }
113:
114: /**
115: * {@inheritdoc}
116: *
117: * @return false
118: */
119: public function getContent()
120: {
121: return false;
122: }
123: }
124: