This repository was archived by the owner on Jan 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathCache.php
97 lines (75 loc) · 1.91 KB
/
Cache.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace SDK;
class Cache
{
protected $id;
protected $hash;
public function __construct(string $id)
{/*{{{*/
$this->id = $id;
$this->hash = md5($id);
/* XXX pass as arg, fine for now. */
}/*}}}*/
protected function getCacheablePath(string $path, bool $relative = false) : string
{/*{{{*/
if ($relative) {
$dir = Config::getCacheDir();
$name = $path;
} else {
$dir = dirname($path);
$name = basename($path);
}
return $dir . DIRECTORY_SEPARATOR . $this->hash . "." . $name;
}/*}}}*/
public function fileIsCached(string $path, bool $relative = false) : bool
{/*{{{*/
return file_exists($this->getCacheablePath($path, $relative));
}/*}}}*/
/* TODO Sometimes a timestamp comparison might make sense. */
public function cachedContentDiffers(string $path, string $content, bool $relative = false) : bool
{/*{{{*/
$p = $this->getCacheablePath($path, $relative);
if (!file_exists($p)) {
return true;
}
$old_sum = md5_file($p);
$new_sum = md5($content);
return $old_sum !== $new_sum;
}/*}}}*/
public function cacheContent(string $path, string $content, bool $relative = false) : void
{/*{{{*/
$p = $this->getCacheablePath($path, $relative);
$to_write = strlen($content);
$wrote = 0;
$fd = fopen($p, "wb");
flock($fd, LOCK_EX);
do {
$got = fwrite($fd, substr($content, $wrote));
if (false === $got) {
break;
}
$wrote += $got;
} while ($wrote < $to_write);
flock($fd, LOCK_UN);
fclose($fd);
if ($to_write !== $wrote) {
throw new Exception("Couldn't cache '$p'");
}
}/*}}}*/
public function getCachedContent(string $path, bool $relative = false) : ?string
{/*{{{*/
$p = $this->getCacheablePath($path, $relative);
if ($this->isFileCached($p)) {
return file_get_contents($p);
}
return NULL;
}/*}}}*/
}
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: sw=4 ts=4 fdm=marker
* vim<600: sw=4 ts=4
*/