| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler; |
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
class MemcachedSessionHandler extends AbstractSessionHandler |
| 23 |
{ |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
private int|\Closure|null $ttl; |
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
private string $prefix; |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
|
| 42 |
|
| 43 |
public function __construct( |
| 44 |
private \Memcached $memcached, |
| 45 |
array $options = [], |
| 46 |
) { |
| 47 |
if ($diff = array_diff(array_keys($options), ['prefix', 'expiretime', 'ttl'])) { |
| 48 |
throw new \InvalidArgumentException(\sprintf('The following options are not supported "%s".', implode(', ', $diff))); |
| 49 |
} |
| 50 |
|
| 51 |
$this->ttl = $options['expiretime'] ?? $options['ttl'] ?? null; |
| 52 |
$this->prefix = $options['prefix'] ?? 'sf2s'; |
| 53 |
} |
| 54 |
|
| 55 |
public function close(): bool |
| 56 |
{ |
| 57 |
return $this->memcached->quit(); |
| 58 |
} |
| 59 |
|
| 60 |
protected function doRead(#[\SensitiveParameter] string $sessionId): string |
| 61 |
{ |
| 62 |
return $this->memcached->get($this->prefix.$sessionId) ?: ''; |
| 63 |
} |
| 64 |
|
| 65 |
public function updateTimestamp(#[\SensitiveParameter] string $sessionId, string $data): bool |
| 66 |
{ |
| 67 |
$this->memcached->touch($this->prefix.$sessionId, $this->getCompatibleTtl()); |
| 68 |
|
| 69 |
return true; |
| 70 |
} |
| 71 |
|
| 72 |
protected function doWrite(#[\SensitiveParameter] string $sessionId, string $data): bool |
| 73 |
{ |
| 74 |
return $this->memcached->set($this->prefix.$sessionId, $data, $this->getCompatibleTtl()); |
| 75 |
} |
| 76 |
|
| 77 |
private function getCompatibleTtl(): int |
| 78 |
{ |
| 79 |
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'); |
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
if ($ttl > 60 * 60 * 24 * 30) { |
| 84 |
$ttl += time(); |
| 85 |
} |
| 86 |
|
| 87 |
return $ttl; |
| 88 |
} |
| 89 |
|
| 90 |
protected function doDestroy(#[\SensitiveParameter] string $sessionId): bool |
| 91 |
{ |
| 92 |
$result = $this->memcached->delete($this->prefix.$sessionId); |
| 93 |
|
| 94 |
return $result || \Memcached::RES_NOTFOUND == $this->memcached->getResultCode(); |
| 95 |
} |
| 96 |
|
| 97 |
public function gc(int $maxlifetime): int|false |
| 98 |
{ |
| 99 |
|
| 100 |
return 0; |
| 101 |
} |
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 106 |
protected function getMemcached(): \Memcached |
| 107 |
{ |
| 108 |
return $this->memcached; |
| 109 |
} |
| 110 |
} |