This repository has been archived on 2023-08-20. You can view files and clone it, but cannot push or open issues or pull requests.
symfony/src/Symfony/Bundle/TwigBundle/TwigEngine.php
Fabien Potencier 0038d1bac4 [HttpFoundation] added support for streamed responses
To stream a Response, use the StreamedResponse class instead of the
standard Response class:

    $response = new StreamedResponse(function () {
        echo 'FOO';
    });

    $response = new StreamedResponse(function () {
        echo 'FOO';
    }, 200, array('Content-Type' => 'text/plain'));

As you can see, a StreamedResponse instance takes a PHP callback instead of
a string for the Response content. It's up to the developer to stream the
response content from the callback with standard PHP functions like echo.
You can also use flush() if needed.

From a controller, do something like this:

    $twig = $this->get('templating');

    return new StreamedResponse(function () use ($templating) {
        $templating->stream('BlogBundle:Annot:streamed.html.twig');
    }, 200, array('Content-Type' => 'text/html'));

If you are using the base controller, you can use the stream() method instead:

    return $this->stream('BlogBundle:Annot:streamed.html.twig');

You can stream an existing file by using the PHP built-in readfile() function:

    new StreamedResponse(function () use ($file) {
        readfile($file);
    }, 200, array('Content-Type' => 'image/png');

Read http://php.net/flush for more information about output buffering in PHP.

Note that you should do your best to move all expensive operations to
be "activated/evaluated/called" during template evaluation.

Templates
---------

If you are using Twig as a template engine, everything should work as
usual, even if are using template inheritance!

However, note that streaming is not supported for PHP templates. Support
is impossible by design (as the layout is rendered after the main content).

Exceptions
----------

Exceptions thrown during rendering will be rendered as usual except that
some content might have been rendered already.

Limitations
-----------

As the getContent() method always returns false for streamed Responses, some
event listeners won't work at all:

* Web debug toolbar is not available for such Responses (but the profiler works fine);
* ESI is not supported.

Also note that streamed responses cannot benefit from HTTP caching for obvious
reasons.
2011-12-21 14:34:26 +01:00

169 lines
4.9 KiB
PHP

<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\TwigBundle;
use Symfony\Bundle\FrameworkBundle\Templating\EngineInterface;
use Symfony\Bundle\FrameworkBundle\Templating\GlobalVariables;
use Symfony\Bundle\FrameworkBundle\Templating\TemplateReference;
use Symfony\Component\Templating\TemplateNameParserInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Config\FileLocatorInterface;
/**
* This engine knows how to render Twig templates.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class TwigEngine implements EngineInterface
{
protected $environment;
protected $parser;
protected $locator;
/**
* Constructor.
*
* @param \Twig_Environment $environment A \Twig_Environment instance
* @param TemplateNameParserInterface $parser A TemplateNameParserInterface instance
* @param GlobalVariables|null $globals A GlobalVariables instance or null
*/
public function __construct(\Twig_Environment $environment, TemplateNameParserInterface $parser, FileLocatorInterface $locator, GlobalVariables $globals = null)
{
$this->environment = $environment;
$this->parser = $parser;
$this->locator = $locator;
if (null !== $globals) {
$environment->addGlobal('app', $globals);
}
}
/**
* Renders a template.
*
* @param mixed $name A template name
* @param array $parameters An array of parameters to pass to the template
*
* @return string The evaluated template as a string
*
* @throws \InvalidArgumentException if the template does not exist
* @throws \RuntimeException if the template cannot be rendered
*/
public function render($name, array $parameters = array())
{
try {
return $this->load($name)->render($parameters);
} catch (\Twig_Error $e) {
if ($name instanceof TemplateReference) {
try {
// try to get the real file name of the template where the error occurred
$e->setTemplateFile(sprintf('%s', $this->locator->locate($this->parser->parse($e->getTemplateFile()))));
} catch (\Exception $ex) {
}
}
throw $e;
}
}
/**
* Streams a template.
*
* @param mixed $name A template name or a TemplateReferenceInterface instance
* @param array $parameters An array of parameters to pass to the template
*
* @throws \RuntimeException if the template cannot be rendered
*/
public function stream($name, array $parameters = array())
{
$this->load($name)->display($parameters);
}
/**
* Returns true if the template exists.
*
* @param mixed $name A template name
*
* @return Boolean true if the template exists, false otherwise
*/
public function exists($name)
{
try {
$this->load($name);
} catch (\InvalidArgumentException $e) {
return false;
}
return true;
}
/**
* Returns true if this class is able to render the given template.
*
* @param string $name A template name
*
* @return Boolean True if this class supports the given resource, false otherwise
*/
public function supports($name)
{
if ($name instanceof \Twig_Template) {
return true;
}
$template = $this->parser->parse($name);
return 'twig' === $template->get('engine');
}
/**
* Renders a view and returns a Response.
*
* @param string $view The view name
* @param array $parameters An array of parameters to pass to the view
* @param Response $response A Response instance
*
* @return Response A Response instance
*/
public function renderResponse($view, array $parameters = array(), Response $response = null)
{
if (null === $response) {
$response = new Response();
}
$response->setContent($this->render($view, $parameters));
return $response;
}
/**
* Loads the given template.
*
* @param mixed $name A template name or an instance of Twig_Template
*
* @return \Twig_TemplateInterface A \Twig_TemplateInterface instance
*
* @throws \InvalidArgumentException if the template does not exist
*/
protected function load($name)
{
if ($name instanceof \Twig_Template) {
return $name;
}
try {
return $this->environment->loadTemplate($name);
} catch (\Twig_Error_Loader $e) {
throw new \InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
}