added the possibility to change a StreamedResponse callback after its creation

This commit is contained in:
Fabien Potencier 2011-12-22 07:40:06 +01:00
parent 8717d4425e
commit 473741b9db
2 changed files with 32 additions and 9 deletions

View File

@ -102,19 +102,27 @@ class Controller extends ContainerAware
/**
* Streams a view.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @param Response $response A response instance
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @param StreamedResponse $response A response instance
*
* @return StreamedResponse A StreamedResponse instance
*/
public function stream($view, array $parameters = array(), Response $response = null)
public function stream($view, array $parameters = array(), StreamedResponse $response = null)
{
$templating = $this->container->get('templating');
return new StreamedResponse(function () use ($templating, $view, $parameters) {
$callback = function () use ($templating, $view, $parameters) {
$templating->stream($view, $parameters);
}, null === $response ? 200 : $response->getStatusCode(), null === $response ? array() : $response->headers->all());
};
if (null === $response) {
return new StreamedResponse($callback);
}
$response->setCallback($callback);
return $response;
}
/**

View File

@ -40,16 +40,27 @@ class StreamedResponse extends Response
*
* @api
*/
public function __construct($callback, $status = 200, $headers = array())
public function __construct($callback = null, $status = 200, $headers = array())
{
parent::__construct(null, $status, $headers);
if (null !== $callback) {
$this->setCallback($callback);
}
$this->streamed = false;
}
/**
* Sets the PHP callback associated with this Response.
*
* @param mixed $callback A valid PHP callback
*/
public function setCallback($callback)
{
$this->callback = $callback;
if (!is_callable($this->callback)) {
throw new \LogicException('The Response callback must be a valid PHP callable.');
}
$this->streamed = false;
}
/**
@ -80,6 +91,10 @@ class StreamedResponse extends Response
$this->streamed = true;
if (null === $this->callback) {
throw new \LogicException('The Response callback must not be null.');
}
call_user_func($this->callback);
}