-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCache.php
More file actions
66 lines (55 loc) · 1.95 KB
/
Cache.php
File metadata and controls
66 lines (55 loc) · 1.95 KB
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
<?php
declare(strict_types=1);
namespace LTS\MarkdownTools;
use LTS\MarkdownTools\MarkdownProcessor\RunConfig;
use RuntimeException;
final class Cache
{
public const MIN_CACHE_DIR_PATH_LENGTH = 10;
private string $cacheDir;
public function __construct(string $cacheDir = null)
{
$this->cacheDir = $cacheDir ?? RunConfig::VAR_PATH . '/cache';
$this->cacheDir .= '/';
$this->assertCacheDirExists();
}
public function getCache(string $prefix, string $item): ?string
{
$cachePath = $this->getCachePath($prefix, $item);
if (file_exists($cachePath)) {
$contents = \Safe\file_get_contents($cachePath);
if ($contents !== '') {
return $contents;
}
}
return null;
}
public function setCache(string $prefix, string $item, string $contents): void
{
$cachePath = $this->getCachePath($prefix, $item);
\Safe\file_put_contents(filename: $cachePath, data: $contents);
}
private function assertCacheDirExists(): void
{
if (strlen($this->cacheDir) < self::MIN_CACHE_DIR_PATH_LENGTH) {
throw new RuntimeException('CacheDir is very short and seems incorect: ' . $this->cacheDir);
}
if (!is_dir($this->cacheDir)) {
\Safe\mkdir(pathname: $this->cacheDir, recursive: true);
}
$this->cacheDir = \Safe\realpath($this->cacheDir) . '/';
}
private function getCachePath(string $prefix, string $item): string
{
$this->assertCacheDirExists();
/** @var string $prefix */
$prefix = \Safe\preg_replace('%\W%', '_', $prefix);
/** @var string $suffix */
$suffix = \Safe\preg_replace('%\W%', '_', $item);
if (strlen($suffix) > 100) {
$suffix = \Safe\substr($suffix, 0, 100) . md5($item);
}
$cacheFileName = "{$prefix}|{$suffix}.cache";
return $this->cacheDir . '/' . $cacheFileName;
}
}