Skip to content

Commit

Permalink
added the possibility to change a StreamedResponse callback after its…
Browse files Browse the repository at this point in the history
… creation
  • Loading branch information
fabpot committed Dec 22, 2011
1 parent 8717d44 commit 473741b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
20 changes: 14 additions & 6 deletions src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php
Expand Up @@ -102,19 +102,27 @@ public function render($view, array $parameters = array(), Response $response =
/**
* 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;
}

/**
Expand Down
21 changes: 18 additions & 3 deletions src/Symfony/Component/HttpFoundation/StreamedResponse.php
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -80,6 +91,10 @@ public function sendContent()

$this->streamed = true;

if (null === $this->callback) {
throw new \LogicException('The Response callback must not be null.');
}

call_user_func($this->callback);
}

Expand Down

0 comments on commit 473741b

Please sign in to comment.