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\HttpCache;
14 use Symfony\Component\HttpFoundation\Request;
15 use Symfony\Component\HttpFoundation\Response;
18 * Esi implements the ESI capabilities to Request and Response instances.
20 * For more information, read the following W3C notes:
22 * * ESI Language Specification 1.0 (http://www.w3.org/TR/esi-lang)
24 * * Edge Architecture Specification (http://www.w3.org/TR/edge-arch)
26 * @author Fabien Potencier <fabien@symfony.com>
28 class Esi extends AbstractSurrogate
30 public function getName()
38 public function addSurrogateControl(Response $response)
40 if (false !== strpos($response->getContent(), '<esi:include')) {
41 $response->headers->set('Surrogate-Control', 'content="ESI/1.0"');
48 public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '')
50 $html = sprintf('<esi:include src="%s"%s%s />',
52 $ignoreErrors ? ' onerror="continue"' : '',
53 $alt ? sprintf(' alt="%s"', $alt) : ''
56 if (!empty($comment)) {
57 return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html);
66 public function process(Request $request, Response $response)
68 $type = $response->headers->get('Content-Type');
73 $parts = explode(';', $type);
74 if (!in_array($parts[0], $this->contentTypes)) {
78 // we don't use a proper XML parser here as we can have ESI tags in a plain text response
79 $content = $response->getContent();
80 $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content);
81 $content = preg_replace('#<esi\:comment[^>]+>#s', '', $content);
83 $chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE);
84 $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]);
87 while (isset($chunks[$i])) {
89 preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER);
90 foreach ($matches as $set) {
91 $options[$set[1]] = $set[2];
94 if (!isset($options['src'])) {
95 throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.');
98 $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n",
99 var_export($options['src'], true),
100 var_export(isset($options['alt']) ? $options['alt'] : '', true),
101 isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false'
104 $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]);
107 $content = implode('', $chunks);
109 $response->setContent($content);
110 $response->headers->set('X-Body-Eval', 'ESI');
112 // remove ESI/1.0 from the Surrogate-Control header
113 $this->removeFromControl($response);