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