|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/* |
| 6 | + * This file is part of the official PHP MCP SDK. |
| 7 | + * |
| 8 | + * A collaboration between Symfony and the PHP Foundation. |
| 9 | + * |
| 10 | + * For the full copyright and license information, please view the LICENSE |
| 11 | + * file that was distributed with this source code. |
| 12 | + */ |
| 13 | + |
| 14 | +namespace Mcp\Server\Session; |
| 15 | + |
| 16 | +use Psr\SimpleCache\CacheInterface; |
| 17 | +use Symfony\Component\Uid\Uuid; |
| 18 | + |
| 19 | +/** |
| 20 | + * PSR-16 compliant cache-based session store. |
| 21 | + * |
| 22 | + * This implementation uses any PSR-16 compliant cache as the storage backend |
| 23 | + * for session data. Each session is stored with a prefixed key using the session ID. |
| 24 | + */ |
| 25 | +class Psr16StoreSession implements SessionStoreInterface |
| 26 | +{ |
| 27 | + public function __construct( |
| 28 | + private readonly CacheInterface $cache, |
| 29 | + private readonly string $prefix = 'mcp-', |
| 30 | + private readonly int $ttl = 3600, |
| 31 | + ) { |
| 32 | + } |
| 33 | + |
| 34 | + public function exists(Uuid $id): bool |
| 35 | + { |
| 36 | + try { |
| 37 | + return $this->cache->has($this->getKey($id)); |
| 38 | + } catch (\Throwable) { |
| 39 | + return false; |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public function read(Uuid $id): string|false |
| 44 | + { |
| 45 | + try { |
| 46 | + return $this->cache->get($this->getKey($id), false); |
| 47 | + } catch (\Throwable) { |
| 48 | + return false; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + public function write(Uuid $id, string $data): bool |
| 53 | + { |
| 54 | + try { |
| 55 | + return $this->cache->set($this->getKey($id), $data, $this->ttl); |
| 56 | + } catch (\Throwable) { |
| 57 | + return false; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + public function destroy(Uuid $id): bool |
| 62 | + { |
| 63 | + try { |
| 64 | + return $this->cache->delete($this->getKey($id)); |
| 65 | + } catch (\Throwable) { |
| 66 | + return false; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + public function gc(): array |
| 71 | + { |
| 72 | + return []; |
| 73 | + } |
| 74 | + |
| 75 | + private function getKey(Uuid $id): string |
| 76 | + { |
| 77 | + return $this->prefix.$id; |
| 78 | + } |
| 79 | +} |
0 commit comments