refactor
[m6w6/seekat] / lib / API / Call / Cache.php
1 <?php
2
3 namespace seekat\API\Call;
4
5 use http\Client\Request;
6 use http\Client\Response;
7 use seekat\API\Call\Cache\Control;
8 use seekat\API\Call\Cache\Service;
9 use seekat\API\Call\Cache\Service\Hollow;
10
11
12 class Cache
13 {
14 /**
15 * @var Service
16 */
17 private $cache;
18
19 /**
20 * @param Service $cache
21 */
22 public function __construct(Service $cache = null) {
23 $this->cache = $cache ?? new Hollow;
24 }
25
26 /**
27 * Save call data
28 * @param Request $request
29 * @param Response $response
30 * @return bool
31 */
32 public function save(Request $request, Response $response) : bool {
33 $ctl = new Control($request);
34 if (!$ctl->isValid()) {
35 return false;
36 }
37
38 $time = time();
39 if ($time - 1 <= $response->getHeader("X-Cache-Time")) {
40 return true;
41 }
42 $response->setHeader("X-Cache-Time", $time);
43
44 return $this->cache->store($ctl->getKey(), $response);
45 }
46
47 /**
48 * Attempt to load call data
49 * @param Request $request
50 * @param Response $response out param
51 * @return bool
52 */
53 public function load(Request $request, Response &$response = null) : bool {
54 $ctl = new Control($request);
55 if (!$ctl->isValid()) {
56 return false;
57 }
58
59 if (!$this->cache->fetch($ctl->getKey(), $response)) {
60 return false;
61 }
62 if ($ctl->isStale($response)) {
63 if (($lmod = $response->getHeader("Last-Modified"))) {
64 $request->setOptions(["lastmodified" => strtotime($lmod)]);
65 }
66 if (($etag = $response->getHeader("ETag"))) {
67 $request->setOptions(["etag" => $etag]);
68 }
69 return false;
70 }
71 return true;
72 }
73
74 }