forked from vimeo/psalm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cache.php
92 lines (76 loc) · 2.02 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
<?php
namespace Psalm\Internal;
use Psalm\Config;
use Psalm\Internal\Provider\Providers;
use function file_exists;
use function file_put_contents;
use function gzdeflate;
use function gzinflate;
use function igbinary_serialize;
use function igbinary_unserialize;
use function serialize;
use function unlink;
use function unserialize;
use const LOCK_EX;
/**
* @internal
*/
class Cache
{
private Config $config;
public bool $use_igbinary;
public function __construct(Config $config)
{
$this->config = $config;
$this->use_igbinary = $config->use_igbinary;
}
/**
* @return array|object|string|null
*/
public function getItem(string $path)
{
if (!file_exists($path)) {
return null;
}
$cache = Providers::safeFileGetContents($path);
if ($this->config->use_gzip) {
$inflated = @gzinflate($cache);
if ($inflated !== false) {
$cache = $inflated;
}
}
if ($this->config->use_igbinary) {
/** @var object|false $unserialized */
$unserialized = igbinary_unserialize($cache);
} else {
/** @var object|false $unserialized */
$unserialized = @unserialize($cache);
}
return $unserialized !== false ? $unserialized : null;
}
public function deleteItem(string $path): void
{
if (file_exists($path)) {
unlink($path);
}
}
/**
* @param array|object|string $item
*/
public function saveItem(string $path, $item): void
{
if ($this->config->use_igbinary) {
$serialized = igbinary_serialize($item);
} else {
$serialized = serialize($item);
}
if ($this->config->use_gzip) {
$serialized = gzdeflate($serialized);
}
file_put_contents($path, $serialized, LOCK_EX);
}
public function getCacheDirectory(): ?string
{
return $this->config->getCacheDirectory();
}
}