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\HttpKernel\Fragment;
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\Response;
16 use Symfony\Component\HttpKernel\Controller\ControllerReference;
17 use Symfony\Component\HttpKernel\HttpCache\SurrogateInterface;
18 use Symfony\Component\HttpKernel\UriSigner;
21 * Implements Surrogate rendering strategy.
23 * @author Fabien Potencier <fabien@symfony.com>
25 abstract class AbstractSurrogateFragmentRenderer extends RoutableFragmentRenderer
28 private $inlineStrategy;
34 * The "fallback" strategy when surrogate is not available should always be an
35 * instance of InlineFragmentRenderer.
37 * @param SurrogateInterface $surrogate An Surrogate instance
38 * @param FragmentRendererInterface $inlineStrategy The inline strategy to use when the surrogate is not supported
39 * @param UriSigner $signer
41 public function __construct(SurrogateInterface $surrogate = null, FragmentRendererInterface $inlineStrategy, UriSigner $signer = null)
43 $this->surrogate = $surrogate;
44 $this->inlineStrategy = $inlineStrategy;
45 $this->signer = $signer;
51 * Note that if the current Request has no surrogate capability, this method
52 * falls back to use the inline rendering strategy.
54 * Additional available options:
56 * * alt: an alternative URI to render in case of an error
57 * * comment: a comment to add when returning the surrogate tag
59 * Note, that not all surrogate strategies support all options. For now
60 * 'alt' and 'comment' are only supported by ESI.
62 * @see Symfony\Component\HttpKernel\HttpCache\SurrogateInterface
64 public function render($uri, Request $request, array $options = array())
66 if (!$this->surrogate || !$this->surrogate->hasSurrogateCapability($request)) {
67 return $this->inlineStrategy->render($uri, $request, $options);
70 if ($uri instanceof ControllerReference) {
71 $uri = $this->generateSignedFragmentUri($uri, $request);
74 $alt = isset($options['alt']) ? $options['alt'] : null;
75 if ($alt instanceof ControllerReference) {
76 $alt = $this->generateSignedFragmentUri($alt, $request);
79 $tag = $this->surrogate->renderIncludeTag($uri, $alt, isset($options['ignore_errors']) ? $options['ignore_errors'] : false, isset($options['comment']) ? $options['comment'] : '');
81 return new Response($tag);
84 private function generateSignedFragmentUri($uri, Request $request)
86 if (null === $this->signer) {
87 throw new \LogicException('You must use a URI when using the ESI rendering strategy or set a URL signer.');
90 // we need to sign the absolute URI, but want to return the path only.
91 $fragmentUri = $this->signer->sign($this->generateFragmentUri($uri, $request, true));
93 return substr($fragmentUri, strlen($request->getSchemeAndHttpHost()));