Debian Codegraph @

lib/3rdParty/composer/symfony/http-foundation/Session/Storage/Handler/MongoDbSessionHandler.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 MongoDB\BSON\Binary;
15 use MongoDB\BSON\UTCDateTime;
16 use MongoDB\Client;
17 use MongoDB\Driver\BulkWrite;
18 use MongoDB\Driver\Manager;
19 use MongoDB\Driver\Query;
20
21 /**
22 * Session handler using the MongoDB driver extension.
23 *
24 * @author Markus Bachmann <[email protected]>
25 * @author Jérôme Tamarelle <[email protected]t>
26 *
27 * @see https://php.net/mongodb
28 */
29 class MongoDbSessionHandler extends AbstractSessionHandler
30 {
31 private Manager $manager;
32 private string $namespace;
33 private array $options;
34 private int|\Closure|null $ttl;
35
36 /**
37 * Constructor.
38 *
39 * List of available options:
40 * * database: The name of the database [required]
41 * * collection: The name of the collection [required]
42 * * id_field: The field name for storing the session id [default: _id]
43 * * data_field: The field name for storing the session data [default: data]
44 * * time_field: The field name for storing the timestamp [default: time]
45 * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]
46 * * ttl: The time to live in seconds.
47 *
48 * It is strongly recommended to put an index on the `expiry_field` for
49 * garbage-collection. Alternatively it's possible to automatically expire
50 * the sessions in the database as described below:
51 *
52 * A TTL collections can be used on MongoDB 2.2+ to cleanup expired sessions
53 * automatically. Such an index can for example look like this:
54 *
55 * db.<session-collection>.createIndex(
56 * { "<expiry-field>": 1 },
57 * { "expireAfterSeconds": 0 }
58 * )
59 *
60 * More details on: https://docs.mongodb.org/manual/tutorial/expire-data/
61 *
62 * If you use such an index, you can drop `gc_probability` to 0 since
63 * no garbage-collection is required.
64 *
65 * @throws \InvalidArgumentException When "database" or "collection" not provided
66 */
67 public function __construct(Client|Manager $mongo, array $options)
68 {
69 if (!isset($options['database']) || !isset($options['collection'])) {
70 throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler.');
71 }
72
73 if ($mongo instanceof Client) {
74 $mongo = $mongo->getManager();
75 }
76
77 $this->manager = $mongo;
78 $this->namespace = $options['database'].'.'.$options['collection'];
79
80 $this->options = array_merge([
81 'id_field' => '_id',
82 'data_field' => 'data',
83 'time_field' => 'time',
84 'expiry_field' => 'expires_at',
85 ], $options);
86 $this->ttl = $this->options['ttl'] ?? null;
87 }
88
89 public function close(): bool
90 {
91 return true;
92 }
93
94 protected function doDestroy(#[\SensitiveParameter] string $sessionId): bool
95 {
96 $write = new BulkWrite();
97 $write->delete(
98 [$this->options['id_field'] => $sessionId],
99 ['limit' => 1]
100 );
101
102 $this->manager->executeBulkWrite($this->namespace, $write);
103
104 return true;
105 }
106
107 public function gc(int $maxlifetime): int|false
108 {
109 $write = new BulkWrite();
110 $write->delete(
111 [$this->options['expiry_field'] => ['$lt' => $this->getUTCDateTime()]],
112 );
113 $result = $this->manager->executeBulkWrite($this->namespace, $write);
114
115 return $result->getDeletedCount() ?? false;
116 }
117
118 protected function doWrite(#[\SensitiveParameter] string $sessionId, string $data): bool
119 {
120 $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
121 $expiry = $this->getUTCDateTime($ttl);
122
123 $fields = [
124 $this->options['time_field'] => $this->getUTCDateTime(),
125 $this->options['expiry_field'] => $expiry,
126 $this->options['data_field'] => new Binary($data, Binary::TYPE_GENERIC),
127 ];
128
129 $write = new BulkWrite();
130 $write->update(
131 [$this->options['id_field'] => $sessionId],
132 ['$set' => $fields],
133 ['upsert' => true]
134 );
135
136 $this->manager->executeBulkWrite($this->namespace, $write);
137
138 return true;
139 }
140
141 public function updateTimestamp(#[\SensitiveParameter] string $sessionId, string $data): bool
142 {
143 $ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
144 $expiry = $this->getUTCDateTime($ttl);
145
146 $write = new BulkWrite();
147 $write->update(
148 [$this->options['id_field'] => $sessionId],
149 ['$set' => [
150 $this->options['time_field'] => $this->getUTCDateTime(),
151 $this->options['expiry_field'] => $expiry,
152 ]],
153 ['multi' => false],
154 );
155
156 $this->manager->executeBulkWrite($this->namespace, $write);
157
158 return true;
159 }
160
161 protected function doRead(#[\SensitiveParameter] string $sessionId): string
162 {
163 $cursor = $this->manager->executeQuery($this->namespace, new Query([
164 $this->options['id_field'] => $sessionId,
165 $this->options['expiry_field'] => ['$gte' => $this->getUTCDateTime()],
166 ], [
167 'projection' => [
168 '_id' => false,
169 $this->options['data_field'] => true,
170 ],
171 'limit' => 1,
172 ]));
173
174 foreach ($cursor as $document) {
175 return (string) $document->{$this->options['data_field']} ?? '';
176 }
177
178 // Not found
179 return '';
180 }
181
182 private function getUTCDateTime(int $additionalSeconds = 0): UTCDateTime
183 {
184 return new UTCDateTime((time() + $additionalSeconds) * 1000);
185 }
186 }