Skip to content

PHPORM-310 Create dedicated session handler #3348

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Apr 15, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions phpstan.neon.dist
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ parameters:

editorUrl: 'phpstorm://open?file=%%file%%&line=%%line%%'

universalObjectCratesClasses:
- MongoDB\BSON\Document
Comment on lines +14 to +15
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIL


ignoreErrors:
- '#Unsafe usage of new static#'
- '#Call to an undefined method [a-zA-Z0-9\\_\<\>\(\)]+::[a-zA-Z]+\(\)#'
Expand Down
12 changes: 5 additions & 7 deletions src/MongoDBServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@
use MongoDB\Laravel\Eloquent\Model;
use MongoDB\Laravel\Queue\MongoConnector;
use MongoDB\Laravel\Scout\ScoutEngine;
use MongoDB\Laravel\Session\MongoDbSessionHandler;
use RuntimeException;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler;

use function assert;
use function class_exists;
Expand Down Expand Up @@ -67,12 +67,10 @@ public function register()
assert($connection instanceof Connection, new InvalidArgumentException(sprintf('The database connection "%s" used for the session does not use the "mongodb" driver.', $connectionName)));

return new MongoDbSessionHandler(
$connection->getClient(),
$app->config->get('session.options', []) + [
'database' => $connection->getDatabaseName(),
'collection' => $app->config->get('session.table') ?: 'sessions',
'ttl' => $app->config->get('session.lifetime'),
],
$connection,
$app->config->get('session.table', 'sessions'),
$app->config->get('session.lifetime'),
$app,
);
});
});
Expand Down
115 changes: 115 additions & 0 deletions src/Session/MongoDbSessionHandler.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace MongoDB\Laravel\Session;

use Illuminate\Session\DatabaseSessionHandler;
use MongoDB\BSON\Binary;
use MongoDB\BSON\Document;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Collection;

use function assert;
use function tap;
use function time;

/**
* Session handler using the MongoDB driver extension.
*/
final class MongoDbSessionHandler extends DatabaseSessionHandler
{
private Collection $collection;

public function close(): bool
{
return true;
}

public function gc($lifetime): int
{
$result = $this->getCollection()->deleteMany(['last_activity' => ['$lt' => $this->getUTCDateTime(-$lifetime)]]);

return $result->getDeletedCount() ?? 0;
}

public function destroy($sessionId): bool
{
$this->getCollection()->deleteOne(['_id' => (string) $sessionId]);

return true;
}

public function read($sessionId): string|false
{
$result = $this->getCollection()->findOne(
['_id' => (string) $sessionId, 'expires_at' => ['$gte' => $this->getUTCDateTime()]],
[
'projection' => ['_id' => false, 'payload' => true],
'typeMap' => ['root' => 'bson'],
],
);
assert($result instanceof Document);

return $result ? (string) $result->payload : false;
}

public function write($sessionId, $data): bool
{
$payload = $this->getDefaultPayload($data);

$this->getCollection()->replaceOne(
['_id' => (string) $sessionId],
$payload,
['upsert' => true],
);

return true;
}

/** Creates a TTL index that automatically deletes expired objects. */
public function createTTLIndex(): void
{
$this->collection->createIndex(
// UTCDateTime field that holds the expiration date
['expires_at' => 1],
// Delay to remove items after expiration
['expireAfterSeconds' => 0],
);
}

protected function getDefaultPayload($data): array
{
$payload = [
'payload' => new Binary($data),
'last_activity' => $this->getUTCDateTime(),
'expires_at' => $this->getUTCDateTime($this->minutes * 60),
];

if (! $this->container) {
return $payload;
}

return tap($payload, function (&$payload) {
$this->addUserInformation($payload)
->addRequestInformation($payload);
});
}

private function getCollection(): Collection
{
return $this->collection ??= $this->connection->getCollection($this->table);
}

private function getUTCDateTime(int $additionalSeconds = 0): UTCDateTime
{
return new UTCDateTime((time() + $additionalSeconds) * 1000);
}
}
2 changes: 1 addition & 1 deletion tests/Query/BuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -868,7 +868,7 @@ function (Builder $builder) {
[],
],
],
fn (Builder $builder) => $builder->whereDate('created_at', '=', new DateTimeImmutable('2018-09-30 15:00:00 +02:00')),
fn (Builder $builder) => $builder->whereDate('created_at', '=', new DateTimeImmutable('2018-09-30 15:00:00 +00:00')),
];

yield 'where date !=' => [
Expand Down
30 changes: 25 additions & 5 deletions tests/SessionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
use Illuminate\Session\DatabaseSessionHandler;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MongoDbSessionHandler;
use MongoDB\Laravel\Session\MongoDbSessionHandler;
use PHPUnit\Framework\Attributes\TestWith;
use SessionHandlerInterface;

class SessionTest extends TestCase
{
Expand All @@ -16,21 +18,31 @@ protected function tearDown(): void
parent::tearDown();
}

public function testDatabaseSessionHandlerCompatibility()
/** @param class-string<SessionHandlerInterface> $class */
#[TestWith([DatabaseSessionHandler::class])]
#[TestWith([MongoDbSessionHandler::class])]
public function testSessionHandlerFunctionality(string $class)
{
$sessionId = '123';

$handler = new DatabaseSessionHandler(
$handler = new $class(
$this->app['db']->connection('mongodb'),
'sessions',
10,
);

$sessionId = '123';

$handler->write($sessionId, 'foo');
$this->assertEquals('foo', $handler->read($sessionId));

$handler->write($sessionId, 'bar');
$this->assertEquals('bar', $handler->read($sessionId));

$handler->destroy($sessionId);
$this->assertEmpty($handler->read($sessionId));

$handler->write($sessionId, 'bar');
$handler->gc(-1);
$this->assertEmpty($handler->read($sessionId));
}

public function testDatabaseSessionHandlerRegistration()
Expand Down Expand Up @@ -70,5 +82,13 @@ private function assertSessionCanStoreInMongoDB(SessionManager $session): void

self::assertIsObject($data);
self::assertSame($session->getId(), $data->_id);

$session->remove('foo');
$data = DB::connection('mongodb')
->getCollection('sessions')
->findOne(['_id' => $session->getId()]);

self::assertIsObject($data);
self::assertSame($session->getId(), $data->_id);
}
}
Loading