@@ -29,6 +29,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
2929 private Client $ mongo ;
3030 private Collection $ collection ;
3131 private array $ options ;
32+ private int |\Closure |null $ ttl ;
3233
3334 /**
3435 * Constructor.
@@ -39,7 +40,8 @@ class MongoDbSessionHandler extends AbstractSessionHandler
3940 * * id_field: The field name for storing the session id [default: _id]
4041 * * data_field: The field name for storing the session data [default: data]
4142 * * time_field: The field name for storing the timestamp [default: time]
42- * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at].
43+ * * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]
44+ * * ttl: The time to live in seconds.
4345 *
4446 * It is strongly recommended to put an index on the `expiry_field` for
4547 * garbage-collection. Alternatively it's possible to automatically expire
@@ -74,6 +76,7 @@ public function __construct(Client $mongo, array $options)
7476 'time_field ' => 'time ' ,
7577 'expiry_field ' => 'expires_at ' ,
7678 ], $ options );
79+ $ this ->ttl = $ this ->options ['ttl ' ] ?? null ;
7780 }
7881
7982 public function close (): bool
@@ -105,7 +108,8 @@ public function gc(int $maxlifetime): int|false
105108 */
106109 protected function doWrite (string $ sessionId , string $ data ): bool
107110 {
108- $ expiry = new UTCDateTime ((time () + (int ) ini_get ('session.gc_maxlifetime ' )) * 1000 );
111+ $ ttl = ($ this ->ttl instanceof \Closure ? ($ this ->ttl )() : $ this ->ttl ) ?? ini_get ('session.gc_maxlifetime ' );
112+ $ expiry = new UTCDateTime ((time () + (int ) $ ttl ) * 1000 );
109113
110114 $ fields = [
111115 $ this ->options ['time_field ' ] => new UTCDateTime (),
@@ -124,7 +128,8 @@ protected function doWrite(string $sessionId, string $data): bool
124128
125129 public function updateTimestamp (string $ sessionId , string $ data ): bool
126130 {
127- $ expiry = new UTCDateTime ((time () + (int ) ini_get ('session.gc_maxlifetime ' )) * 1000 );
131+ $ ttl = ($ this ->ttl instanceof \Closure ? ($ this ->ttl )() : $ this ->ttl ) ?? ini_get ('session.gc_maxlifetime ' );
132+ $ expiry = new UTCDateTime ((time () + (int ) $ ttl ) * 1000 );
128133
129134 $ this ->getCollection ()->updateOne (
130135 [$ this ->options ['id_field ' ] => $ sessionId ],
0 commit comments