Code Coverage
 
Classes and Traits
Functions and Methods
Lines
Total
0.00% covered (danger)
0.00%
0 / 1
66.67% covered (warning)
66.67%
14 / 21
CRAP
88.54% covered (warning)
88.54%
139 / 157
Store
0.00% covered (danger)
0.00%
0 / 1
66.67% covered (warning)
66.67%
14 / 21
83.48
88.54% covered (warning)
88.54%
139 / 157
 __construct
0.00% covered (danger)
0.00%
0 / 1
4.07
83.33% covered (warning)
83.33%
5 / 6
 cleanup
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
5 / 5
 lock
0.00% covered (danger)
0.00%
0 / 1
6.03
90.91% covered (success)
90.91%
10 / 11
 unlock
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
7 / 7
 isLocked
0.00% covered (danger)
0.00%
0 / 1
3.01
90.00% covered (success)
90.00%
9 / 10
 lookup
100.00% covered (success)
100.00%
1 / 1
7
100.00% covered (success)
100.00%
14 / 14
 write
0.00% covered (danger)
0.00%
0 / 1
8.06
90.48% covered (success)
90.48%
19 / 21
 generateContentDigest
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 invalidate
0.00% covered (danger)
0.00%
0 / 1
5.09
84.62% covered (warning)
84.62%
11 / 13
 requestsMatch
100.00% covered (success)
100.00%
1 / 1
7
100.00% covered (success)
100.00%
9 / 9
 getMetadata
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
3 / 3
 purge
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
5 / 5
 doPurge
0.00% covered (danger)
0.00%
0 / 1
3.33
66.67% covered (warning)
66.67%
6 / 9
 load
100.00% covered (success)
100.00%
1 / 1
4
100.00% covered (success)
100.00%
2 / 2
 save
0.00% covered (danger)
0.00%
0 / 1
14.15
70.37% covered (warning)
70.37%
19 / 27
 getPath
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 generateCacheKey
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 getCacheKey
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
3 / 3
 persistRequest
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
1 / 1
 persistResponse
100.00% covered (success)
100.00%
1 / 1
1
100.00% covered (success)
100.00%
3 / 3
 restoreResponse
100.00% covered (success)
100.00%
1 / 1
2
100.00% covered (success)
100.00%
5 / 5
<?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;
    /**
     * @throws \RuntimeException
     */
    public function __construct(string $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 = [];
    }
    /**
     * Cleanups storage.
     */
    public function cleanup()
    {
        // unlock everything
        foreach ($this->locks as $lock) {
            flock($lock, LOCK_UN);
            fclose($lock);
        }
        $this->locks = [];
    }
    /**
     * Tries to lock the cache for a given Request, without blocking.
     *
     * @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.
     *
     * @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.
     *
     * @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 null;
        }
        // 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 null;
        }
        $headers = $match[1];
        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.
        return null;
    }
    /**
     * 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.
     *
     * @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);
        $digest = $this->generateContentDigest($response);
        $response->headers->set('X-Content-Digest', $digest);
        if (!$this->save($digest, $response->getContent(), false)) {
            throw new \RuntimeException('Unable to store the entity.');
        }
        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 = [];
        $vary = $response->headers->get('vary');
        foreach ($this->getMetadata($key) as $entry) {
            if (!isset($entry[1]['vary'][0])) {
                $entry[1]['vary'] = [''];
            }
            if ($entry[1]['vary'][0] != $vary || !$this->requestsMatch($vary ?? '', $entry[0], $storedEnv)) {
                $entries[] = $entry;
            }
        }
        $headers = $this->persistResponse($response);
        unset($headers['age']);
        array_unshift($entries, [$storedEnv, $headers]);
        if (!$this->save($key, serialize($entries))) {
            throw new \RuntimeException('Unable to store the metadata.');
        }
        return $key;
    }
    /**
     * Returns content digest for $response.
     *
     * @return string
     */
    protected function generateContentDigest(Response $response)
    {
        return 'en'.hash('sha256', $response->getContent());
    }
    /**
     * Invalidates all cache entries that match the request.
     *
     * @throws \RuntimeException
     */
    public function invalidate(Request $request)
    {
        $modified = false;
        $key = $this->getCacheKey($request);
        $entries = [];
        foreach ($this->getMetadata($key) as $entry) {
            $response = $this->restoreResponse($entry[1]);
            if ($response->isFresh()) {
                $response->expire();
                $modified = true;
                $entries[] = [$entry[0], $this->persistResponse($response)];
            } else {
                $entries[] = $entry;
            }
        }
        if ($modified && !$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|null $vary A Response vary header
     * @param array       $env1 A Request HTTP header array
     * @param array       $env2 A Request HTTP header array
     */
    private function requestsMatch(?string $vary, array $env1, array $env2): bool
    {
        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.
     */
    private function getMetadata(string $key): array
    {
        if (!$entries = $this->load($key)) {
            return [];
        }
        return unserialize($entries);
    }
    /**
     * Purges data for the given URL.
     *
     * This method purges both the HTTP and the HTTPS version of the cache entry.
     *
     * @return bool true if the URL exists with either HTTP or HTTPS scheme and has been purged, false otherwise
     */
    public function purge(string $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.
     */
    private function doPurge(string $url): bool
    {
        $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.
     */
    private function load(string $key): ?string
    {
        $path = $this->getPath($key);
        return file_exists($path) && false !== ($contents = file_get_contents($path)) ? $contents : null;
    }
    /**
     * Save data for the given key.
     */
    private function save(string $key, string $data, bool $overwrite = true): bool
    {
        $path = $this->getPath($key);
        if (!$overwrite && file_exists($path)) {
            return true;
        }
        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')) {
                @unlink($tmpFile);
                return false;
            }
            @fwrite($fp, $data);
            @fclose($fp);
            if ($data != file_get_contents($tmpFile)) {
                @unlink($tmpFile);
                return false;
            }
            if (false === @rename($tmpFile, $path)) {
                @unlink($tmpFile);
                return false;
            }
        }
        @chmod($path, 0666 & ~umask());
        return true;
    }
    public <