123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136 |
- <?php
- namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
- use Predis\Response\ErrorInterface;
- use Symfony\Component\Cache\Traits\RedisClusterProxy;
- use Symfony\Component\Cache\Traits\RedisProxy;
- class RedisSessionHandler extends AbstractSessionHandler
- {
- private $redis;
-
- private $prefix;
-
- private $ttl;
-
- public function __construct($redis, array $options = [])
- {
- if (
- !$redis instanceof \Redis &&
- !$redis instanceof \RedisArray &&
- !$redis instanceof \RedisCluster &&
- !$redis instanceof \Predis\ClientInterface &&
- !$redis instanceof RedisProxy &&
- !$redis instanceof RedisClusterProxy
- ) {
- throw new \InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($redis)));
- }
- if ($diff = array_diff(array_keys($options), ['prefix', 'ttl'])) {
- throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff)));
- }
- $this->redis = $redis;
- $this->prefix = $options['prefix'] ?? 'sf_s';
- $this->ttl = $options['ttl'] ?? null;
- }
-
- protected function doRead(string $sessionId): string
- {
- return $this->redis->get($this->prefix.$sessionId) ?: '';
- }
-
- protected function doWrite(string $sessionId, string $data): bool
- {
- $result = $this->redis->setEx($this->prefix.$sessionId, (int) ($this->ttl ?? ini_get('session.gc_maxlifetime')), $data);
- return $result && !$result instanceof ErrorInterface;
- }
-
- protected function doDestroy(string $sessionId): bool
- {
- static $unlink = true;
- if ($unlink) {
- try {
- $unlink = false !== $this->redis->unlink($this->prefix.$sessionId);
- } catch (\Throwable $e) {
- $unlink = false;
- }
- }
- if (!$unlink) {
- $this->redis->del($this->prefix.$sessionId);
- }
- return true;
- }
-
- public function close(): bool
- {
- return true;
- }
-
-
- public function gc($maxlifetime)
- {
- return 0;
- }
-
-
- public function updateTimestamp($sessionId, $data)
- {
- return (bool) $this->redis->expire($this->prefix.$sessionId, (int) ($this->ttl ?? ini_get('session.gc_maxlifetime')));
- }
- }
|