Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
13
14 use Predis\Response\ErrorInterface;
15 use Relay\Relay;
16
17 /**
18 * Redis based session storage handler based on the Redis class
19 * provided by the PHP redis extension.
20 *
21 * @author Dalibor Karlović <[email protected]>
22 */
23 class RedisSessionHandler extends AbstractSessionHandler
24 {
25 /**
26 * Key prefix for shared environments.
27 */
28 private string $prefix;
29
30 /**
31 * Time to live in seconds.
32 */
33 private int|\Closure|null $ttl;
34
35 /**
36 * List of available options:
37 * * prefix: The prefix to use for the keys in order to avoid collision on the Redis server
38 * * ttl: The time to live in seconds.
39 *
40 * @throws \InvalidArgumentException When unsupported client or options are passed
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 }