PageRenderTime 52ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/htdocs/symfony/2.0.0pr4/src/vendor/symfony/src/Symfony/Component/HttpKernel/Cache/Store.php

https://github.com/ad2joe/php-framework-benchmarks
PHP | 406 lines | 214 code | 57 blank | 135 comment | 34 complexity | 9a08c5b606a91b410f0fe4c4c01ff08b MD5 | raw file
  1. <?php
  2. namespace Symfony\Component\HttpKernel\Cache;
  3. use Symfony\Component\HttpFoundation\Request;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\HeaderBag;
  6. /*
  7. * This file is part of the Symfony framework.
  8. *
  9. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  10. *
  11. * This code is partially based on the Rack-Cache library by Ryan Tomayko,
  12. * which is released under the MIT license.
  13. *
  14. * This source file is subject to the MIT license that is bundled
  15. * with this source code in the file LICENSE.
  16. */
  17. /**
  18. * Store implements all the logic for storing cache metadata (Request and Response headers).
  19. *
  20. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  21. */
  22. class Store
  23. {
  24. protected $root;
  25. protected $keyCache;
  26. protected $locks;
  27. /**
  28. * Constructor.
  29. *
  30. * @param string $root The path to the cache directory
  31. */
  32. public function __construct($root)
  33. {
  34. $this->root = $root;
  35. if (!is_dir($this->root)) {
  36. mkdir($this->root, 0777, true);
  37. }
  38. $this->keyCache = new \SplObjectStorage();
  39. $this->locks = array();
  40. }
  41. public function __destruct()
  42. {
  43. // unlock everything
  44. foreach ($this->locks as $lock) {
  45. @unlink($lock);
  46. }
  47. $error = error_get_last();
  48. if (1 === $error['type'] && false === headers_sent()) {
  49. // send a 503
  50. header('HTTP/1.0 503 Service Unavailable');
  51. header('Retry-After: 10');
  52. echo '503 Service Unavailable';
  53. }
  54. }
  55. /**
  56. * Locks the cache for a given Request.
  57. *
  58. * @param Request $request A Request instance
  59. *
  60. * @return Boolean|string true if the lock is acquired, the path to the current lock otherwise
  61. */
  62. public function lock(Request $request)
  63. {
  64. if (false !== $lock = @fopen($path = $this->getPath($this->getCacheKey($request).'.lck'), 'x')) {
  65. fclose($lock);
  66. $this->locks[] = $path;
  67. return true;
  68. } else {
  69. return $path;
  70. }
  71. }
  72. /**
  73. * Releases the lock for the given Request.
  74. *
  75. * @param Request $request A Request instance
  76. */
  77. public function unlock(Request $request)
  78. {
  79. return @unlink($this->getPath($this->getCacheKey($request).'.lck'));
  80. }
  81. /**
  82. * Locates a cached Response for the Request provided.
  83. *
  84. * @param Request $request A Request instance
  85. *
  86. * @return Response|null A Response instance, or null if no cache entry was found
  87. */
  88. public function lookup(Request $request)
  89. {
  90. $key = $this->getCacheKey($request);
  91. if (!$entries = $this->getMetadata($key)) {
  92. return null;
  93. }
  94. // find a cached entry that matches the request.
  95. $match = null;
  96. foreach ($entries as $entry) {
  97. if ($this->requestsMatch(isset($entry[1]['vary']) ? $entry[1]['vary'][0] : '', $request->headers->all(), $entry[0]))
  98. {
  99. $match = $entry;
  100. break;
  101. }
  102. }
  103. if (null === $match) {
  104. return null;
  105. }
  106. list($req, $headers) = $match;
  107. if (file_exists($body = $this->getPath($headers['x-content-digest'][0]))) {
  108. return $this->restoreResponse($headers, $body);
  109. } else {
  110. // TODO the metaStore referenced an entity that doesn't exist in
  111. // the entityStore. We definitely want to return nil but we should
  112. // also purge the entry from the meta-store when this is detected.
  113. return null;
  114. }
  115. }
  116. /**
  117. * Writes a cache entry to the store for the given Request and Response.
  118. *
  119. * Existing entries are read and any that match the response are removed. This
  120. * method calls write with the new list of cache entries.
  121. *
  122. * @param Request $request A Request instance
  123. * @param Response $response A Response instance
  124. *
  125. * @return string The key under which the response is stored
  126. */
  127. public function write(Request $request, Response $response)
  128. {
  129. $key = $this->getCacheKey($request);
  130. $storedEnv = $this->persistRequest($request);
  131. // write the response body to the entity store if this is the original response
  132. if (!$response->headers->has('X-Content-Digest')) {
  133. $digest = 'en'.sha1($response->getContent());
  134. if (false === $this->save($digest, $response->getContent())) {
  135. throw new \RuntimeException(sprintf('Unable to store the entity (%s).', $e->getMessage()));
  136. }
  137. $response->headers->set('X-Content-Digest', $digest);
  138. if (!$response->headers->has('Transfer-Encoding')) {
  139. $response->headers->set('Content-Length', strlen($response->getContent()));
  140. }
  141. }
  142. // read existing cache entries, remove non-varying, and add this one to the list
  143. $entries = array();
  144. $vary = $response->headers->get('vary');
  145. foreach ($this->getMetadata($key) as $entry) {
  146. if (!isset($entry[1]['vary'])) {
  147. $entry[1]['vary'] = array('');
  148. }
  149. if ($vary != $entry[1]['vary'][0] || !$this->requestsMatch($vary, $entry[0], $storedEnv)) {
  150. $entries[] = $entry;
  151. }
  152. }
  153. $headers = $this->persistResponse($response);
  154. unset($headers['age']);
  155. array_unshift($entries, array($storedEnv, $headers));
  156. if (false === $this->save($key, serialize($entries))) {
  157. throw new \RuntimeException(sprintf('Unable to store the metadata (%s).', $e->getMessage()));
  158. }
  159. return $key;
  160. }
  161. /**
  162. * Invalidates all cache entries that match the request.
  163. *
  164. * @param Request $request A Request instance
  165. */
  166. public function invalidate(Request $request)
  167. {
  168. $modified = false;
  169. $key = $this->getCacheKey($request);
  170. $entries = array();
  171. foreach ($this->getMetadata($key) as $entry) {
  172. $response = $this->restoreResponse($entry[1]);
  173. if ($response->isFresh()) {
  174. $response->expire();
  175. $modified = true;
  176. $entries[] = array($entry[0], $this->persistResponse($response));
  177. } else {
  178. $entries[] = $entry;
  179. }
  180. }
  181. if ($modified) {
  182. if (false === $this->save($key, serialize($entries))) {
  183. throw new \RuntimeException('Unable to store the metadata.');
  184. }
  185. }
  186. // As per the RFC, invalidate Location and Content-Location URLs if present
  187. foreach (array('Location', 'Content-Location') as $header) {
  188. if ($uri = $request->headers->get($header)) {
  189. $subRequest = Request::create($uri, 'get', array(), array(), array(), $request->server->all());
  190. $this->invalidate($subRequest);
  191. }
  192. }
  193. }
  194. /**
  195. * Determines whether two Request HTTP header sets are non-varying based on
  196. * the vary response header value provided.
  197. *
  198. * @param string $vary A Response vary header
  199. * @param array $env1 A Request HTTP header array
  200. * @param array $env2 A Request HTTP header array
  201. *
  202. * @return Boolean true if the the two environments match, false otherwise
  203. */
  204. public function requestsMatch($vary, $env1, $env2)
  205. {
  206. if (empty($vary)) {
  207. return true;
  208. }
  209. foreach (preg_split('/[\s,]+/', $vary) as $header) {
  210. $key = strtr(strtolower($header), '_', '-');
  211. $v1 = isset($env1[$key]) ? $env1[$key] : null;
  212. $v2 = isset($env2[$key]) ? $env2[$key] : null;
  213. if ($v1 !== $v2) {
  214. return false;
  215. }
  216. }
  217. return true;
  218. }
  219. /**
  220. * Gets all data associated with the given key.
  221. *
  222. * Use this method only if you know what you are doing.
  223. *
  224. * @param string $key The store key
  225. *
  226. * @return array An array of data associated with the key
  227. */
  228. public function getMetadata($key)
  229. {
  230. if (false === $entries = $this->load($key)) {
  231. return array();
  232. }
  233. return unserialize($entries);
  234. }
  235. /**
  236. * Purges data for the given URL.
  237. *
  238. * @param string $url A URL
  239. *
  240. * @return Boolean true if the URL exists and has been purged, false otherwise
  241. */
  242. public function purge($url)
  243. {
  244. if (file_exists($path = $this->getPath($this->getCacheKey(Request::create($url))))) {
  245. unlink($path);
  246. return true;
  247. }
  248. return false;
  249. }
  250. /**
  251. * Loads data for the given key.
  252. *
  253. * Don't use this method directly, use lookup() instead
  254. *
  255. * @param string $key The store key
  256. *
  257. * @return string The data associated with the key
  258. */
  259. public function load($key)
  260. {
  261. $path = $this->getPath($key);
  262. return file_exists($path) ? file_get_contents($path) : false;
  263. }
  264. /**
  265. * Save data for the given key.
  266. *
  267. * Don't use this method directly, use write() instead
  268. *
  269. * @param string $key The store key
  270. * @param string $data The data to store
  271. */
  272. public function save($key, $data)
  273. {
  274. $path = $this->getPath($key);
  275. if (!is_dir(dirname($path))) {
  276. mkdir(dirname($path), 0777, true);
  277. }
  278. $tmpFile = tempnam(dirname($path), basename($path));
  279. if (false === $fp = @fopen($tmpFile, 'wb')) {
  280. return false;
  281. }
  282. @fwrite($fp, $data);
  283. @fclose($fp);
  284. if ($data != file_get_contents($tmpFile)) {
  285. return false;
  286. }
  287. if (false === @rename($tmpFile, $path)) {
  288. return false;
  289. }
  290. chmod($path, 0644);
  291. }
  292. public function getPath($key)
  293. {
  294. return $this->root.DIRECTORY_SEPARATOR.substr($key, 0, 2).DIRECTORY_SEPARATOR.substr($key, 2, 4).DIRECTORY_SEPARATOR.substr($key, 4);
  295. }
  296. /**
  297. * Returns a cache key for the given Request.
  298. *
  299. * @param Request $request A Request instance
  300. *
  301. * @return string A key for the given Request
  302. */
  303. public function getCacheKey(Request $request)
  304. {
  305. if (isset($this->keyCache[$request])) {
  306. return $this->keyCache[$request];
  307. }
  308. return $this->keyCache[$request] = 'md'.sha1($request->getUri());
  309. }
  310. /**
  311. * Persists the Request HTTP headers.
  312. *
  313. * @param Request $request A Request instance
  314. *
  315. * @return array An array of HTTP headers
  316. */
  317. protected function persistRequest(Request $request)
  318. {
  319. return $request->headers->all();
  320. }
  321. /**
  322. * Persists the Response HTTP headers.
  323. *
  324. * @param Response $response A Response instance
  325. *
  326. * @return array An array of HTTP headers
  327. */
  328. protected function persistResponse(Response $response)
  329. {
  330. $headers = $response->headers->all();
  331. $headers['X-Status'] = array($response->getStatusCode());
  332. return $headers;
  333. }
  334. /**
  335. * Restores a Response from the HTTP headers and body.
  336. *
  337. * @param array $headers An array of HTTP headers for the Response
  338. * @param string $body The Response body
  339. */
  340. protected function restoreResponse($headers, $body = null)
  341. {
  342. $status = $headers['X-Status'][0];
  343. unset($headers['X-Status']);
  344. if (null !== $body) {
  345. $headers['X-Body-File'] = array($body);
  346. }
  347. return new Response($body, $status, $headers);
  348. }
  349. }