|
| 1 | +<?php |
| 2 | +declare(strict_types = 1); |
| 3 | + |
| 4 | +namespace LanguageServer\Cache; |
| 5 | + |
| 6 | +use LanguageServer\LanguageClient; |
| 7 | +use Sabre\Event\Promise; |
| 8 | + |
| 9 | +/** |
| 10 | + * Caches content on the file system |
| 11 | + */ |
| 12 | +class FileSystemCache implements Cache |
| 13 | +{ |
| 14 | + /** |
| 15 | + * @var string |
| 16 | + */ |
| 17 | + public $cacheDir; |
| 18 | + |
| 19 | + public function __construct() |
| 20 | + { |
| 21 | + if (PHP_OS === 'WINNT') { |
| 22 | + $this->cacheDir = getenv('LOCALAPPDATA') . '\\PHP Language Server\\'; |
| 23 | + } else if (getenv('XDG_CACHE_HOME')) { |
| 24 | + $this->cacheDir = getenv('XDG_CACHE_HOME') . '/phpls/'; |
| 25 | + } else { |
| 26 | + $this->cacheDir = getenv('HOME') . '/.phpls/'; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Gets a value from the cache |
| 32 | + * |
| 33 | + * @param string $key |
| 34 | + * @return Promise <mixed> |
| 35 | + */ |
| 36 | + public function get(string $key): Promise |
| 37 | + { |
| 38 | + try { |
| 39 | + $file = $this->cacheDir . urlencode($key); |
| 40 | + if (!file_exists($file)) { |
| 41 | + return Promise\resolve(null); |
| 42 | + } |
| 43 | + return Promise\resolve(unserialize(file_get_contents($file))); |
| 44 | + } catch (\Exception $e) { |
| 45 | + return Promise\resolve(null); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + /** |
| 50 | + * Sets a value in the cache |
| 51 | + * |
| 52 | + * @param string $key |
| 53 | + * @param mixed $value |
| 54 | + * @return Promise |
| 55 | + */ |
| 56 | + public function set(string $key, $value): Promise |
| 57 | + { |
| 58 | + try { |
| 59 | + $file = $this->cacheDir . urlencode($key); |
| 60 | + if (!file_exists($this->cacheDir)) { |
| 61 | + mkdir($this->cacheDir); |
| 62 | + } |
| 63 | + file_put_contents($file, serialize($value)); |
| 64 | + } finally { |
| 65 | + return Promise\resolve(null); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments