|
| 1 | +<?php |
| 2 | + |
| 3 | +/* |
| 4 | + * This file is part of the Koded package. |
| 5 | + * |
| 6 | + * (c) Mihail Binev <mihail@kodeart.com> |
| 7 | + * |
| 8 | + * Please view the LICENSE distributed with this source code |
| 9 | + * for the full copyright and license information. |
| 10 | + * |
| 11 | + */ |
| 12 | + |
| 13 | +namespace Koded\Session\Handler; |
| 14 | + |
| 15 | +use Koded\Caching\Client\RedisClient; |
| 16 | +use Koded\Caching\Configuration\RedisConfiguration; |
| 17 | +use Koded\Session\SessionConfiguration; |
| 18 | +use Redis; |
| 19 | +use SessionHandlerInterface; |
| 20 | + |
| 21 | + |
| 22 | +final class RedisHandler implements SessionHandlerInterface |
| 23 | +{ |
| 24 | + |
| 25 | + /** |
| 26 | + * @var int |
| 27 | + */ |
| 28 | + protected $ttl; |
| 29 | + |
| 30 | + /** |
| 31 | + * @var Redis |
| 32 | + */ |
| 33 | + private $client; |
| 34 | + |
| 35 | + public function __construct(SessionConfiguration $settings) |
| 36 | + { |
| 37 | + $this->ttl = (int)$settings->get('gc_maxlifetime', ini_get('session.gc_maxlifetime')); |
| 38 | + $this->client = (new RedisClient(new Redis, $this->configuration($settings)))->client(); |
| 39 | + } |
| 40 | + |
| 41 | + public function close(): bool |
| 42 | + { |
| 43 | + return true; |
| 44 | + } |
| 45 | + |
| 46 | + public function destroy($sessionId): bool |
| 47 | + { |
| 48 | + return $this->client->del($sessionId) > 0; |
| 49 | + } |
| 50 | + |
| 51 | + /** |
| 52 | + * @codeCoverageIgnore |
| 53 | + */ |
| 54 | + public function gc($maxLifetime): bool |
| 55 | + { |
| 56 | + return true; |
| 57 | + } |
| 58 | + |
| 59 | + public function read($sessionId): string |
| 60 | + { |
| 61 | + return $this->client->get($sessionId) ?: ''; |
| 62 | + } |
| 63 | + |
| 64 | + public function write($sessionId, $sessionData): bool |
| 65 | + { |
| 66 | + if ($this->ttl > 0) { |
| 67 | + return $this->client->setex($sessionId, $this->ttl, $sessionData); |
| 68 | + } |
| 69 | + |
| 70 | + return $this->client->set($sessionId, $sessionData, $this->ttl); |
| 71 | + } |
| 72 | + |
| 73 | + public function open($savePath, $sessionId): bool |
| 74 | + { |
| 75 | + return true; |
| 76 | + } |
| 77 | + |
| 78 | + private function configuration(SessionConfiguration $settings): RedisConfiguration |
| 79 | + { |
| 80 | + return new RedisConfiguration([ |
| 81 | + 'prefix' => (string)$settings->get('prefix', 'session:'), |
| 82 | + 'host' => (string)$settings->get('host'), |
| 83 | + 'port' => (int)$settings->get('port', 6379), |
| 84 | + 'timeout' => (float)$settings->get('timeout', 0.0), |
| 85 | + 'retry' => (int)$settings->get('retry', 0), |
| 86 | + 'db' => (int)$settings->get('db', 0), |
| 87 | + ]); |
| 88 | + } |
| 89 | +} |
0 commit comments