관리-도구
편집 파일: HttpCache.tar
AbstractSurrogate.php 0000604 00000010620 15224665251 0010717 0 ustar 00 <?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\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; /** * Abstract class implementing Surrogate capabilities to Request and Response instances. * * @author Fabien Potencier <fabien@symfony.com> * @author Robin Chalas <robin.chalas@gmail.com> */ abstract class AbstractSurrogate implements SurrogateInterface { protected $contentTypes; protected $phpEscapeMap = array( array('<?', '<%', '<s', '<S'), array('<?php echo "<?"; ?>', '<?php echo "<%"; ?>', '<?php echo "<s"; ?>', '<?php echo "<S"; ?>'), ); /** * Constructor. * * @param array $contentTypes An array of content-type that should be parsed for Surrogate information * (default: text/html, text/xml, application/xhtml+xml, and application/xml) */ public function __construct(array $contentTypes = array('text/html', 'text/xml', 'application/xhtml+xml', 'application/xml')) { $this->contentTypes = $contentTypes; } /** * Returns a new cache strategy instance. * * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance */ public function createCacheStrategy() { return new ResponseCacheStrategy(); } /** * {@inheritdoc} */ public function hasSurrogateCapability(Request $request) { if (null === $value = $request->headers->get('Surrogate-Capability')) { return false; } return false !== strpos($value, sprintf('%s/1.0', strtoupper($this->getName()))); } /** * {@inheritdoc} */ public function addSurrogateCapability(Request $request) { $current = $request->headers->get('Surrogate-Capability'); $new = sprintf('symfony="%s/1.0"', strtoupper($this->getName())); $request->headers->set('Surrogate-Capability', $current ? $current.', '.$new : $new); } /** * {@inheritdoc} */ public function needsParsing(Response $response) { if (!$control = $response->headers->get('Surrogate-Control')) { return false; } $pattern = sprintf('#content="[^"]*%s/1.0[^"]*"#', strtoupper($this->getName())); return (bool) preg_match($pattern, $control); } /** * {@inheritdoc} */ public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors) { $subRequest = Request::create($uri, Request::METHOD_GET, array(), $cache->getRequest()->cookies->all(), array(), $cache->getRequest()->server->all()); try { $response = $cache->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true); if (!$response->isSuccessful()) { throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $subRequest->getUri(), $response->getStatusCode())); } return $response->getContent(); } catch (\Exception $e) { if ($alt) { return $this->handle($cache, $alt, '', $ignoreErrors); } if (!$ignoreErrors) { throw $e; } } } /** * Remove the Surrogate from the Surrogate-Control header. * * @param Response $response */ protected function removeFromControl(Response $response) { if (!$response->headers->has('Surrogate-Control')) { return; } $value = $response->headers->get('Surrogate-Control'); $upperName = strtoupper($this->getName()); if (sprintf('content="%s/1.0"', $upperName) == $value) { $response->headers->remove('Surrogate-Control'); } elseif (preg_match(sprintf('#,\s*content="%s/1.0"#', $upperName), $value)) { $response->headers->set('Surrogate-Control', preg_replace(sprintf('#,\s*content="%s/1.0"#', $upperName), '', $value)); } elseif (preg_match(sprintf('#content="%s/1.0",\s*#', $upperName), $value)) { $response->headers->set('Surrogate-Control', preg_replace(sprintf('#content="%s/1.0",\s*#', $upperName), '', $value)); } } } ResponseCacheStrategyInterface.php 0000604 00000002071 15224665251 0013347 0 ustar 00 <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * This code is partially based on the Rack-Cache library by Ryan Tomayko, * which is released under the MIT license. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Response; /** * ResponseCacheStrategyInterface implementations know how to compute the * Response cache HTTP header based on the different response cache headers. * * @author Fabien Potencier <fabien@symfony.com> */ interface ResponseCacheStrategyInterface { /** * Adds a Response. * * @param Response $response */ public function add(Response $response); /** * Updates the Response HTTP headers based on the embedded Responses. * * @param Response $response */ public function update(Response $response); } Store.php 0000604 00000034230 15224665251 0006357 0 ustar 00 <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * This code is partially based on the Rack-Cache library by Ryan Tomayko, * which is released under the MIT license. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Store implements all the logic for storing cache metadata (Request and Response headers). * * @author Fabien Potencier <fabien@symfony.com> */ class Store implements StoreInterface { protected $root; private $keyCache; private $locks; /** * Constructor. * * @param string $root The path to the cache directory * * @throws \RuntimeException */ public function __construct($root) { $this->root = $root; if (!file_exists($this->root) && !@mkdir($this->root, 0777, true) && !is_dir($this->root)) { throw new \RuntimeException(sprintf('Unable to create the store directory (%s).', $this->root)); } $this->keyCache = new \SplObjectStorage(); $this->locks = array(); } /** * Cleanups storage. */ public function cleanup() { // unlock everything foreach ($this->locks as $lock) { flock($lock, LOCK_UN); fclose($lock); } $this->locks = array(); } /** * Tries to lock the cache for a given Request, without blocking. * * @param Request $request A Request instance * * @return bool|string true if the lock is acquired, the path to the current lock otherwise */ public function lock(Request $request) { $key = $this->getCacheKey($request); if (!isset($this->locks[$key])) { $path = $this->getPath($key); if (!file_exists(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) { return $path; } $h = fopen($path, 'cb'); if (!flock($h, LOCK_EX | LOCK_NB)) { fclose($h); return $path; } $this->locks[$key] = $h; } return true; } /** * Releases the lock for the given Request. * * @param Request $request A Request instance * * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise */ public function unlock(Request $request) { $key = $this->getCacheKey($request); if (isset($this->locks[$key])) { flock($this->locks[$key], LOCK_UN); fclose($this->locks[$key]); unset($this->locks[$key]); return true; } return false; } public function isLocked(Request $request) { $key = $this->getCacheKey($request); if (isset($this->locks[$key])) { return true; // shortcut if lock held by this process } if (!file_exists($path = $this->getPath($key))) { return false; } $h = fopen($path, 'rb'); flock($h, LOCK_EX | LOCK_NB, $wouldBlock); flock($h, LOCK_UN); // release the lock we just acquired fclose($h); return (bool) $wouldBlock; } /** * Locates a cached Response for the Request provided. * * @param Request $request A Request instance * * @return Response|null A Response instance, or null if no cache entry was found */ public function lookup(Request $request) { $key = $this->getCacheKey($request); if (!$entries = $this->getMetadata($key)) { return; } // find a cached entry that matches the request. $match = null; foreach ($entries as $entry) { if ($this->requestsMatch(isset($entry[1]['vary'][0]) ? implode(', ', $entry[1]['vary']) : '', $request->headers->all(), $entry[0])) { $match = $entry; break; } } if (null === $match) { return; } list($req, $headers) = $match; if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) { return $this->restoreResponse($headers, $body); } // TODO the metaStore referenced an entity that doesn't exist in // the entityStore. We definitely want to return nil but we should // also purge the entry from the meta-store when this is detected. } /** * Writes a cache entry to the store for the given Request and Response. * * Existing entries are read and any that match the response are removed. This * method calls write with the new list of cache entries. * * @param Request $request A Request instance * @param Response $response A Response instance * * @return string The key under which the response is stored * * @throws \RuntimeException */ public function write(Request $request, Response $response) { $key = $this->getCacheKey($request); $storedEnv = $this->persistRequest($request); // write the response body to the entity store if this is the original response if (!$response->headers->has('X-Content-Digest')) { $digest = $this->generateContentDigest($response); if (false === $this->save($digest, $response->getContent())) { throw new \RuntimeException('Unable to store the entity.'); } $response->headers->set('X-Content-Digest', $digest); if (!$response->headers->has('Transfer-Encoding')) { $response->headers->set('Content-Length', strlen($response->getContent())); } } // read existing cache entries, remove non-varying, and add this one to the list $entries = array(); $vary = $response->headers->get('vary'); foreach ($this->getMetadata($key) as $entry) { if (!isset($entry[1]['vary'][0])) { $entry[1]['vary'] = array(''); } if ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) { $entries[] = $entry; } } $headers = $this->persistResponse($response); unset($headers['age']); array_unshift($entries, array($storedEnv, $headers)); if (false === $this->save($key, serialize($entries))) { throw new \RuntimeException('Unable to store the metadata.'); } return $key; } /** * Returns content digest for $response. * * @param Response $response * * @return string */ protected function generateContentDigest(Response $response) { return 'en'.hash('sha256', $response->getContent()); } /** * Invalidates all cache entries that match the request. * * @param Request $request A Request instance * * @throws \RuntimeException */ public function invalidate(Request $request) { $modified = false; $key = $this->getCacheKey($request); $entries = array(); foreach ($this->getMetadata($key) as $entry) { $response = $this->restoreResponse($entry[1]); if ($response->isFresh()) { $response->expire(); $modified = true; $entries[] = array($entry[0], $this->persistResponse($response)); } else { $entries[] = $entry; } } if ($modified && false === $this->save($key, serialize($entries))) { throw new \RuntimeException('Unable to store the metadata.'); } } /** * Determines whether two Request HTTP header sets are non-varying based on * the vary response header value provided. * * @param string $vary A Response vary header * @param array $env1 A Request HTTP header array * @param array $env2 A Request HTTP header array * * @return bool true if the two environments match, false otherwise */ private function requestsMatch($vary, $env1, $env2) { if (empty($vary)) { return true; } foreach (preg_split('/[\s,]+/', $vary) as $header) { $key = str_replace('_', '-', strtolower($header)); $v1 = isset($env1[$key]) ? $env1[$key] : null; $v2 = isset($env2[$key]) ? $env2[$key] : null; if ($v1 !== $v2) { return false; } } return true; } /** * Gets all data associated with the given key. * * Use this method only if you know what you are doing. * * @param string $key The store key * * @return array An array of data associated with the key */ private function getMetadata($key) { if (!$entries = $this->load($key)) { return array(); } return unserialize($entries); } /** * Purges data for the given URL. * * This method purges both the HTTP and the HTTPS version of the cache entry. * * @param string $url A URL * * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise */ public function purge($url) { $http = preg_replace('#^https:#', 'http:', $url); $https = preg_replace('#^http:#', 'https:', $url); $purgedHttp = $this->doPurge($http); $purgedHttps = $this->doPurge($https); return $purgedHttp || $purgedHttps; } /** * Purges data for the given URL. * * @param string $url A URL * * @return bool true if the URL exists and has been purged, false otherwise */ private function doPurge($url) { $key = $this->getCacheKey(Request::create($url)); if (isset($this->locks[$key])) { flock($this->locks[$key], LOCK_UN); fclose($this->locks[$key]); unset($this->locks[$key]); } if (file_exists($path = $this->getPath($key))) { unlink($path); return true; } return false; } /** * Loads data for the given key. * * @param string $key The store key * * @return string The data associated with the key */ private function load($key) { $path = $this->getPath($key); return file_exists($path) ? file_get_contents($path) : false; } /** * Save data for the given key. * * @param string $key The store key * @param string $data The data to store * * @return bool */ private function save($key, $data) { $path = $this->getPath($key); if (isset($this->locks[$key])) { $fp = $this->locks[$key]; @ftruncate($fp, 0); @fseek($fp, 0); $len = @fwrite($fp, $data); if (strlen($data) !== $len) { @ftruncate($fp, 0); return false; } } else { if (!file_exists(dirname($path)) && false === @mkdir(dirname($path), 0777, true) && !is_dir(dirname($path))) { return false; } $tmpFile = tempnam(dirname($path), basename($path)); if (false === $fp = @fopen($tmpFile, 'wb')) { return false; } @fwrite($fp, $data); @fclose($fp); if ($data != file_get_contents($tmpFile)) { return false; } if (false === @rename($tmpFile, $path)) { return false; } } @chmod($path, 0666 & ~umask()); } public function getPath($key) { return $this->root.DIRECTORY_SEPARATOR.substr($key, 0, 2).DIRECTORY_SEPARATOR.substr($key, 2, 2).DIRECTORY_SEPARATOR.substr($key, 4, 2).DIRECTORY_SEPARATOR.substr($key, 6); } /** * Generates a cache key for the given Request. * * This method should return a key that must only depend on a * normalized version of the request URI. * * If the same URI can have more than one representation, based on some * headers, use a Vary header to indicate them, and each representation will * be stored independently under the same cache key. * * @param Request $request A Request instance * * @return string A key for the given Request */ protected function generateCacheKey(Request $request) { return 'md'.hash('sha256', $request->getUri()); } /** * Returns a cache key for the given Request. * * @param Request $request A Request instance * * @return string A key for the given Request */ private function getCacheKey(Request $request) { if (isset($this->keyCache[$request])) { return $this->keyCache[$request]; } return $this->keyCache[$request] = $this->generateCacheKey($request); } /** * Persists the Request HTTP headers. * * @param Request $request A Request instance * * @return array An array of HTTP headers */ private function persistRequest(Request $request) { return $request->headers->all(); } /** * Persists the Response HTTP headers. * * @param Response $response A Response instance * * @return array An array of HTTP headers */ private function persistResponse(Response $response) { $headers = $response->headers->all(); $headers['X-Status'] = array($response->getStatusCode()); return $headers; } /** * Restores a Response from the HTTP headers and body. * * @param array $headers An array of HTTP headers for the Response * @param string $body The Response body * * @return Response */ private function restoreResponse($headers, $body = null) { $status = $headers['X-Status'][0]; unset($headers['X-Status']); if (null !== $body) { $headers['X-Body-File'] = array($body); } return new Response($body, $status, $headers); } } ResponseCacheStrategy.php 0000604 00000005564 15224665251 0011540 0 ustar 00 <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * This code is partially based on the Rack-Cache library by Ryan Tomayko, * which is released under the MIT license. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Response; /** * ResponseCacheStrategy knows how to compute the Response cache HTTP header * based on the different response cache headers. * * This implementation changes the master response TTL to the smallest TTL received * or force validation if one of the surrogates has validation cache strategy. * * @author Fabien Potencier <fabien@symfony.com> */ class ResponseCacheStrategy implements ResponseCacheStrategyInterface { private $cacheable = true; private $embeddedResponses = 0; private $ttls = array(); private $maxAges = array(); private $isNotCacheableResponseEmbedded = false; /** * {@inheritdoc} */ public function add(Response $response) { if (!$response->isFresh() || !$response->isCacheable()) { $this->cacheable = false; } else { $maxAge = $response->getMaxAge(); $this->ttls[] = $response->getTtl(); $this->maxAges[] = $maxAge; if (null === $maxAge) { $this->isNotCacheableResponseEmbedded = true; } } ++$this->embeddedResponses; } /** * {@inheritdoc} */ public function update(Response $response) { // if we have no embedded Response, do nothing if (0 === $this->embeddedResponses) { return; } // Remove validation related headers in order to avoid browsers using // their own cache, because some of the response content comes from // at least one embedded response (which likely has a different caching strategy). if ($response->isValidateable()) { $response->setEtag(null); $response->setLastModified(null); } if (!$response->isFresh()) { $this->cacheable = false; } if (!$this->cacheable) { $response->headers->set('Cache-Control', 'no-cache, must-revalidate'); return; } $this->ttls[] = $response->getTtl(); $this->maxAges[] = $response->getMaxAge(); if ($this->isNotCacheableResponseEmbedded) { $response->headers->removeCacheControlDirective('s-maxage'); } elseif (null !== $maxAge = min($this->maxAges)) { $response->setSharedMaxAge($maxAge); $response->headers->set('Age', $maxAge - min($this->ttls)); } $response->setMaxAge(0); } } Ssi.php 0000604 00000005467 15224665251 0006033 0 ustar 00 <?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\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Ssi implements the SSI capabilities to Request and Response instances. * * @author Sebastian Krebs <krebs.seb@gmail.com> */ class Ssi extends AbstractSurrogate { /** * {@inheritdoc} */ public function getName() { return 'ssi'; } /** * {@inheritdoc} */ public function addSurrogateControl(Response $response) { if (false !== strpos($response->getContent(), '<!--#include')) { $response->headers->set('Surrogate-Control', 'content="SSI/1.0"'); } } /** * {@inheritdoc} */ public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '') { return sprintf('<!--#include virtual="%s" -->', $uri); } /** * {@inheritdoc} */ public function process(Request $request, Response $response) { $type = $response->headers->get('Content-Type'); if (empty($type)) { $type = 'text/html'; } $parts = explode(';', $type); if (!in_array($parts[0], $this->contentTypes)) { return $response; } // we don't use a proper XML parser here as we can have SSI tags in a plain text response $content = $response->getContent(); $chunks = preg_split('#<!--\#include\s+(.*?)\s*-->#', $content, -1, PREG_SPLIT_DELIM_CAPTURE); $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]); $i = 1; while (isset($chunks[$i])) { $options = array(); preg_match_all('/(virtual)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER); foreach ($matches as $set) { $options[$set[1]] = $set[2]; } if (!isset($options['virtual'])) { throw new \RuntimeException('Unable to process an SSI tag without a "virtual" attribute.'); } $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, \'\', false) ?>'."\n", var_export($options['virtual'], true) ); ++$i; $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]); ++$i; } $content = implode('', $chunks); $response->setContent($content); $response->headers->set('X-Body-Eval', 'SSI'); // remove SSI/1.0 from the Surrogate-Control header $this->removeFromControl($response); } } SurrogateInterface.php 0000604 00000005707 15224665251 0011066 0 ustar 00 <?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\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; interface SurrogateInterface { /** * Returns surrogate name. * * @return string */ public function getName(); /** * Returns a new cache strategy instance. * * @return ResponseCacheStrategyInterface A ResponseCacheStrategyInterface instance */ public function createCacheStrategy(); /** * Checks that at least one surrogate has Surrogate capability. * * @param Request $request A Request instance * * @return bool true if one surrogate has Surrogate capability, false otherwise */ public function hasSurrogateCapability(Request $request); /** * Adds Surrogate-capability to the given Request. * * @param Request $request A Request instance */ public function addSurrogateCapability(Request $request); /** * Adds HTTP headers to specify that the Response needs to be parsed for Surrogate. * * This method only adds an Surrogate HTTP header if the Response has some Surrogate tags. * * @param Response $response A Response instance */ public function addSurrogateControl(Response $response); /** * Checks that the Response needs to be parsed for Surrogate tags. * * @param Response $response A Response instance * * @return bool true if the Response needs to be parsed, false otherwise */ public function needsParsing(Response $response); /** * Renders a Surrogate tag. * * @param string $uri A URI * @param string $alt An alternate URI * @param bool $ignoreErrors Whether to ignore errors or not * @param string $comment A comment to add as an esi:include tag * * @return string */ public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = ''); /** * Replaces a Response Surrogate tags with the included resource content. * * @param Request $request A Request instance * @param Response $response A Response instance * * @return Response */ public function process(Request $request, Response $response); /** * Handles a Surrogate from the cache. * * @param HttpCache $cache An HttpCache instance * @param string $uri The main URI * @param string $alt An alternative URI * @param bool $ignoreErrors Whether to ignore errors or not * * @return string * * @throws \RuntimeException * @throws \Exception */ public function handle(HttpCache $cache, $uri, $alt, $ignoreErrors); } HttpCache.php 0000604 00000061414 15224665251 0007132 0 ustar 00 <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * This code is partially based on the Rack-Cache library by Ryan Tomayko, * which is released under the MIT license. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\HttpCache; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\TerminableInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Cache provides HTTP caching. * * @author Fabien Potencier <fabien@symfony.com> */ class HttpCache implements HttpKernelInterface, TerminableInterface { private $kernel; private $store; private $request; private $surrogate; private $surrogateCacheStrategy; private $options = array(); private $traces = array(); /** * Constructor. * * The available options are: * * * debug: If true, the traces are added as a HTTP header to ease debugging * * * default_ttl The number of seconds that a cache entry should be considered * fresh when no explicit freshness information is provided in * a response. Explicit Cache-Control or Expires headers * override this value. (default: 0) * * * private_headers Set of request headers that trigger "private" cache-control behavior * on responses that don't explicitly state whether the response is * public or private via a Cache-Control directive. (default: Authorization and Cookie) * * * allow_reload Specifies whether the client can force a cache reload by including a * Cache-Control "no-cache" directive in the request. Set it to ``true`` * for compliance with RFC 2616. (default: false) * * * allow_revalidate Specifies whether the client can force a cache revalidate by including * a Cache-Control "max-age=0" directive in the request. Set it to ``true`` * for compliance with RFC 2616. (default: false) * * * stale_while_revalidate Specifies the default number of seconds (the granularity is the second as the * Response TTL precision is a second) during which the cache can immediately return * a stale response while it revalidates it in the background (default: 2). * This setting is overridden by the stale-while-revalidate HTTP Cache-Control * extension (see RFC 5861). * * * stale_if_error Specifies the default number of seconds (the granularity is the second) during which * the cache can serve a stale response when an error is encountered (default: 60). * This setting is overridden by the stale-if-error HTTP Cache-Control extension * (see RFC 5861). * * @param HttpKernelInterface $kernel An HttpKernelInterface instance * @param StoreInterface $store A Store instance * @param SurrogateInterface $surrogate A SurrogateInterface instance * @param array $options An array of options */ public function __construct(HttpKernelInterface $kernel, StoreInterface $store, SurrogateInterface $surrogate = null, array $options = array()) { $this->store = $store; $this->kernel = $kernel; $this->surrogate = $surrogate; // needed in case there is a fatal error because the backend is too slow to respond register_shutdown_function(array($this->store, 'cleanup')); $this->options = array_merge(array( 'debug' => false, 'default_ttl' => 0, 'private_headers' => array('Authorization', 'Cookie'), 'allow_reload' => false, 'allow_revalidate' => false, 'stale_while_revalidate' => 2, 'stale_if_error' => 60, ), $options); } /** * Gets the current store. * * @return StoreInterface $store A StoreInterface instance */ public function getStore() { return $this->store; } /** * Returns an array of events that took place during processing of the last request. * * @return array An array of events */ public function getTraces() { return $this->traces; } /** * Returns a log message for the events of the last request processing. * * @return string A log message */ public function getLog() { $log = array(); foreach ($this->traces as $request => $traces) { $log[] = sprintf('%s: %s', $request, implode(', ', $traces)); } return implode('; ', $log); } /** * Gets the Request instance associated with the master request. * * @return Request A Request instance */ public function getRequest() { return $this->request; } /** * Gets the Kernel instance. * * @return HttpKernelInterface An HttpKernelInterface instance */ public function getKernel() { return $this->kernel; } /** * Gets the Surrogate instance. * * @return SurrogateInterface A Surrogate instance * * @throws \LogicException */ public function getSurrogate() { return $this->surrogate; } /** * {@inheritdoc} */ public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true) { // FIXME: catch exceptions and implement a 500 error page here? -> in Varnish, there is a built-in error page mechanism if (HttpKernelInterface::MASTER_REQUEST === $type) { $this->traces = array(); $this->request = $request; if (null !== $this->surrogate) { $this->surrogateCacheStrategy = $this->surrogate->createCacheStrategy(); } } $this->traces[$this->getTraceKey($request)] = array(); if (!$request->isMethodSafe(false)) { $response = $this->invalidate($request, $catch); } elseif ($request->headers->has('expect') || !$request->isMethodCacheable()) { $response = $this->pass($request, $catch); } elseif ($this->options['allow_reload'] && $request->isNoCache()) { /* If allow_reload is configured and the client requests "Cache-Control: no-cache", reload the cache by fetching a fresh response and caching it (if possible). */ $this->record($request, 'reload'); $response = $this->fetch($request, $catch); } else { $response = $this->lookup($request, $catch); } $this->restoreResponseBody($request, $response); if (HttpKernelInterface::MASTER_REQUEST === $type && $this->options['debug']) { $response->headers->set('X-Symfony-Cache', $this->getLog()); } if (null !== $this->surrogate) { if (HttpKernelInterface::MASTER_REQUEST === $type) { $this->surrogateCacheStrategy->update($response); } else { $this->surrogateCacheStrategy->add($response); } } $response->prepare($request); $response->isNotModified($request); return $response; } /** * {@inheritdoc} */ public function terminate(Request $request, Response $response) { if ($this->getKernel() instanceof TerminableInterface) { $this->getKernel()->terminate($request, $response); } } /** * Forwards the Request to the backend without storing the Response in the cache. * * @param Request $request A Request instance * @param bool $catch Whether to process exceptions * * @return Response A Response instance */ protected function pass(Request $request, $catch = false) { $this->record($request, 'pass'); return $this->forward($request, $catch); } /** * Invalidates non-safe methods (like POST, PUT, and DELETE). * * @param Request $request A Request instance * @param bool $catch Whether to process exceptions * * @return Response A Response instance * * @throws \Exception * * @see RFC2616 13.10 */ protected function invalidate(Request $request, $catch = false) { $response = $this->pass($request, $catch); // invalidate only when the response is successful if ($response->isSuccessful() || $response->isRedirect()) { try { $this->store->invalidate($request); // As per the RFC, invalidate Location and Content-Location URLs if present foreach (array('Location', 'Content-Location') as $header) { if ($uri = $response->headers->get($header)) { $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all()); $this->store->invalidate($subRequest); } } $this->record($request, 'invalidate'); } catch (\Exception $e) { $this->record($request, 'invalidate-failed'); if ($this->options['debug']) { throw $e; } } } return $response; } /** * Lookups a Response from the cache for the given Request. * * When a matching cache entry is found and is fresh, it uses it as the * response without forwarding any request to the backend. When a matching * cache entry is found but is stale, it attempts to "validate" the entry with * the backend using conditional GET. When no matching cache entry is found, * it triggers "miss" processing. * * @param Request $request A Request instance * @param bool $catch whether to process exceptions * * @return Response A Response instance * * @throws \Exception */ protected function lookup(Request $request, $catch = false) { try { $entry = $this->store->lookup($request); } catch (\Exception $e) { $this->record($request, 'lookup-failed'); if ($this->options['debug']) { throw $e; } return $this->pass($request, $catch); } if (null === $entry) { $this->record($request, 'miss'); return $this->fetch($request, $catch); } if (!$this->isFreshEnough($request, $entry)) { $this->record($request, 'stale'); return $this->validate($request, $entry, $catch); } $this->record($request, 'fresh'); $entry->headers->set('Age', $entry->getAge()); return $entry; } /** * Validates that a cache entry is fresh. * * The original request is used as a template for a conditional * GET request with the backend. * * @param Request $request A Request instance * @param Response $entry A Response instance to validate * @param bool $catch Whether to process exceptions * * @return Response A Response instance */ protected function validate(Request $request, Response $entry, $catch = false) { $subRequest = clone $request; // send no head requests because we want content if ('HEAD' === $request->getMethod()) { $subRequest->setMethod('GET'); } // add our cached last-modified validator $subRequest->headers->set('if_modified_since', $entry->headers->get('Last-Modified')); // Add our cached etag validator to the environment. // We keep the etags from the client to handle the case when the client // has a different private valid entry which is not cached here. $cachedEtags = $entry->getEtag() ? array($entry->getEtag()) : array(); $requestEtags = $request->getETags(); if ($etags = array_unique(array_merge($cachedEtags, $requestEtags))) { $subRequest->headers->set('if_none_match', implode(', ', $etags)); } $response = $this->forward($subRequest, $catch, $entry); if (304 == $response->getStatusCode()) { $this->record($request, 'valid'); // return the response and not the cache entry if the response is valid but not cached $etag = $response->getEtag(); if ($etag && in_array($etag, $requestEtags) && !in_array($etag, $cachedEtags)) { return $response; } $entry = clone $entry; $entry->headers->remove('Date'); foreach (array('Date', 'Expires', 'Cache-Control', 'ETag', 'Last-Modified') as $name) { if ($response->headers->has($name)) { $entry->headers->set($name, $response->headers->get($name)); } } $response = $entry; } else { $this->record($request, 'invalid'); } if ($response->isCacheable()) { $this->store($request, $response); } return $response; } /** * Unconditionally fetches a fresh response from the backend and * stores it in the cache if is cacheable. * * @param Request $request A Request instance * @param bool $catch whether to process exceptions * * @return Response A Response instance */ protected function fetch(Request $request, $catch = false) { $subRequest = clone $request; // send no head requests because we want content if ('HEAD' === $request->getMethod()) { $subRequest->setMethod('GET'); } // avoid that the backend sends no content $subRequest->headers->remove('if_modified_since'); $subRequest->headers->remove('if_none_match'); $response = $this->forward($subRequest, $catch); if ($response->isCacheable()) { $this->store($request, $response); } return $response; } /** * Forwards the Request to the backend and returns the Response. * * All backend requests (cache passes, fetches, cache validations) * run through this method. * * @param Request $request A Request instance * @param bool $catch Whether to catch exceptions or not * @param Response $entry A Response instance (the stale entry if present, null otherwise) * * @return Response A Response instance */ protected function forward(Request $request, $catch = false, Response $entry = null) { if ($this->surrogate) { $this->surrogate->addSurrogateCapability($request); } // modify the X-Forwarded-For header if needed $forwardedFor = $request->headers->get('X-Forwarded-For'); if ($forwardedFor) { $request->headers->set('X-Forwarded-For', $forwardedFor.', '.$request->server->get('REMOTE_ADDR')); } else { $request->headers->set('X-Forwarded-For', $request->server->get('REMOTE_ADDR')); } // fix the client IP address by setting it to 127.0.0.1 as HttpCache // is always called from the same process as the backend. $request->server->set('REMOTE_ADDR', '127.0.0.1'); // make sure HttpCache is a trusted proxy if (!in_array('127.0.0.1', $trustedProxies = Request::getTrustedProxies())) { $trustedProxies[] = '127.0.0.1'; Request::setTrustedProxies($trustedProxies, Request::HEADER_X_FORWARDED_ALL); } // always a "master" request (as the real master request can be in cache) $response = $this->kernel->handle($request, HttpKernelInterface::MASTER_REQUEST, $catch); // FIXME: we probably need to also catch exceptions if raw === true // we don't implement the stale-if-error on Requests, which is nonetheless part of the RFC if (null !== $entry && in_array($response->getStatusCode(), array(500, 502, 503, 504))) { if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) { $age = $this->options['stale_if_error']; } if (abs($entry->getTtl()) < $age) { $this->record($request, 'stale-if-error'); return $entry; } } /* RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate clock MUST NOT send a "Date" header, although it MUST send one in most other cases except for 1xx or 5xx responses where it MAY do so. Anyway, a client that received a message without a "Date" header MUST add it. */ if (!$response->headers->has('Date')) { $response->setDate(\DateTime::createFromFormat('U', time())); } $this->processResponseBody($request, $response); if ($this->isPrivateRequest($request) && !$response->headers->hasCacheControlDirective('public')) { $response->setPrivate(); } elseif ($this->options['default_ttl'] > 0 && null === $response->getTtl() && !$response->headers->getCacheControlDirective('must-revalidate')) { $response->setTtl($this->options['default_ttl']); } return $response; } /** * Checks whether the cache entry is "fresh enough" to satisfy the Request. * * @param Request $request A Request instance * @param Response $entry A Response instance * * @return bool true if the cache entry if fresh enough, false otherwise */ protected function isFreshEnough(Request $request, Response $entry) { if (!$entry->isFresh()) { return $this->lock($request, $entry); } if ($this->options['allow_revalidate'] && null !== $maxAge = $request->headers->getCacheControlDirective('max-age')) { return $maxAge > 0 && $maxAge >= $entry->getAge(); } return true; } /** * Locks a Request during the call to the backend. * * @param Request $request A Request instance * @param Response $entry A Response instance * * @return bool true if the cache entry can be returned even if it is staled, false otherwise */ protected function lock(Request $request, Response $entry) { // try to acquire a lock to call the backend $lock = $this->store->lock($request); if (true === $lock) { // we have the lock, call the backend return false; } // there is already another process calling the backend // May we serve a stale response? if ($this->mayServeStaleWhileRevalidate($entry)) { $this->record($request, 'stale-while-revalidate'); return true; } // wait for the lock to be released if ($this->waitForLock($request)) { // replace the current entry with the fresh one $new = $this->lookup($request); $entry->headers = $new->headers; $entry->setContent($new->getContent()); $entry->setStatusCode($new->getStatusCode()); $entry->setProtocolVersion($new->getProtocolVersion()); foreach ($new->headers->getCookies() as $cookie) { $entry->headers->setCookie($cookie); } } else { // backend is slow as hell, send a 503 response (to avoid the dog pile effect) $entry->setStatusCode(503); $entry->setContent('503 Service Unavailable'); $entry->headers->set('Retry-After', 10); } return true; } /** * Writes the Response to the cache. * * @param Request $request A Request instance * @param Response $response A Response instance * * @throws \Exception */ protected function store(Request $request, Response $response) { try { $this->store->write($request, $response); $this->record($request, 'store'); $response->headers->set('Age', $response->getAge()); } catch (\Exception $e) { $this->record($request, 'store-failed'); if ($this->options['debug']) { throw $e; } } // now that the response is cached, release the lock $this->store->unlock($request); } /** * Restores the Response body. * * @param Request $request A Request instance * @param Response $response A Response instance */ private function restoreResponseBody(Request $request, Response $response) { if ($request->isMethod('HEAD') || 304 === $response->getStatusCode()) { $response->setContent(null); $response->headers->remove('X-Body-Eval'); $response->headers->remove('X-Body-File'); return; } if ($response->headers->has('X-Body-Eval')) { ob_start(); if ($response->headers->has('X-Body-File')) { include $response->headers->get('X-Body-File'); } else { eval('; ?>'.$response->getContent().'<?php ;'); } $response->setContent(ob_get_clean()); $response->headers->remove('X-Body-Eval'); if (!$response->headers->has('Transfer-Encoding')) { $response->headers->set('Content-Length', strlen($response->getContent())); } } elseif ($response->headers->has('X-Body-File')) { $response->setContent(file_get_contents($response->headers->get('X-Body-File'))); } else { return; } $response->headers->remove('X-Body-File'); } protected function processResponseBody(Request $request, Response $response) { if (null !== $this->surrogate && $this->surrogate->needsParsing($response)) { $this->surrogate->process($request, $response); } } /** * Checks if the Request includes authorization or other sensitive information * that should cause the Response to be considered private by default. * * @param Request $request A Request instance * * @return bool true if the Request is private, false otherwise */ private function isPrivateRequest(Request $request) { foreach ($this->options['private_headers'] as $key) { $key = strtolower(str_replace('HTTP_', '', $key)); if ('cookie' === $key) { if (count($request->cookies->all())) { return true; } } elseif ($request->headers->has($key)) { return true; } } return false; } /** * Records that an event took place. * * @param Request $request A Request instance * @param string $event The event name */ private function record(Request $request, $event) { $this->traces[$this->getTraceKey($request)][] = $event; } /** * Calculates the key we use in the "trace" array for a given request. * * @param Request $request * * @return string */ private function getTraceKey(Request $request) { $path = $request->getPathInfo(); if ($qs = $request->getQueryString()) { $path .= '?'.$qs; } return $request->getMethod().' '.$path; } /** * Checks whether the given (cached) response may be served as "stale" when a revalidation * is currently in progress. * * @param Response $entry * * @return bool True when the stale response may be served, false otherwise. */ private function mayServeStaleWhileRevalidate(Response $entry) { $timeout = $entry->headers->getCacheControlDirective('stale-while-revalidate'); if (null === $timeout) { $timeout = $this->options['stale_while_revalidate']; } return abs($entry->getTtl()) < $timeout; } /** * Waits for the store to release a locked entry. * * @param Request $request The request to wait for * * @return bool True if the lock was released before the internal timeout was hit; false if the wait timeout was exceeded. */ private function waitForLock(Request $request) { $wait = 0; while ($this->store->isLocked($request) && $wait < 5000000) { usleep(50000); $wait += 50000; } return $wait < 5000000; } } Esi.php 0000604 00000007115 15224665251 0006005 0 ustar 00 <?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\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Esi implements the ESI capabilities to Request and Response instances. * * For more information, read the following W3C notes: * * * ESI Language Specification 1.0 (http://www.w3.org/TR/esi-lang) * * * Edge Architecture Specification (http://www.w3.org/TR/edge-arch) * * @author Fabien Potencier <fabien@symfony.com> */ class Esi extends AbstractSurrogate { public function getName() { return 'esi'; } /** * {@inheritdoc} */ public function addSurrogateControl(Response $response) { if (false !== strpos($response->getContent(), '<esi:include')) { $response->headers->set('Surrogate-Control', 'content="ESI/1.0"'); } } /** * {@inheritdoc} */ public function renderIncludeTag($uri, $alt = null, $ignoreErrors = true, $comment = '') { $html = sprintf('<esi:include src="%s"%s%s />', $uri, $ignoreErrors ? ' onerror="continue"' : '', $alt ? sprintf(' alt="%s"', $alt) : '' ); if (!empty($comment)) { return sprintf("<esi:comment text=\"%s\" />\n%s", $comment, $html); } return $html; } /** * {@inheritdoc} */ public function process(Request $request, Response $response) { $type = $response->headers->get('Content-Type'); if (empty($type)) { $type = 'text/html'; } $parts = explode(';', $type); if (!in_array($parts[0], $this->contentTypes)) { return $response; } // we don't use a proper XML parser here as we can have ESI tags in a plain text response $content = $response->getContent(); $content = preg_replace('#<esi\:remove>.*?</esi\:remove>#s', '', $content); $content = preg_replace('#<esi\:comment[^>]+>#s', '', $content); $chunks = preg_split('#<esi\:include\s+(.*?)\s*(?:/|</esi\:include)>#', $content, -1, PREG_SPLIT_DELIM_CAPTURE); $chunks[0] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[0]); $i = 1; while (isset($chunks[$i])) { $options = array(); preg_match_all('/(src|onerror|alt)="([^"]*?)"/', $chunks[$i], $matches, PREG_SET_ORDER); foreach ($matches as $set) { $options[$set[1]] = $set[2]; } if (!isset($options['src'])) { throw new \RuntimeException('Unable to process an ESI tag without a "src" attribute.'); } $chunks[$i] = sprintf('<?php echo $this->surrogate->handle($this, %s, %s, %s) ?>'."\n", var_export($options['src'], true), var_export(isset($options['alt']) ? $options['alt'] : '', true), isset($options['onerror']) && 'continue' === $options['onerror'] ? 'true' : 'false' ); ++$i; $chunks[$i] = str_replace($this->phpEscapeMap[0], $this->phpEscapeMap[1], $chunks[$i]); ++$i; } $content = implode('', $chunks); $response->setContent($content); $response->headers->set('X-Body-Eval', 'ESI'); // remove ESI/1.0 from the Surrogate-Control header $this->removeFromControl($response); } } StoreInterface.php 0000604 00000005126 15224665251 0010202 0 ustar 00 <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * This code is partially based on the Rack-Cache library by Ryan Tomayko, * which is released under the MIT license. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Interface implemented by HTTP cache stores. * * @author Fabien Potencier <fabien@symfony.com> */ interface StoreInterface { /** * Locates a cached Response for the Request provided. * * @param Request $request A Request instance * * @return Response|null A Response instance, or null if no cache entry was found */ public function lookup(Request $request); /** * Writes a cache entry to the store for the given Request and Response. * * Existing entries are read and any that match the response are removed. This * method calls write with the new list of cache entries. * * @param Request $request A Request instance * @param Response $response A Response instance * * @return string The key under which the response is stored */ public function write(Request $request, Response $response); /** * Invalidates all cache entries that match the request. * * @param Request $request A Request instance */ public function invalidate(Request $request); /** * Locks the cache for a given Request. * * @param Request $request A Request instance * * @return bool|string true if the lock is acquired, the path to the current lock otherwise */ public function lock(Request $request); /** * Releases the lock for the given Request. * * @param Request $request A Request instance * * @return bool False if the lock file does not exist or cannot be unlocked, true otherwise */ public function unlock(Request $request); /** * Returns whether or not a lock exists. * * @param Request $request A Request instance * * @return bool true if lock exists, false otherwise */ public function isLocked(Request $request); /** * Purges data for the given URL. * * @param string $url A URL * * @return bool true if the URL exists and has been purged, false otherwise */ public function purge($url); /** * Cleanups storage. */ public function cleanup(); } StoreTest.php 0000604 00000026250 15224666447 0007232 0 ustar 00 <?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\Component\HttpKernel\Tests\HttpCache; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpCache\Store; class StoreTest extends TestCase { protected $request; protected $response; /** * @var Store */ protected $store; protected function setUp() { $this->request = Request::create('/'); $this->response = new Response('hello world', 200, array()); HttpCacheTestCase::clearDirectory(sys_get_temp_dir().'/http_cache'); $this->store = new Store(sys_get_temp_dir().'/http_cache'); } protected function tearDown() { $this->store = null; $this->request = null; $this->response = null; HttpCacheTestCase::clearDirectory(sys_get_temp_dir().'/http_cache'); } public function testReadsAnEmptyArrayWithReadWhenNothingCachedAtKey() { $this->assertEmpty($this->getStoreMetadata('/nothing')); } public function testUnlockFileThatDoesExist() { $cacheKey = $this->storeSimpleEntry(); $this->store->lock($this->request); $this->assertTrue($this->store->unlock($this->request)); } public function testUnlockFileThatDoesNotExist() { $this->assertFalse($this->store->unlock($this->request)); } public function testRemovesEntriesForKeyWithPurge() { $request = Request::create('/foo'); $this->store->write($request, new Response('foo')); $metadata = $this->getStoreMetadata($request); $this->assertNotEmpty($metadata); $this->assertTrue($this->store->purge('/foo')); $this->assertEmpty($this->getStoreMetadata($request)); // cached content should be kept after purging $path = $this->store->getPath($metadata[0][1]['x-content-digest'][0]); $this->assertTrue(is_file($path)); $this->assertFalse($this->store->purge('/bar')); } public function testStoresACacheEntry() { $cacheKey = $this->storeSimpleEntry(); $this->assertNotEmpty($this->getStoreMetadata($cacheKey)); } public function testSetsTheXContentDigestResponseHeaderBeforeStoring() { $cacheKey = $this->storeSimpleEntry(); $entries = $this->getStoreMetadata($cacheKey); list($req, $res) = $entries[0]; $this->assertEquals('en9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08', $res['x-content-digest'][0]); } public function testFindsAStoredEntryWithLookup() { $this->storeSimpleEntry(); $response = $this->store->lookup($this->request); $this->assertNotNull($response); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); } public function testDoesNotFindAnEntryWithLookupWhenNoneExists() { $request = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $this->assertNull($this->store->lookup($request)); } public function testCanonizesUrlsForCacheKeys() { $this->storeSimpleEntry($path = '/test?x=y&p=q'); $hitsReq = Request::create($path); $missReq = Request::create('/test?p=x'); $this->assertNotNull($this->store->lookup($hitsReq)); $this->assertNull($this->store->lookup($missReq)); } public function testDoesNotFindAnEntryWithLookupWhenTheBodyDoesNotExist() { $this->storeSimpleEntry(); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $path = $this->getStorePath($this->response->headers->get('X-Content-Digest')); @unlink($path); $this->assertNull($this->store->lookup($this->request)); } public function testRestoresResponseHeadersProperlyWithLookup() { $this->storeSimpleEntry(); $response = $this->store->lookup($this->request); $this->assertEquals($response->headers->all(), array_merge(array('content-length' => 4, 'x-body-file' => array($this->getStorePath($response->headers->get('X-Content-Digest')))), $this->response->headers->all())); } public function testRestoresResponseContentFromEntityStoreWithLookup() { $this->storeSimpleEntry(); $response = $this->store->lookup($this->request); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test')), $response->getContent()); } public function testInvalidatesMetaAndEntityStoreEntriesWithInvalidate() { $this->storeSimpleEntry(); $this->store->invalidate($this->request); $response = $this->store->lookup($this->request); $this->assertInstanceOf('Symfony\Component\HttpFoundation\Response', $response); $this->assertFalse($response->isFresh()); } public function testSucceedsQuietlyWhenInvalidateCalledWithNoMatchingEntries() { $req = Request::create('/test'); $this->store->invalidate($req); $this->assertNull($this->store->lookup($this->request)); } public function testDoesNotReturnEntriesThatVaryWithLookup() { $req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam')); $res = new Response('test', 200, array('Vary' => 'Foo Bar')); $this->store->write($req1, $res); $this->assertNull($this->store->lookup($req2)); } public function testDoesNotReturnEntriesThatSlightlyVaryWithLookup() { $req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bam')); $res = new Response('test', 200, array('Vary' => array('Foo', 'Bar'))); $this->store->write($req1, $res); $this->assertNull($this->store->lookup($req2)); } public function testStoresMultipleResponsesForEachVaryCombination() { $req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar')); $key = $this->store->write($req1, $res1); $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam')); $res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar')); $this->store->write($req2, $res2); $req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Baz', 'HTTP_BAR' => 'Boom')); $res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar')); $this->store->write($req3, $res3); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 3')), $this->store->lookup($req3)->getContent()); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 2')), $this->store->lookup($req2)->getContent()); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent()); $this->assertCount(3, $this->getStoreMetadata($key)); } public function testOverwritesNonVaryingResponseWithStore() { $req1 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $res1 = new Response('test 1', 200, array('Vary' => 'Foo Bar')); $key = $this->store->write($req1, $res1); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 1')), $this->store->lookup($req1)->getContent()); $req2 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Bling', 'HTTP_BAR' => 'Bam')); $res2 = new Response('test 2', 200, array('Vary' => 'Foo Bar')); $this->store->write($req2, $res2); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 2')), $this->store->lookup($req2)->getContent()); $req3 = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $res3 = new Response('test 3', 200, array('Vary' => 'Foo Bar')); $key = $this->store->write($req3, $res3); $this->assertEquals($this->getStorePath('en'.hash('sha256', 'test 3')), $this->store->lookup($req3)->getContent()); $this->assertCount(2, $this->getStoreMetadata($key)); } public function testLocking() { $req = Request::create('/test', 'get', array(), array(), array(), array('HTTP_FOO' => 'Foo', 'HTTP_BAR' => 'Bar')); $this->assertTrue($this->store->lock($req)); $path = $this->store->lock($req); $this->assertTrue($this->store->isLocked($req)); $this->store->unlock($req); $this->assertFalse($this->store->isLocked($req)); } public function testPurgeHttps() { $request = Request::create('https://example.com/foo'); $this->store->write($request, new Response('foo')); $this->assertNotEmpty($this->getStoreMetadata($request)); $this->assertTrue($this->store->purge('https://example.com/foo')); $this->assertEmpty($this->getStoreMetadata($request)); } public function testPurgeHttpAndHttps() { $requestHttp = Request::create('https://example.com/foo'); $this->store->write($requestHttp, new Response('foo')); $requestHttps = Request::create('http://example.com/foo'); $this->store->write($requestHttps, new Response('foo')); $this->assertNotEmpty($this->getStoreMetadata($requestHttp)); $this->assertNotEmpty($this->getStoreMetadata($requestHttps)); $this->assertTrue($this->store->purge('http://example.com/foo')); $this->assertEmpty($this->getStoreMetadata($requestHttp)); $this->assertEmpty($this->getStoreMetadata($requestHttps)); } protected function storeSimpleEntry($path = null, $headers = array()) { if (null === $path) { $path = '/test'; } $this->request = Request::create($path, 'get', array(), array(), array(), $headers); $this->response = new Response('test', 200, array('Cache-Control' => 'max-age=420')); return $this->store->write($this->request, $this->response); } protected function getStoreMetadata($key) { $r = new \ReflectionObject($this->store); $m = $r->getMethod('getMetadata'); $m->setAccessible(true); if ($key instanceof Request) { $m1 = $r->getMethod('getCacheKey'); $m1->setAccessible(true); $key = $m1->invoke($this->store, $key); } return $m->invoke($this->store, $key); } protected function getStorePath($key) { $r = new \ReflectionObject($this->store); $m = $r->getMethod('getPath'); $m->setAccessible(true); return $m->invoke($this->store, $key); } } SsiTest.php 0000604 00000016601 15224666447 0006673 0 ustar 00 <?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\Component\HttpKernel\Tests\HttpCache; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpCache\Ssi; class SsiTest extends TestCase { public function testHasSurrogateSsiCapability() { $ssi = new Ssi(); $request = Request::create('/'); $request->headers->set('Surrogate-Capability', 'abc="SSI/1.0"'); $this->assertTrue($ssi->hasSurrogateCapability($request)); $request = Request::create('/'); $request->headers->set('Surrogate-Capability', 'foobar'); $this->assertFalse($ssi->hasSurrogateCapability($request)); $request = Request::create('/'); $this->assertFalse($ssi->hasSurrogateCapability($request)); } public function testAddSurrogateSsiCapability() { $ssi = new Ssi(); $request = Request::create('/'); $ssi->addSurrogateCapability($request); $this->assertEquals('symfony="SSI/1.0"', $request->headers->get('Surrogate-Capability')); $ssi->addSurrogateCapability($request); $this->assertEquals('symfony="SSI/1.0", symfony="SSI/1.0"', $request->headers->get('Surrogate-Capability')); } public function testAddSurrogateControl() { $ssi = new Ssi(); $response = new Response('foo <!--#include virtual="" -->'); $ssi->addSurrogateControl($response); $this->assertEquals('content="SSI/1.0"', $response->headers->get('Surrogate-Control')); $response = new Response('foo'); $ssi->addSurrogateControl($response); $this->assertEquals('', $response->headers->get('Surrogate-Control')); } public function testNeedsSsiParsing() { $ssi = new Ssi(); $response = new Response(); $response->headers->set('Surrogate-Control', 'content="SSI/1.0"'); $this->assertTrue($ssi->needsParsing($response)); $response = new Response(); $this->assertFalse($ssi->needsParsing($response)); } public function testRenderIncludeTag() { $ssi = new Ssi(); $this->assertEquals('<!--#include virtual="/" -->', $ssi->renderIncludeTag('/', '/alt', true)); $this->assertEquals('<!--#include virtual="/" -->', $ssi->renderIncludeTag('/', '/alt', false)); $this->assertEquals('<!--#include virtual="/" -->', $ssi->renderIncludeTag('/')); } public function testProcessDoesNothingIfContentTypeIsNotHtml() { $ssi = new Ssi(); $request = Request::create('/'); $response = new Response(); $response->headers->set('Content-Type', 'text/plain'); $ssi->process($request, $response); $this->assertFalse($response->headers->has('x-body-eval')); } public function testProcess() { $ssi = new Ssi(); $request = Request::create('/'); $response = new Response('foo <!--#include virtual="..." -->'); $ssi->process($request, $response); $this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent()); $this->assertEquals('SSI', $response->headers->get('x-body-eval')); $response = new Response('foo <!--#include virtual="foo\'" -->'); $ssi->process($request, $response); $this->assertEquals("foo <?php echo \$this->surrogate->handle(\$this, 'foo\\'', '', false) ?>"."\n", $response->getContent()); } public function testProcessEscapesPhpTags() { $ssi = new Ssi(); $request = Request::create('/'); $response = new Response('<?php <? <% <script language=php>'); $ssi->process($request, $response); $this->assertEquals('<?php echo "<?"; ?>php <?php echo "<?"; ?> <?php echo "<%"; ?> <?php echo "<s"; ?>cript language=php>', $response->getContent()); } /** * @expectedException \RuntimeException */ public function testProcessWhenNoSrcInAnSsi() { $ssi = new Ssi(); $request = Request::create('/'); $response = new Response('foo <!--#include -->'); $ssi->process($request, $response); } public function testProcessRemoveSurrogateControlHeader() { $ssi = new Ssi(); $request = Request::create('/'); $response = new Response('foo <!--#include virtual="..." -->'); $response->headers->set('Surrogate-Control', 'content="SSI/1.0"'); $ssi->process($request, $response); $this->assertEquals('SSI', $response->headers->get('x-body-eval')); $response->headers->set('Surrogate-Control', 'no-store, content="SSI/1.0"'); $ssi->process($request, $response); $this->assertEquals('SSI', $response->headers->get('x-body-eval')); $this->assertEquals('no-store', $response->headers->get('surrogate-control')); $response->headers->set('Surrogate-Control', 'content="SSI/1.0", no-store'); $ssi->process($request, $response); $this->assertEquals('SSI', $response->headers->get('x-body-eval')); $this->assertEquals('no-store', $response->headers->get('surrogate-control')); } public function testHandle() { $ssi = new Ssi(); $cache = $this->getCache(Request::create('/'), new Response('foo')); $this->assertEquals('foo', $ssi->handle($cache, '/', '/alt', true)); } /** * @expectedException \RuntimeException */ public function testHandleWhenResponseIsNot200() { $ssi = new Ssi(); $response = new Response('foo'); $response->setStatusCode(404); $cache = $this->getCache(Request::create('/'), $response); $ssi->handle($cache, '/', '/alt', false); } public function testHandleWhenResponseIsNot200AndErrorsAreIgnored() { $ssi = new Ssi(); $response = new Response('foo'); $response->setStatusCode(404); $cache = $this->getCache(Request::create('/'), $response); $this->assertEquals('', $ssi->handle($cache, '/', '/alt', true)); } public function testHandleWhenResponseIsNot200AndAltIsPresent() { $ssi = new Ssi(); $response1 = new Response('foo'); $response1->setStatusCode(404); $response2 = new Response('bar'); $cache = $this->getCache(Request::create('/'), array($response1, $response2)); $this->assertEquals('bar', $ssi->handle($cache, '/', '/alt', false)); } protected function getCache($request, $response) { $cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('getRequest') ->will($this->returnValue($request)) ; if (is_array($response)) { $cache->expects($this->any()) ->method('handle') ->will(call_user_func_array(array($this, 'onConsecutiveCalls'), $response)) ; } else { $cache->expects($this->any()) ->method('handle') ->will($this->returnValue($response)) ; } return $cache; } } HttpCacheTest.php 0000604 00000162522 15224666447 0010004 0 ustar 00 <?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\Component\HttpKernel\Tests\HttpCache; use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpKernelInterface; /** * @group time-sensitive */ class HttpCacheTest extends HttpCacheTestCase { public function testTerminateDelegatesTerminationOnlyForTerminableInterface() { $storeMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\HttpCache\\StoreInterface') ->disableOriginalConstructor() ->getMock(); // does not implement TerminableInterface $kernel = new TestKernel(); $httpCache = new HttpCache($kernel, $storeMock); $httpCache->terminate(Request::create('/'), new Response()); $this->assertFalse($kernel->terminateCalled, 'terminate() is never called if the kernel class does not implement TerminableInterface'); // implements TerminableInterface $kernelMock = $this->getMockBuilder('Symfony\\Component\\HttpKernel\\Kernel') ->disableOriginalConstructor() ->setMethods(array('terminate', 'registerBundles', 'registerContainerConfiguration')) ->getMock(); $kernelMock->expects($this->once()) ->method('terminate'); $kernel = new HttpCache($kernelMock, $storeMock); $kernel->terminate(Request::create('/'), new Response()); } public function testPassesOnNonGetHeadRequests() { $this->setNextResponse(200); $this->request('POST', '/'); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertTraceContains('pass'); $this->assertFalse($this->response->headers->has('Age')); } public function testInvalidatesOnPostPutDeleteRequests() { foreach (array('post', 'put', 'delete') as $method) { $this->setNextResponse(200); $this->request($method, '/'); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertTraceContains('invalidate'); $this->assertTraceContains('pass'); } } public function testDoesNotCacheWithAuthorizationRequestHeaderAndNonPublicResponse() { $this->setNextResponse(200, array('ETag' => '"Foo"')); $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertEquals('private', $this->response->headers->get('Cache-Control')); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testDoesCacheWithAuthorizationRequestHeaderAndPublicResponse() { $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"Foo"')); $this->request('GET', '/', array('HTTP_AUTHORIZATION' => 'basic foobarbaz')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertTrue($this->response->headers->has('Age')); $this->assertEquals('public', $this->response->headers->get('Cache-Control')); } public function testDoesNotCacheWithCookieHeaderAndNonPublicResponse() { $this->setNextResponse(200, array('ETag' => '"Foo"')); $this->request('GET', '/', array(), array('foo' => 'bar')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertEquals('private', $this->response->headers->get('Cache-Control')); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testDoesNotCacheRequestsWithACookieHeader() { $this->setNextResponse(200); $this->request('GET', '/', array(), array('foo' => 'bar')); $this->assertHttpKernelIsCalled(); $this->assertResponseOk(); $this->assertEquals('private', $this->response->headers->get('Cache-Control')); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testRespondsWith304WhenIfModifiedSinceMatchesLastModified() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822), 'Content-Type' => 'text/plain'), 'Hello World'); $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); $this->assertEquals('', $this->response->headers->get('Content-Type')); $this->assertEmpty($this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testRespondsWith304WhenIfNoneMatchMatchesETag() { $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '12345', 'Content-Type' => 'text/plain'), 'Hello World'); $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345')); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); $this->assertEquals('', $this->response->headers->get('Content-Type')); $this->assertTrue($this->response->headers->has('ETag')); $this->assertEmpty($this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testRespondsWith304OnlyIfIfNoneMatchAndIfModifiedSinceBothMatch() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array(), '', function ($request, $response) use ($time) { $response->setStatusCode(200); $response->headers->set('ETag', '12345'); $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); $response->headers->set('Content-Type', 'text/plain'); $response->setContent('Hello World'); }); // only ETag matches $t = \DateTime::createFromFormat('U', time() - 3600); $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $t->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); // only Last-Modified matches $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '1234', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); // Both matches $this->request('GET', '/', array('HTTP_IF_NONE_MATCH' => '12345', 'HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsCalled(); $this->assertEquals(304, $this->response->getStatusCode()); } public function testIncrementsMaxAgeWhenNoDateIsSpecifiedEventWhenUsingETag() { $this->setNextResponse( 200, array( 'ETag' => '1234', 'Cache-Control' => 'public, s-maxage=60', ) ); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); sleep(2); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('fresh'); $this->assertEquals(2, $this->response->headers->get('Age')); } public function testValidatesPrivateResponsesCachedOnTheClient() { $this->setNextResponse(200, array(), '', function ($request, $response) { $etags = preg_split('/\s*,\s*/', $request->headers->get('IF_NONE_MATCH')); if ($request->cookies->has('authenticated')) { $response->headers->set('Cache-Control', 'private, no-store'); $response->setETag('"private tag"'); if (in_array('"private tag"', $etags)) { $response->setStatusCode(304); } else { $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/plain'); $response->setContent('private data'); } } else { $response->headers->set('Cache-Control', 'public'); $response->setETag('"public tag"'); if (in_array('"public tag"', $etags)) { $response->setStatusCode(304); } else { $response->setStatusCode(200); $response->headers->set('Content-Type', 'text/plain'); $response->setContent('public data'); } } }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('"public tag"', $this->response->headers->get('ETag')); $this->assertEquals('public data', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->request('GET', '/', array(), array('authenticated' => '')); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('"private tag"', $this->response->headers->get('ETag')); $this->assertEquals('private data', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('invalid'); $this->assertTraceNotContains('store'); } public function testStoresResponsesWhenNoCacheRequestDirectivePresent() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertHttpKernelIsCalled(); $this->assertTraceContains('store'); $this->assertTrue($this->response->headers->has('Age')); } public function testReloadsResponsesWhenCacheHitsButNoCacheRequestDirectivePresentWhenAllowReloadIsSetTrue() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) { ++$count; $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_reload'] = true; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Goodbye World', $this->response->getContent()); $this->assertTraceContains('reload'); $this->assertTraceContains('store'); } public function testDoesNotReloadResponsesWhenAllowReloadIsSetFalseDefault() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=10000'), '', function ($request, $response) use (&$count) { ++$count; $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_reload'] = false; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('reload'); $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'no-cache')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('reload'); } public function testRevalidatesFreshCacheEntryWhenMaxAgeRequestDirectiveIsExceededWhenAllowRevalidateOptionIsSetTrue() { $count = 0; $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) { ++$count; $response->headers->set('Cache-Control', 'public, max-age=10000'); $response->setETag($count); $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_revalidate'] = true; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Goodbye World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('invalid'); $this->assertTraceContains('store'); } public function testDoesNotRevalidateFreshCacheEntryWhenEnableRevalidateOptionIsSetFalseDefault() { $count = 0; $this->setNextResponse(200, array(), '', function ($request, $response) use (&$count) { ++$count; $response->headers->set('Cache-Control', 'public, max-age=10000'); $response->setETag($count); $response->setContent(1 == $count ? 'Hello World' : 'Goodbye World'); }); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('store'); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->cacheConfig['allow_revalidate'] = false; $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('stale'); $this->assertTraceNotContains('invalid'); $this->assertTraceContains('fresh'); $this->request('GET', '/', array('HTTP_CACHE_CONTROL' => 'max-age=0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceNotContains('stale'); $this->assertTraceNotContains('invalid'); $this->assertTraceContains('fresh'); } public function testFetchesResponseFromBackendWhenCacheMisses() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('miss'); $this->assertTrue($this->response->headers->has('Age')); } public function testDoesNotCacheSomeStatusCodeResponses() { foreach (array_merge(range(201, 202), range(204, 206), range(303, 305), range(400, 403), range(405, 409), range(411, 417), range(500, 505)) as $code) { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse($code, array('Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals($code, $this->response->getStatusCode()); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } } public function testDoesNotCacheResponsesWithExplicitNoStoreDirective() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'no-store')); $this->request('GET', '/'); $this->assertTraceNotContains('store'); $this->assertFalse($this->response->headers->has('Age')); } public function testDoesNotCacheResponsesWithoutFreshnessInformationOrAValidator() { $this->setNextResponse(); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceNotContains('store'); } public function testCachesResponsesWithExplicitNoCacheDirective() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Expires' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, no-cache')); $this->request('GET', '/'); $this->assertTraceContains('store'); $this->assertTrue($this->response->headers->has('Age')); } public function testCachesResponsesWithAnExpirationHeader() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); } public function testCachesResponsesWithAMaxAgeDirective() { $this->setNextResponse(200, array('Cache-Control' => 'public, max-age=5')); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); } public function testCachesResponsesWithASMaxAgeDirective() { $this->setNextResponse(200, array('Cache-Control' => 's-maxage=5')); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); } public function testCachesResponsesWithALastModifiedValidatorButNoFreshnessInformation() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Last-Modified' => $time->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testCachesResponsesWithAnETagValidatorButNoFreshnessInformation() { $this->setNextResponse(200, array('Cache-Control' => 'public', 'ETag' => '"123456"')); $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); } public function testHitsCachedResponsesWithExpiresHeader() { $time1 = \DateTime::createFromFormat('U', time() - 5); $time2 = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Date' => $time1->format(DATE_RFC2822), 'Expires' => $time2->format(DATE_RFC2822))); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2); $this->assertTrue($this->response->headers->get('Age') > 0); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testHitsCachedResponseWithMaxAgeDirective() { $time = \DateTime::createFromFormat('U', time() - 5); $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 'public, max-age=10')); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2); $this->assertTrue($this->response->headers->get('Age') > 0); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testDegradationWhenCacheLocked() { if ('\\' === DIRECTORY_SEPARATOR) { $this->markTestSkipped('Skips on windows to avoid permissions issues.'); } $this->cacheConfig['stale_while_revalidate'] = 10; // The prescence of Last-Modified makes this cacheable (because Response::isValidateable() then). $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=5', 'Last-Modified' => 'some while ago'), 'Old response'); $this->request('GET', '/'); // warm the cache // Now, lock the cache $concurrentRequest = Request::create('/', 'GET'); $this->store->lock($concurrentRequest); /* * After 10s, the cached response has become stale. Yet, we're still within the "stale_while_revalidate" * timeout so we may serve the stale response. */ sleep(10); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('stale-while-revalidate'); $this->assertEquals('Old response', $this->response->getContent()); /* * Another 10s later, stale_while_revalidate is over. Resort to serving the old response, but * do so with a "server unavailable" message. */ sleep(10); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(503, $this->response->getStatusCode()); $this->assertEquals('Old response', $this->response->getContent()); } public function testHitsCachedResponseWithSMaxAgeDirective() { $time = \DateTime::createFromFormat('U', time() - 5); $this->setNextResponse(200, array('Date' => $time->format(DATE_RFC2822), 'Cache-Control' => 's-maxage=10, max-age=0')); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue(strtotime($this->responses[0]->headers->get('Date')) - strtotime($this->response->headers->get('Date')) < 2); $this->assertTrue($this->response->headers->get('Age') > 0); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformation() { $this->setNextResponse(); $this->cacheConfig['default_ttl'] = 10; $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=10/', $this->response->headers->get('Cache-Control')); $this->cacheConfig['default_ttl'] = 10; $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=10/', $this->response->headers->get('Cache-Control')); } public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformationAndAfterTtlWasExpired() { $this->setNextResponse(); $this->cacheConfig['default_ttl'] = 2; $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); // expires the cache $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); $tmp = unserialize($values[0]); $time = \DateTime::createFromFormat('U', time() - 5); $tmp[0][1]['date'] = $time->format(DATE_RFC2822); $r = new \ReflectionObject($this->store); $m = $r->getMethod('save'); $m->setAccessible(true); $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp)); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('stale'); $this->assertTraceContains('invalid'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); $this->setNextResponse(); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); } public function testAssignsDefaultTtlWhenResponseHasNoFreshnessInformationAndAfterTtlWasExpiredWithStatus304() { $this->setNextResponse(); $this->cacheConfig['default_ttl'] = 2; $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); // expires the cache $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); $tmp = unserialize($values[0]); $time = \DateTime::createFromFormat('U', time() - 5); $tmp[0][1]['date'] = $time->format(DATE_RFC2822); $r = new \ReflectionObject($this->store); $m = $r->getMethod('save'); $m->setAccessible(true); $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp)); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('stale'); $this->assertTraceContains('valid'); $this->assertTraceContains('store'); $this->assertTraceNotContains('miss'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertRegExp('/s-maxage=2/', $this->response->headers->get('Cache-Control')); } public function testDoesNotAssignDefaultTtlWhenResponseHasMustRevalidateDirective() { $this->setNextResponse(200, array('Cache-Control' => 'must-revalidate')); $this->cacheConfig['default_ttl'] = 10; $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('miss'); $this->assertTraceNotContains('store'); $this->assertNotRegExp('/s-maxage/', $this->response->headers->get('Cache-Control')); $this->assertEquals('Hello World', $this->response->getContent()); } public function testFetchesFullResponseWhenCacheStaleAndNoValidatorsPresent() { $time = \DateTime::createFromFormat('U', time() + 5); $this->setNextResponse(200, array('Cache-Control' => 'public', 'Expires' => $time->format(DATE_RFC2822))); // build initial request $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Date')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertNotNull($this->response->headers->get('Age')); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); // go in and play around with the cached metadata directly ... $values = $this->getMetaStorageValues(); $this->assertCount(1, $values); $tmp = unserialize($values[0]); $time = \DateTime::createFromFormat('U', time()); $tmp[0][1]['expires'] = $time->format(DATE_RFC2822); $r = new \ReflectionObject($this->store); $m = $r->getMethod('save'); $m->setAccessible(true); $m->invoke($this->store, 'md'.hash('sha256', 'http://localhost/'), serialize($tmp)); // build subsequent request; should be found but miss due to freshness $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTrue($this->response->headers->get('Age') <= 1); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTraceContains('stale'); $this->assertTraceNotContains('fresh'); $this->assertTraceNotContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Hello World', $this->response->getContent()); } public function testValidatesCachedResponsesWithLastModifiedAndNoFreshnessInformation() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time) { $response->headers->set('Cache-Control', 'public'); $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); if ($time->format(DATE_RFC2822) == $request->headers->get('IF_MODIFIED_SINCE')) { $response->setStatusCode(304); $response->setContent(''); } }); // build initial request $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Last-Modified')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertTraceNotContains('stale'); // build subsequent request; should be found but miss due to freshness $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('Last-Modified')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTrue($this->response->headers->get('Age') <= 1); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('valid'); $this->assertTraceContains('store'); $this->assertTraceNotContains('miss'); } public function testValidatesCachedResponsesUseSameHttpMethod() { $test = $this; $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($test) { $test->assertSame('OPTIONS', $request->getMethod()); }); // build initial request $this->request('OPTIONS', '/'); // build subsequent request $this->request('OPTIONS', '/'); } public function testValidatesCachedResponsesWithETagAndNoFreshnessInformation() { $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) { $response->headers->set('Cache-Control', 'public'); $response->headers->set('ETag', '"12345"'); if ($response->getETag() == $request->headers->get('IF_NONE_MATCH')) { $response->setStatusCode(304); $response->setContent(''); } }); // build initial request $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('ETag')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); // build subsequent request; should be found but miss due to freshness $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertNotNull($this->response->headers->get('ETag')); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); $this->assertTrue($this->response->headers->get('Age') <= 1); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('valid'); $this->assertTraceContains('store'); $this->assertTraceNotContains('miss'); } public function testServesResponseWhileFreshAndRevalidatesWithLastModifiedInformation() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array(), 'Hello World', function (Request $request, Response $response) use ($time) { $response->setSharedMaxAge(10); $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); }); // prime the cache $this->request('GET', '/'); // next request before s-maxage has expired: Serve from cache // without hitting the backend $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); sleep(15); // expire the cache $this->setNextResponse(304, array(), '', function (Request $request, Response $response) use ($time) { $this->assertEquals($time->format(DATE_RFC2822), $request->headers->get('IF_MODIFIED_SINCE')); }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('valid'); } public function testReplacesCachedResponsesWhenValidationResultsInNon304Response() { $time = \DateTime::createFromFormat('U', time()); $count = 0; $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time, &$count) { $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); $response->headers->set('Cache-Control', 'public'); switch (++$count) { case 1: $response->setContent('first response'); break; case 2: $response->setContent('second response'); break; case 3: $response->setContent(''); $response->setStatusCode(304); break; } }); // first request should fetch from backend and store in cache $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('first response', $this->response->getContent()); // second request is validated, is invalid, and replaces cached entry $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('second response', $this->response->getContent()); // third response is validated, valid, and returns cached entry $this->request('GET', '/'); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('second response', $this->response->getContent()); $this->assertEquals(3, $count); } public function testPassesHeadRequestsThroughDirectlyOnPass() { $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) { $response->setContent(''); $response->setStatusCode(200); $this->assertEquals('HEAD', $request->getMethod()); }); $this->request('HEAD', '/', array('HTTP_EXPECT' => 'something ...')); $this->assertHttpKernelIsCalled(); $this->assertEquals('', $this->response->getContent()); } public function testUsesCacheToRespondToHeadRequestsWhenFresh() { $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) { $response->headers->set('Cache-Control', 'public, max-age=10'); $response->setContent('Hello World'); $response->setStatusCode(200); $this->assertNotEquals('HEAD', $request->getMethod()); }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('HEAD', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('', $this->response->getContent()); $this->assertEquals(strlen('Hello World'), $this->response->headers->get('Content-Length')); } public function testSendsNoContentWhenFresh() { $time = \DateTime::createFromFormat('U', time()); $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) use ($time) { $response->headers->set('Cache-Control', 'public, max-age=10'); $response->headers->set('Last-Modified', $time->format(DATE_RFC2822)); }); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals('Hello World', $this->response->getContent()); $this->request('GET', '/', array('HTTP_IF_MODIFIED_SINCE' => $time->format(DATE_RFC2822))); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(304, $this->response->getStatusCode()); $this->assertEquals('', $this->response->getContent()); } public function testInvalidatesCachedResponsesOnPost() { $this->setNextResponse(200, array(), 'Hello World', function ($request, $response) { if ('GET' == $request->getMethod()) { $response->setStatusCode(200); $response->headers->set('Cache-Control', 'public, max-age=500'); $response->setContent('Hello World'); } elseif ('POST' == $request->getMethod()) { $response->setStatusCode(303); $response->headers->set('Location', '/'); $response->headers->remove('Cache-Control'); $response->setContent(''); } }); // build initial request to enter into the cache $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); // make sure it is valid $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('fresh'); // now POST to same URL $this->request('POST', '/helloworld'); $this->assertHttpKernelIsCalled(); $this->assertEquals('/', $this->response->headers->get('Location')); $this->assertTraceContains('invalidate'); $this->assertTraceContains('pass'); $this->assertEquals('', $this->response->getContent()); // now make sure it was actually invalidated $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Hello World', $this->response->getContent()); $this->assertTraceContains('stale'); $this->assertTraceContains('invalid'); $this->assertTraceContains('store'); } public function testServesFromCacheWhenHeadersMatch() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) { $response->headers->set('Vary', 'Accept User-Agent Foo'); $response->headers->set('Cache-Control', 'public, max-age=10'); $response->headers->set('X-Response-Count', ++$count); $response->setContent($request->headers->get('USER_AGENT')); }); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertTraceContains('fresh'); $this->assertTraceNotContains('store'); $this->assertNotNull($this->response->headers->get('X-Content-Digest')); } public function testStoresMultipleResponsesWhenHeadersDiffer() { $count = 0; $this->setNextResponse(200, array('Cache-Control' => 'max-age=10000'), '', function ($request, $response) use (&$count) { $response->headers->set('Vary', 'Accept User-Agent Foo'); $response->headers->set('Cache-Control', 'public, max-age=10'); $response->headers->set('X-Response-Count', ++$count); $response->setContent($request->headers->get('USER_AGENT')); }); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertEquals(1, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0')); $this->assertEquals(200, $this->response->getStatusCode()); $this->assertTraceContains('miss'); $this->assertTraceContains('store'); $this->assertEquals('Bob/2.0', $this->response->getContent()); $this->assertEquals(2, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/1.0')); $this->assertTraceContains('fresh'); $this->assertEquals('Bob/1.0', $this->response->getContent()); $this->assertEquals(1, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_ACCEPT' => 'text/html', 'HTTP_USER_AGENT' => 'Bob/2.0')); $this->assertTraceContains('fresh'); $this->assertEquals('Bob/2.0', $this->response->getContent()); $this->assertEquals(2, $this->response->headers->get('X-Response-Count')); $this->request('GET', '/', array('HTTP_USER_AGENT' => 'Bob/2.0')); $this->assertTraceContains('miss'); $this->assertEquals('Bob/2.0', $this->response->getContent()); $this->assertEquals(3, $this->response->headers->get('X-Response-Count')); } public function testShouldCatchExceptions() { $this->catchExceptions(); $this->setNextResponse(); $this->request('GET', '/'); $this->assertExceptionsAreCaught(); } public function testShouldCatchExceptionsWhenReloadingAndNoCacheRequest() { $this->catchExceptions(); $this->setNextResponse(); $this->cacheConfig['allow_reload'] = true; $this->request('GET', '/', array(), array(), false, array('Pragma' => 'no-cache')); $this->assertExceptionsAreCaught(); } public function testShouldNotCatchExceptions() { $this->catchExceptions(false); $this->setNextResponse(); $this->request('GET', '/'); $this->assertExceptionsAreNotCaught(); } public function testEsiCacheSendsTheLowestTtl() { $responses = array( array( 'status' => 200, 'body' => '<esi:include src="/foo" /> <esi:include src="/bar" />', 'headers' => array( 'Cache-Control' => 's-maxage=300', 'Surrogate-Control' => 'content="ESI/1.0"', ), ), array( 'status' => 200, 'body' => 'Hello World!', 'headers' => array('Cache-Control' => 's-maxage=300'), ), array( 'status' => 200, 'body' => 'My name is Bobby.', 'headers' => array('Cache-Control' => 's-maxage=100'), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent()); // check for 100 or 99 as the test can be executed after a second change $this->assertTrue(in_array($this->response->getTtl(), array(99, 100))); } public function testEsiCacheForceValidation() { $responses = array( array( 'status' => 200, 'body' => '<esi:include src="/foo" /> <esi:include src="/bar" />', 'headers' => array( 'Cache-Control' => 's-maxage=300', 'Surrogate-Control' => 'content="ESI/1.0"', ), ), array( 'status' => 200, 'body' => 'Hello World!', 'headers' => array('ETag' => 'foobar'), ), array( 'status' => 200, 'body' => 'My name is Bobby.', 'headers' => array('Cache-Control' => 's-maxage=100'), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent()); $this->assertNull($this->response->getTtl()); $this->assertTrue($this->response->mustRevalidate()); $this->assertTrue($this->response->headers->hasCacheControlDirective('private')); $this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache')); } public function testEsiRecalculateContentLengthHeader() { $responses = array( array( 'status' => 200, 'body' => '<esi:include src="/foo" />', 'headers' => array( 'Content-Length' => 26, 'Cache-Control' => 's-maxage=300', 'Surrogate-Control' => 'content="ESI/1.0"', ), ), array( 'status' => 200, 'body' => 'Hello World!', 'headers' => array(), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertEquals('Hello World!', $this->response->getContent()); $this->assertEquals(12, $this->response->headers->get('Content-Length')); } public function testClientIpIsAlwaysLocalhostForForwardedRequests() { $this->setNextResponse(); $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1')); $this->assertEquals('127.0.0.1', $this->kernel->getBackendRequest()->server->get('REMOTE_ADDR')); } /** * @dataProvider getTrustedProxyData */ public function testHttpCacheIsSetAsATrustedProxy(array $existing, array $expected) { Request::setTrustedProxies($existing, Request::HEADER_X_FORWARDED_ALL); $this->setNextResponse(); $this->request('GET', '/', array('REMOTE_ADDR' => '10.0.0.1')); $this->assertEquals($expected, Request::getTrustedProxies()); } public function getTrustedProxyData() { return array( array(array(), array('127.0.0.1')), array(array('10.0.0.2'), array('10.0.0.2', '127.0.0.1')), array(array('10.0.0.2', '127.0.0.1'), array('10.0.0.2', '127.0.0.1')), ); } /** * @dataProvider getXForwardedForData */ public function testXForwarderForHeaderForForwardedRequests($xForwardedFor, $expected) { $this->setNextResponse(); $server = array('REMOTE_ADDR' => '10.0.0.1'); if (false !== $xForwardedFor) { $server['HTTP_X_FORWARDED_FOR'] = $xForwardedFor; } $this->request('GET', '/', $server); $this->assertEquals($expected, $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For')); } public function getXForwardedForData() { return array( array(false, '10.0.0.1'), array('10.0.0.2', '10.0.0.2, 10.0.0.1'), array('10.0.0.2, 10.0.0.3', '10.0.0.2, 10.0.0.3, 10.0.0.1'), ); } public function testXForwarderForHeaderForPassRequests() { $this->setNextResponse(); $server = array('REMOTE_ADDR' => '10.0.0.1'); $this->request('POST', '/', $server); $this->assertEquals('10.0.0.1', $this->kernel->getBackendRequest()->headers->get('X-Forwarded-For')); } public function testEsiCacheRemoveValidationHeadersIfEmbeddedResponses() { $time = \DateTime::createFromFormat('U', time()); $responses = array( array( 'status' => 200, 'body' => '<esi:include src="/hey" />', 'headers' => array( 'Surrogate-Control' => 'content="ESI/1.0"', 'ETag' => 'hey', 'Last-Modified' => $time->format(DATE_RFC2822), ), ), array( 'status' => 200, 'body' => 'Hey!', 'headers' => array(), ), ); $this->setNextResponses($responses); $this->request('GET', '/', array(), array(), true); $this->assertNull($this->response->getETag()); $this->assertNull($this->response->getLastModified()); } public function testDoesNotCacheOptionsRequest() { $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'get'); $this->request('GET', '/'); $this->assertHttpKernelIsCalled(); $this->setNextResponse(200, array('Cache-Control' => 'public, s-maxage=60'), 'options'); $this->request('OPTIONS', '/'); $this->assertHttpKernelIsCalled(); $this->request('GET', '/'); $this->assertHttpKernelIsNotCalled(); $this->assertSame('get', $this->response->getContent()); } } class TestKernel implements HttpKernelInterface { public $terminateCalled = false; public function terminate(Request $request, Response $response) { $this->terminateCalled = true; } public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { } } TestMultipleHttpKernel.php 0000604 00000004272 15224666447 0011732 0 ustar 00 <?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\Component\HttpKernel\Tests\HttpCache; use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\EventDispatcher\EventDispatcher; class TestMultipleHttpKernel extends HttpKernel implements ControllerResolverInterface, ArgumentResolverInterface { protected $bodies = array(); protected $statuses = array(); protected $headers = array(); protected $called = false; protected $backendRequest; public function __construct($responses) { foreach ($responses as $response) { $this->bodies[] = $response['body']; $this->statuses[] = $response['status']; $this->headers[] = $response['headers']; } parent::__construct(new EventDispatcher(), $this, null, $this); } public function getBackendRequest() { return $this->backendRequest; } public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false) { $this->backendRequest = $request; return parent::handle($request, $type, $catch); } public function getController(Request $request) { return array($this, 'callController'); } public function getArguments(Request $request, $controller) { return array($request); } public function callController(Request $request) { $this->called = true; $response = new Response(array_shift($this->bodies), array_shift($this->statuses), array_shift($this->headers)); return $response; } public function hasBeenCalled() { return $this->called; } public function reset() { $this->called = false; } } ResponseCacheStrategyTest.php 0000604 00000020223 15224666447 0012375 0 ustar 00 <?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * This code is partially based on the Rack-Cache library by Ryan Tomayko, * which is released under the MIT license. * (based on commit 02d2b48d75bcb63cf1c0c7149c077ad256542801) * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\Tests\HttpCache; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\HttpCache\ResponseCacheStrategy; class ResponseCacheStrategyTest extends TestCase { public function testMinimumSharedMaxAgeWins() { $cacheStrategy = new ResponseCacheStrategy(); $response1 = new Response(); $response1->setSharedMaxAge(60); $cacheStrategy->add($response1); $response2 = new Response(); $response2->setSharedMaxAge(3600); $cacheStrategy->add($response2); $response = new Response(); $response->setSharedMaxAge(86400); $cacheStrategy->update($response); $this->assertSame('60', $response->headers->getCacheControlDirective('s-maxage')); } public function testSharedMaxAgeNotSetIfNotSetInAnyEmbeddedRequest() { $cacheStrategy = new ResponseCacheStrategy(); $response1 = new Response(); $response1->setSharedMaxAge(60); $cacheStrategy->add($response1); $response2 = new Response(); $cacheStrategy->add($response2); $response = new Response(); $response->setSharedMaxAge(86400); $cacheStrategy->update($response); $this->assertFalse($response->headers->hasCacheControlDirective('s-maxage')); } public function testSharedMaxAgeNotSetIfNotSetInMasterRequest() { $cacheStrategy = new ResponseCacheStrategy(); $response1 = new Response(); $response1->setSharedMaxAge(60); $cacheStrategy->add($response1); $response2 = new Response(); $response2->setSharedMaxAge(3600); $cacheStrategy->add($response2); $response = new Response(); $cacheStrategy->update($response); $this->assertFalse($response->headers->hasCacheControlDirective('s-maxage')); } public function testMasterResponseNotCacheableWhenEmbeddedResponseRequiresValidation() { $cacheStrategy = new ResponseCacheStrategy(); $embeddedResponse = new Response(); $embeddedResponse->setLastModified(new \DateTime()); $cacheStrategy->add($embeddedResponse); $masterResponse = new Response(); $masterResponse->setSharedMaxAge(3600); $cacheStrategy->update($masterResponse); $this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache')); $this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate')); $this->assertFalse($masterResponse->isFresh()); } public function testValidationOnMasterResponseIsNotPossibleWhenItContainsEmbeddedResponses() { $cacheStrategy = new ResponseCacheStrategy(); // This master response uses the "validation" model $masterResponse = new Response(); $masterResponse->setLastModified(new \DateTime()); $masterResponse->setEtag('foo'); // Embedded response uses "expiry" model $embeddedResponse = new Response(); $masterResponse->setSharedMaxAge(3600); $cacheStrategy->add($embeddedResponse); $cacheStrategy->update($masterResponse); $this->assertFalse($masterResponse->isValidateable()); $this->assertFalse($masterResponse->headers->has('Last-Modified')); $this->assertFalse($masterResponse->headers->has('ETag')); $this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache')); $this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate')); } public function testMasterResponseWithValidationIsUnchangedWhenThereIsNoEmbeddedResponse() { $cacheStrategy = new ResponseCacheStrategy(); $masterResponse = new Response(); $masterResponse->setLastModified(new \DateTime()); $cacheStrategy->update($masterResponse); $this->assertTrue($masterResponse->isValidateable()); } public function testMasterResponseWithExpirationIsUnchangedWhenThereIsNoEmbeddedResponse() { $cacheStrategy = new ResponseCacheStrategy(); $masterResponse = new Response(); $masterResponse->setSharedMaxAge(3600); $cacheStrategy->update($masterResponse); $this->assertTrue($masterResponse->isFresh()); } public function testMasterResponseIsNotCacheableWhenEmbeddedResponseIsNotCacheable() { $cacheStrategy = new ResponseCacheStrategy(); $masterResponse = new Response(); $masterResponse->setSharedMaxAge(3600); // Public, cacheable /* This response has no validation or expiration information. That makes it uncacheable, it is always stale. (It does *not* make this private, though.) */ $embeddedResponse = new Response(); $this->assertFalse($embeddedResponse->isFresh()); // not fresh, as no lifetime is provided $cacheStrategy->add($embeddedResponse); $cacheStrategy->update($masterResponse); $this->assertTrue($masterResponse->headers->hasCacheControlDirective('no-cache')); $this->assertTrue($masterResponse->headers->hasCacheControlDirective('must-revalidate')); $this->assertFalse($masterResponse->isFresh()); } public function testEmbeddingPrivateResponseMakesMainResponsePrivate() { $cacheStrategy = new ResponseCacheStrategy(); $masterResponse = new Response(); $masterResponse->setSharedMaxAge(3600); // public, cacheable // The embedded response might for example contain per-user data that remains valid for 60 seconds $embeddedResponse = new Response(); $embeddedResponse->setPrivate(); $embeddedResponse->setMaxAge(60); // this would implicitly set "private" as well, but let's be explicit $cacheStrategy->add($embeddedResponse); $cacheStrategy->update($masterResponse); $this->assertTrue($masterResponse->headers->hasCacheControlDirective('private')); // Not sure if we should pass "max-age: 60" in this case, as long as the response is private and // that's the more conservative of both the master and embedded response...? } public function testResponseIsExiprableWhenEmbeddedResponseCombinesExpiryAndValidation() { /* When "expiration wins over validation" (https://symfony.com/doc/current/http_cache/validation.html) * and both the main and embedded response provide s-maxage, then the more restricting value of both * should be fine, regardless of whether the embedded response can be validated later on or must be * completely regenerated. */ $cacheStrategy = new ResponseCacheStrategy(); $masterResponse = new Response(); $masterResponse->setSharedMaxAge(3600); $embeddedResponse = new Response(); $embeddedResponse->setSharedMaxAge(60); $embeddedResponse->setEtag('foo'); $cacheStrategy->add($embeddedResponse); $cacheStrategy->update($masterResponse); $this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage')); } public function testResponseIsExpirableButNotValidateableWhenMasterResponseCombinesExpirationAndValidation() { $cacheStrategy = new ResponseCacheStrategy(); $masterResponse = new Response(); $masterResponse->setSharedMaxAge(3600); $masterResponse->setEtag('foo'); $masterResponse->setLastModified(new \DateTime()); $embeddedResponse = new Response(); $embeddedResponse->setSharedMaxAge(60); $cacheStrategy->add($embeddedResponse); $cacheStrategy->update($masterResponse); $this->assertSame('60', $masterResponse->headers->getCacheControlDirective('s-maxage')); $this->assertFalse($masterResponse->isValidateable()); } } TestHttpKernel.php 0000604 00000004547 15224666447 0010223 0 ustar 00 <?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\Component\HttpKernel\Tests\HttpCache; use Symfony\Component\HttpKernel\Controller\ArgumentResolverInterface; use Symfony\Component\HttpKernel\HttpKernel; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface; use Symfony\Component\EventDispatcher\EventDispatcher; class TestHttpKernel extends HttpKernel implements ControllerResolverInterface, ArgumentResolverInterface { protected $body; protected $status; protected $headers; protected $called = false; protected $customizer; protected $catch = false; protected $backendRequest; public function __construct($body, $status, $headers, \Closure $customizer = null) { $this->body = $body; $this->status = $status; $this->headers = $headers; $this->customizer = $customizer; parent::__construct(new EventDispatcher(), $this, null, $this); } public function getBackendRequest() { return $this->backendRequest; } public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = false) { $this->catch = $catch; $this->backendRequest = $request; return parent::handle($request, $type, $catch); } public function isCatchingExceptions() { return $this->catch; } public function getController(Request $request) { return array($this, 'callController'); } public function getArguments(Request $request, $controller) { return array($request); } public function callController(Request $request) { $this->called = true; $response = new Response($this->body, $this->status, $this->headers); if (null !== $customizer = $this->customizer) { $customizer($request, $response); } return $response; } public function hasBeenCalled() { return $this->called; } public function reset() { $this->called = false; } } EsiTest.php 0000604 00000021752 15224666447 0006660 0 ustar 00 <?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\Component\HttpKernel\Tests\HttpCache; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpKernel\HttpCache\Esi; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; class EsiTest extends TestCase { public function testHasSurrogateEsiCapability() { $esi = new Esi(); $request = Request::create('/'); $request->headers->set('Surrogate-Capability', 'abc="ESI/1.0"'); $this->assertTrue($esi->hasSurrogateCapability($request)); $request = Request::create('/'); $request->headers->set('Surrogate-Capability', 'foobar'); $this->assertFalse($esi->hasSurrogateCapability($request)); $request = Request::create('/'); $this->assertFalse($esi->hasSurrogateCapability($request)); } public function testAddSurrogateEsiCapability() { $esi = new Esi(); $request = Request::create('/'); $esi->addSurrogateCapability($request); $this->assertEquals('symfony="ESI/1.0"', $request->headers->get('Surrogate-Capability')); $esi->addSurrogateCapability($request); $this->assertEquals('symfony="ESI/1.0", symfony="ESI/1.0"', $request->headers->get('Surrogate-Capability')); } public function testAddSurrogateControl() { $esi = new Esi(); $response = new Response('foo <esi:include src="" />'); $esi->addSurrogateControl($response); $this->assertEquals('content="ESI/1.0"', $response->headers->get('Surrogate-Control')); $response = new Response('foo'); $esi->addSurrogateControl($response); $this->assertEquals('', $response->headers->get('Surrogate-Control')); } public function testNeedsEsiParsing() { $esi = new Esi(); $response = new Response(); $response->headers->set('Surrogate-Control', 'content="ESI/1.0"'); $this->assertTrue($esi->needsParsing($response)); $response = new Response(); $this->assertFalse($esi->needsParsing($response)); } public function testRenderIncludeTag() { $esi = new Esi(); $this->assertEquals('<esi:include src="/" onerror="continue" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', true)); $this->assertEquals('<esi:include src="/" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', false)); $this->assertEquals('<esi:include src="/" onerror="continue" />', $esi->renderIncludeTag('/')); $this->assertEquals('<esi:comment text="some comment" />'."\n".'<esi:include src="/" onerror="continue" alt="/alt" />', $esi->renderIncludeTag('/', '/alt', true, 'some comment')); } public function testProcessDoesNothingIfContentTypeIsNotHtml() { $esi = new Esi(); $request = Request::create('/'); $response = new Response(); $response->headers->set('Content-Type', 'text/plain'); $esi->process($request, $response); $this->assertFalse($response->headers->has('x-body-eval')); } public function testMultilineEsiRemoveTagsAreRemoved() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('<esi:remove> <a href="http://www.example.com">www.example.com</a> </esi:remove> Keep this'."<esi:remove>\n <a>www.example.com</a> </esi:remove> And this"); $esi->process($request, $response); $this->assertEquals(' Keep this And this', $response->getContent()); } public function testCommentTagsAreRemoved() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('<esi:comment text="some comment >" /> Keep this'); $esi->process($request, $response); $this->assertEquals(' Keep this', $response->getContent()); } public function testProcess() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo <esi:comment text="some comment" /><esi:include src="..." alt="alt" onerror="continue" />'); $esi->process($request, $response); $this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'...\', \'alt\', true) ?>'."\n", $response->getContent()); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $response = new Response('foo <esi:comment text="some comment" /><esi:include src="foo\'" alt="bar\'" onerror="continue" />'); $esi->process($request, $response); $this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'foo\\\'\', \'bar\\\'\', true) ?>'."\n", $response->getContent()); $response = new Response('foo <esi:include src="..." />'); $esi->process($request, $response); $this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent()); $response = new Response('foo <esi:include src="..."></esi:include>'); $esi->process($request, $response); $this->assertEquals('foo <?php echo $this->surrogate->handle($this, \'...\', \'\', false) ?>'."\n", $response->getContent()); } public function testProcessEscapesPhpTags() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('<?php <? <% <script language=php>'); $esi->process($request, $response); $this->assertEquals('<?php echo "<?"; ?>php <?php echo "<?"; ?> <?php echo "<%"; ?> <?php echo "<s"; ?>cript language=php>', $response->getContent()); } /** * @expectedException \RuntimeException */ public function testProcessWhenNoSrcInAnEsi() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo <esi:include />'); $esi->process($request, $response); } public function testProcessRemoveSurrogateControlHeader() { $esi = new Esi(); $request = Request::create('/'); $response = new Response('foo <esi:include src="..." />'); $response->headers->set('Surrogate-Control', 'content="ESI/1.0"'); $esi->process($request, $response); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $response->headers->set('Surrogate-Control', 'no-store, content="ESI/1.0"'); $esi->process($request, $response); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $this->assertEquals('no-store', $response->headers->get('surrogate-control')); $response->headers->set('Surrogate-Control', 'content="ESI/1.0", no-store'); $esi->process($request, $response); $this->assertEquals('ESI', $response->headers->get('x-body-eval')); $this->assertEquals('no-store', $response->headers->get('surrogate-control')); } public function testHandle() { $esi = new Esi(); $cache = $this->getCache(Request::create('/'), new Response('foo')); $this->assertEquals('foo', $esi->handle($cache, '/', '/alt', true)); } /** * @expectedException \RuntimeException */ public function testHandleWhenResponseIsNot200() { $esi = new Esi(); $response = new Response('foo'); $response->setStatusCode(404); $cache = $this->getCache(Request::create('/'), $response); $esi->handle($cache, '/', '/alt', false); } public function testHandleWhenResponseIsNot200AndErrorsAreIgnored() { $esi = new Esi(); $response = new Response('foo'); $response->setStatusCode(404); $cache = $this->getCache(Request::create('/'), $response); $this->assertEquals('', $esi->handle($cache, '/', '/alt', true)); } public function testHandleWhenResponseIsNot200AndAltIsPresent() { $esi = new Esi(); $response1 = new Response('foo'); $response1->setStatusCode(404); $response2 = new Response('bar'); $cache = $this->getCache(Request::create('/'), array($response1, $response2)); $this->assertEquals('bar', $esi->handle($cache, '/', '/alt', false)); } protected function getCache($request, $response) { $cache = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpCache\HttpCache')->setMethods(array('getRequest', 'handle'))->disableOriginalConstructor()->getMock(); $cache->expects($this->any()) ->method('getRequest') ->will($this->returnValue($request)) ; if (is_array($response)) { $cache->expects($this->any()) ->method('handle') ->will(call_user_func_array(array($this, 'onConsecutiveCalls'), $response)) ; } else { $cache->expects($this->any()) ->method('handle') ->will($this->returnValue($response)) ; } return $cache; } } HttpCacheTestCase.php 0000604 00000012242 15224666447 0010571 0 ustar 00 <?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\Component\HttpKernel\Tests\HttpCache; use PHPUnit\Framework\TestCase; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\HttpCache\Esi; use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Store; use Symfony\Component\HttpKernel\HttpKernelInterface; class HttpCacheTestCase extends TestCase { protected $kernel; protected $cache; protected $caches; protected $cacheConfig; protected $request; protected $response; protected $responses; protected $catch; protected $esi; /** * @var Store */ protected $store; protected function setUp() { $this->kernel = null; $this->cache = null; $this->esi = null; $this->caches = array(); $this->cacheConfig = array(); $this->request = null; $this->response = null; $this->responses = array(); $this->catch = false; $this->clearDirectory(sys_get_temp_dir().'/http_cache'); } protected function tearDown() { if ($this->cache) { $this->cache->getStore()->cleanup(); } $this->kernel = null; $this->cache = null; $this->caches = null; $this->request = null; $this->response = null; $this->responses = null; $this->cacheConfig = null; $this->catch = null; $this->esi = null; $this->clearDirectory(sys_get_temp_dir().'/http_cache'); } public function assertHttpKernelIsCalled() { $this->assertTrue($this->kernel->hasBeenCalled()); } public function assertHttpKernelIsNotCalled() { $this->assertFalse($this->kernel->hasBeenCalled()); } public function assertResponseOk() { $this->assertEquals(200, $this->response->getStatusCode()); } public function assertTraceContains($trace) { $traces = $this->cache->getTraces(); $traces = current($traces); $this->assertRegExp('/'.$trace.'/', implode(', ', $traces)); } public function assertTraceNotContains($trace) { $traces = $this->cache->getTraces(); $traces = current($traces); $this->assertNotRegExp('/'.$trace.'/', implode(', ', $traces)); } public function assertExceptionsAreCaught() { $this->assertTrue($this->kernel->isCatchingExceptions()); } public function assertExceptionsAreNotCaught() { $this->assertFalse($this->kernel->isCatchingExceptions()); } public function request($method, $uri = '/', $server = array(), $cookies = array(), $esi = false, $headers = array()) { if (null === $this->kernel) { throw new \LogicException('You must call setNextResponse() before calling request().'); } $this->kernel->reset(); $this->store = new Store(sys_get_temp_dir().'/http_cache'); $this->cacheConfig['debug'] = true; $this->esi = $esi ? new Esi() : null; $this->cache = new HttpCache($this->kernel, $this->store, $this->esi, $this->cacheConfig); $this->request = Request::create($uri, $method, array(), $cookies, array(), $server); $this->request->headers->add($headers); $this->response = $this->cache->handle($this->request, HttpKernelInterface::MASTER_REQUEST, $this->catch); $this->responses[] = $this->response; } public function getMetaStorageValues() { $values = array(); foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(sys_get_temp_dir().'/http_cache/md', \RecursiveDirectoryIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) { $values[] = file_get_contents($file); } return $values; } // A basic response with 200 status code and a tiny body. public function setNextResponse($statusCode = 200, array $headers = array(), $body = 'Hello World', \Closure $customizer = null) { $this->kernel = new TestHttpKernel($body, $statusCode, $headers, $customizer); } public function setNextResponses($responses) { $this->kernel = new TestMultipleHttpKernel($responses); } public function catchExceptions($catch = true) { $this->catch = $catch; } public static function clearDirectory($directory) { if (!is_dir($directory)) { return; } $fp = opendir($directory); while (false !== $file = readdir($fp)) { if (!in_array($file, array('.', '..'))) { if (is_link($directory.'/'.$file)) { unlink($directory.'/'.$file); } elseif (is_dir($directory.'/'.$file)) { self::clearDirectory($directory.'/'.$file); rmdir($directory.'/'.$file); } else { unlink($directory.'/'.$file); } } } closedir($fp); } }