package and depencies
This commit is contained in:
@@ -22,17 +22,13 @@ use Symfony\Component\HttpFoundation\Session\SessionUtils;
|
||||
*/
|
||||
abstract class AbstractSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
|
||||
{
|
||||
private $sessionName;
|
||||
private $prefetchId;
|
||||
private $prefetchData;
|
||||
private $newSessionId;
|
||||
private $igbinaryEmptyData;
|
||||
private string $sessionName;
|
||||
private string $prefetchId;
|
||||
private string $prefetchData;
|
||||
private ?string $newSessionId = null;
|
||||
private string $igbinaryEmptyData;
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function open($savePath, $sessionName)
|
||||
public function open(string $savePath, string $sessionName): bool
|
||||
{
|
||||
$this->sessionName = $sessionName;
|
||||
if (!headers_sent() && !\ini_get('session.cache_limiter') && '0' !== \ini_get('session.cache_limiter')) {
|
||||
@@ -42,52 +38,26 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
abstract protected function doRead(string $sessionId);
|
||||
abstract protected function doRead(string $sessionId): string;
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
abstract protected function doWrite(string $sessionId, string $data);
|
||||
abstract protected function doWrite(string $sessionId, string $data): bool;
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
abstract protected function doDestroy(string $sessionId);
|
||||
abstract protected function doDestroy(string $sessionId): bool;
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function validateId($sessionId)
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
$this->prefetchData = $this->read($sessionId);
|
||||
$this->prefetchId = $sessionId;
|
||||
|
||||
if (\PHP_VERSION_ID < 70317 || (70400 <= \PHP_VERSION_ID && \PHP_VERSION_ID < 70405)) {
|
||||
// work around https://bugs.php.net/79413
|
||||
foreach (debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS) as $frame) {
|
||||
if (!isset($frame['class']) && isset($frame['function']) && \in_array($frame['function'], ['session_regenerate_id', 'session_create_id'], true)) {
|
||||
return '' === $this->prefetchData;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return '' !== $this->prefetchData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function read($sessionId)
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
if (null !== $this->prefetchId) {
|
||||
if (isset($this->prefetchId)) {
|
||||
$prefetchId = $this->prefetchId;
|
||||
$prefetchData = $this->prefetchData;
|
||||
$this->prefetchId = $this->prefetchData = null;
|
||||
unset($this->prefetchId, $this->prefetchData);
|
||||
|
||||
if ($prefetchId === $sessionId || '' === $prefetchData) {
|
||||
$this->newSessionId = '' === $prefetchData ? $sessionId : null;
|
||||
@@ -102,16 +72,10 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function write($sessionId, $data)
|
||||
public function write(string $sessionId, string $data): bool
|
||||
{
|
||||
if (null === $this->igbinaryEmptyData) {
|
||||
// see https://github.com/igbinary/igbinary/issues/146
|
||||
$this->igbinaryEmptyData = \function_exists('igbinary_serialize') ? igbinary_serialize([]) : '';
|
||||
}
|
||||
// see https://github.com/igbinary/igbinary/issues/146
|
||||
$this->igbinaryEmptyData ??= \function_exists('igbinary_serialize') ? igbinary_serialize([]) : '';
|
||||
if ('' === $data || $this->igbinaryEmptyData === $data) {
|
||||
return $this->destroy($sessionId);
|
||||
}
|
||||
@@ -120,14 +84,10 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
|
||||
return $this->doWrite($sessionId, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function destroy($sessionId)
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
if (!headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN)) {
|
||||
if (!$this->sessionName) {
|
||||
if (!headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOL)) {
|
||||
if (!isset($this->sessionName)) {
|
||||
throw new \LogicException(sprintf('Session name cannot be empty, did you forget to call "parent::open()" in "%s"?.', static::class));
|
||||
}
|
||||
$cookie = SessionUtils::popSessionCookie($this->sessionName, $sessionId);
|
||||
@@ -140,13 +100,9 @@ abstract class AbstractSessionHandler implements \SessionHandlerInterface, \Sess
|
||||
* started the session).
|
||||
*/
|
||||
if (null === $cookie || isset($_COOKIE[$this->sessionName])) {
|
||||
if (\PHP_VERSION_ID < 70300) {
|
||||
setcookie($this->sessionName, '', 0, \ini_get('session.cookie_path'), \ini_get('session.cookie_domain'), filter_var(\ini_get('session.cookie_secure'), \FILTER_VALIDATE_BOOLEAN), filter_var(\ini_get('session.cookie_httponly'), \FILTER_VALIDATE_BOOLEAN));
|
||||
} else {
|
||||
$params = session_get_cookie_params();
|
||||
unset($params['lifetime']);
|
||||
setcookie($this->sessionName, '', $params);
|
||||
}
|
||||
$params = session_get_cookie_params();
|
||||
unset($params['lifetime']);
|
||||
setcookie($this->sessionName, '', $params);
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -18,9 +18,6 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface;
|
||||
*/
|
||||
class IdentityMarshaller implements MarshallerInterface
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function marshall(array $values, ?array &$failed): array
|
||||
{
|
||||
foreach ($values as $key => $value) {
|
||||
@@ -32,9 +29,6 @@ class IdentityMarshaller implements MarshallerInterface
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function unmarshall(string $value): string
|
||||
{
|
||||
return $value;
|
||||
|
@@ -18,8 +18,8 @@ use Symfony\Component\Cache\Marshaller\MarshallerInterface;
|
||||
*/
|
||||
class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
|
||||
{
|
||||
private $handler;
|
||||
private $marshaller;
|
||||
private AbstractSessionHandler $handler;
|
||||
private MarshallerInterface $marshaller;
|
||||
|
||||
public function __construct(AbstractSessionHandler $handler, MarshallerInterface $marshaller)
|
||||
{
|
||||
@@ -27,56 +27,32 @@ class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpd
|
||||
$this->marshaller = $marshaller;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function open($savePath, $name)
|
||||
public function open(string $savePath, string $name): bool
|
||||
{
|
||||
return $this->handler->open($savePath, $name);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close()
|
||||
public function close(): bool
|
||||
{
|
||||
return $this->handler->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function destroy($sessionId)
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
return $this->handler->destroy($sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return $this->handler->gc($maxlifetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function read($sessionId)
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
return $this->marshaller->unmarshall($this->handler->read($sessionId));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function write($sessionId, $data)
|
||||
public function write(string $sessionId, string $data): bool
|
||||
{
|
||||
$failed = [];
|
||||
$marshalledData = $this->marshaller->marshall(['data' => $data], $failed);
|
||||
@@ -88,20 +64,12 @@ class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpd
|
||||
return $this->handler->write($sessionId, $marshalledData['data']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function validateId($sessionId)
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
return $this->handler->validateId($sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->handler->updateTimestamp($sessionId, $data);
|
||||
}
|
||||
|
@@ -21,17 +21,17 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
*/
|
||||
class MemcachedSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
private $memcached;
|
||||
private \Memcached $memcached;
|
||||
|
||||
/**
|
||||
* @var int Time to live in seconds
|
||||
* Time to live in seconds.
|
||||
*/
|
||||
private $ttl;
|
||||
private int|\Closure|null $ttl;
|
||||
|
||||
/**
|
||||
* @var string Key prefix for shared environments
|
||||
* Key prefix for shared environments.
|
||||
*/
|
||||
private $prefix;
|
||||
private string $prefix;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
@@ -54,45 +54,31 @@ class MemcachedSessionHandler extends AbstractSessionHandler
|
||||
$this->prefix = $options['prefix'] ?? 'sf2s';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close()
|
||||
public function close(): bool
|
||||
{
|
||||
return $this->memcached->quit();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doRead(string $sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
return $this->memcached->get($this->prefix.$sessionId) ?: '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
$this->memcached->touch($this->prefix.$sessionId, $this->getCompatibleTtl());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doWrite(string $sessionId, string $data)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->memcached->set($this->prefix.$sessionId, $data, $this->getCompatibleTtl());
|
||||
}
|
||||
|
||||
private function getCompatibleTtl(): int
|
||||
{
|
||||
$ttl = (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime'));
|
||||
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
|
||||
|
||||
// If the relative TTL that is used exceeds 30 days, memcached will treat the value as Unix time.
|
||||
// We have to convert it to an absolute Unix time at this point, to make sure the TTL is correct.
|
||||
@@ -103,21 +89,14 @@ class MemcachedSessionHandler extends AbstractSessionHandler
|
||||
return $ttl;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId)
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
$result = $this->memcached->delete($this->prefix.$sessionId);
|
||||
|
||||
return $result || \Memcached::RES_NOTFOUND == $this->memcached->getResultCode();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
// not required here because memcached will auto expire the records anyhow.
|
||||
return 0;
|
||||
@@ -125,10 +104,8 @@ class MemcachedSessionHandler extends AbstractSessionHandler
|
||||
|
||||
/**
|
||||
* Return a Memcached instance.
|
||||
*
|
||||
* @return \Memcached
|
||||
*/
|
||||
protected function getMemcached()
|
||||
protected function getMemcached(): \Memcached
|
||||
{
|
||||
return $this->memcached;
|
||||
}
|
||||
|
@@ -25,12 +25,12 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
|
||||
/**
|
||||
* @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface
|
||||
*/
|
||||
private $currentHandler;
|
||||
private \SessionHandlerInterface $currentHandler;
|
||||
|
||||
/**
|
||||
* @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface
|
||||
*/
|
||||
private $writeOnlyHandler;
|
||||
private \SessionHandlerInterface $writeOnlyHandler;
|
||||
|
||||
public function __construct(\SessionHandlerInterface $currentHandler, \SessionHandlerInterface $writeOnlyHandler)
|
||||
{
|
||||
@@ -45,11 +45,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
|
||||
$this->writeOnlyHandler = $writeOnlyHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close()
|
||||
public function close(): bool
|
||||
{
|
||||
$result = $this->currentHandler->close();
|
||||
$this->writeOnlyHandler->close();
|
||||
@@ -57,11 +53,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function destroy($sessionId)
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
$result = $this->currentHandler->destroy($sessionId);
|
||||
$this->writeOnlyHandler->destroy($sessionId);
|
||||
@@ -69,11 +61,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
$result = $this->currentHandler->gc($maxlifetime);
|
||||
$this->writeOnlyHandler->gc($maxlifetime);
|
||||
@@ -81,11 +69,7 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function open($savePath, $sessionName)
|
||||
public function open(string $savePath, string $sessionName): bool
|
||||
{
|
||||
$result = $this->currentHandler->open($savePath, $sessionName);
|
||||
$this->writeOnlyHandler->open($savePath, $sessionName);
|
||||
@@ -93,21 +77,13 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function read($sessionId)
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
// No reading from new handler until switch-over
|
||||
return $this->currentHandler->read($sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function write($sessionId, $sessionData)
|
||||
public function write(string $sessionId, string $sessionData): bool
|
||||
{
|
||||
$result = $this->currentHandler->write($sessionId, $sessionData);
|
||||
$this->writeOnlyHandler->write($sessionId, $sessionData);
|
||||
@@ -115,21 +91,13 @@ class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdat
|
||||
return $result;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function validateId($sessionId)
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
// No reading from new handler until switch-over
|
||||
return $this->currentHandler->validateId($sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $sessionData)
|
||||
public function updateTimestamp(string $sessionId, string $sessionData): bool
|
||||
{
|
||||
$result = $this->currentHandler->updateTimestamp($sessionId, $sessionData);
|
||||
$this->writeOnlyHandler->updateTimestamp($sessionId, $sessionData);
|
||||
|
@@ -26,17 +26,10 @@ use MongoDB\Collection;
|
||||
*/
|
||||
class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
private $mongo;
|
||||
|
||||
/**
|
||||
* @var Collection
|
||||
*/
|
||||
private $collection;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $options;
|
||||
private Client $mongo;
|
||||
private Collection $collection;
|
||||
private array $options;
|
||||
private int|\Closure|null $ttl;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
@@ -47,7 +40,8 @@ class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
* * id_field: The field name for storing the session id [default: _id]
|
||||
* * data_field: The field name for storing the session data [default: data]
|
||||
* * time_field: The field name for storing the timestamp [default: time]
|
||||
* * expiry_field: The field name for storing the expiry-timestamp [default: expires_at].
|
||||
* * expiry_field: The field name for storing the expiry-timestamp [default: expires_at]
|
||||
* * ttl: The time to live in seconds.
|
||||
*
|
||||
* It is strongly recommended to put an index on the `expiry_field` for
|
||||
* garbage-collection. Alternatively it's possible to automatically expire
|
||||
@@ -82,21 +76,15 @@ class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
'time_field' => 'time',
|
||||
'expiry_field' => 'expires_at',
|
||||
], $options);
|
||||
$this->ttl = $this->options['ttl'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close()
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId)
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
$this->getCollection()->deleteOne([
|
||||
$this->options['id_field'] => $sessionId,
|
||||
@@ -105,23 +93,17 @@ class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return $this->getCollection()->deleteMany([
|
||||
$this->options['expiry_field'] => ['$lt' => new UTCDateTime()],
|
||||
])->getDeletedCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doWrite(string $sessionId, string $data)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
$expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000);
|
||||
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
|
||||
$expiry = new UTCDateTime((time() + (int) $ttl) * 1000);
|
||||
|
||||
$fields = [
|
||||
$this->options['time_field'] => new UTCDateTime(),
|
||||
@@ -138,13 +120,10 @@ class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
$expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000);
|
||||
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
|
||||
$expiry = new UTCDateTime((time() + (int) $ttl) * 1000);
|
||||
|
||||
$this->getCollection()->updateOne(
|
||||
[$this->options['id_field'] => $sessionId],
|
||||
@@ -157,10 +136,7 @@ class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doRead(string $sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
$dbData = $this->getCollection()->findOne([
|
||||
$this->options['id_field'] => $sessionId,
|
||||
@@ -176,17 +152,10 @@ class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
|
||||
private function getCollection(): Collection
|
||||
{
|
||||
if (null === $this->collection) {
|
||||
$this->collection = $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
|
||||
}
|
||||
|
||||
return $this->collection;
|
||||
return $this->collection ??= $this->mongo->selectCollection($this->options['database'], $this->options['collection']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Client
|
||||
*/
|
||||
protected function getMongo()
|
||||
protected function getMongo(): Client
|
||||
{
|
||||
return $this->mongo;
|
||||
}
|
||||
|
@@ -30,11 +30,7 @@ class NativeFileSessionHandler extends \SessionHandler
|
||||
*/
|
||||
public function __construct(string $savePath = null)
|
||||
{
|
||||
if (null === $savePath) {
|
||||
$savePath = \ini_get('session.save_path');
|
||||
}
|
||||
|
||||
$baseDir = $savePath;
|
||||
$baseDir = $savePath ??= \ini_get('session.save_path');
|
||||
|
||||
if ($count = substr_count($savePath, ';')) {
|
||||
if ($count > 2) {
|
||||
|
@@ -18,62 +18,37 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
*/
|
||||
class NullSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close()
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function validateId($sessionId)
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doRead(string $sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doWrite(string $sessionId, string $data)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId)
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
@@ -65,105 +65,66 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
*/
|
||||
public const LOCK_TRANSACTIONAL = 2;
|
||||
|
||||
private const MAX_LIFETIME = 315576000;
|
||||
|
||||
/**
|
||||
* @var \PDO|null PDO instance or null when not connected yet
|
||||
*/
|
||||
private $pdo;
|
||||
private \PDO $pdo;
|
||||
|
||||
/**
|
||||
* DSN string or null for session.save_path or false when lazy connection disabled.
|
||||
*
|
||||
* @var string|false|null
|
||||
*/
|
||||
private $dsn = false;
|
||||
private string|false|null $dsn = false;
|
||||
|
||||
private string $driver;
|
||||
private string $table = 'sessions';
|
||||
private string $idCol = 'sess_id';
|
||||
private string $dataCol = 'sess_data';
|
||||
private string $lifetimeCol = 'sess_lifetime';
|
||||
private string $timeCol = 'sess_time';
|
||||
|
||||
/**
|
||||
* @var string|null
|
||||
* Time to live in seconds.
|
||||
*/
|
||||
private $driver;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $table = 'sessions';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $idCol = 'sess_id';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $dataCol = 'sess_data';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $lifetimeCol = 'sess_lifetime';
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $timeCol = 'sess_time';
|
||||
private int|\Closure|null $ttl;
|
||||
|
||||
/**
|
||||
* Username when lazy-connect.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $username = '';
|
||||
private string $username = '';
|
||||
|
||||
/**
|
||||
* Password when lazy-connect.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
private $password = '';
|
||||
private string $password = '';
|
||||
|
||||
/**
|
||||
* Connection options when lazy-connect.
|
||||
*
|
||||
* @var array
|
||||
*/
|
||||
private $connectionOptions = [];
|
||||
private array $connectionOptions = [];
|
||||
|
||||
/**
|
||||
* The strategy for locking, see constants.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
private $lockMode = self::LOCK_TRANSACTIONAL;
|
||||
private int $lockMode = self::LOCK_TRANSACTIONAL;
|
||||
|
||||
/**
|
||||
* It's an array to support multiple reads before closing which is manual, non-standard usage.
|
||||
*
|
||||
* @var \PDOStatement[] An array of statements to release advisory locks
|
||||
*/
|
||||
private $unlockStatements = [];
|
||||
private array $unlockStatements = [];
|
||||
|
||||
/**
|
||||
* True when the current session exists but expired according to session.gc_maxlifetime.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $sessionExpired = false;
|
||||
private bool $sessionExpired = false;
|
||||
|
||||
/**
|
||||
* Whether a transaction is active.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $inTransaction = false;
|
||||
private bool $inTransaction = false;
|
||||
|
||||
/**
|
||||
* Whether gc() has been called.
|
||||
*
|
||||
* @var bool
|
||||
*/
|
||||
private $gcCalled = false;
|
||||
private bool $gcCalled = false;
|
||||
|
||||
/**
|
||||
* You can either pass an existing database connection as PDO instance or
|
||||
@@ -181,12 +142,13 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
* * db_password: The password when lazy-connect [default: '']
|
||||
* * db_connection_options: An array of driver-specific connection options [default: []]
|
||||
* * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
|
||||
* * ttl: The time to live in seconds.
|
||||
*
|
||||
* @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or URL string or null
|
||||
*
|
||||
* @throws \InvalidArgumentException When PDO error mode is not PDO::ERRMODE_EXCEPTION
|
||||
*/
|
||||
public function __construct($pdoOrDsn = null, array $options = [])
|
||||
public function __construct(\PDO|string $pdoOrDsn = null, array $options = [])
|
||||
{
|
||||
if ($pdoOrDsn instanceof \PDO) {
|
||||
if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
|
||||
@@ -210,6 +172,7 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
$this->password = $options['db_password'] ?? $this->password;
|
||||
$this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
|
||||
$this->lockMode = $options['lock_mode'] ?? $this->lockMode;
|
||||
$this->ttl = $options['ttl'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -228,34 +191,23 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
// connect if we are not yet
|
||||
$this->getConnection();
|
||||
|
||||
switch ($this->driver) {
|
||||
case 'mysql':
|
||||
// We use varbinary for the ID column because it prevents unwanted conversions:
|
||||
// - character set conversions between server and client
|
||||
// - trailing space removal
|
||||
// - case-insensitivity
|
||||
// - language processing like é == e
|
||||
$sql = "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB";
|
||||
break;
|
||||
case 'sqlite':
|
||||
$sql = "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
|
||||
break;
|
||||
case 'pgsql':
|
||||
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
|
||||
break;
|
||||
case 'oci':
|
||||
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
|
||||
break;
|
||||
case 'sqlsrv':
|
||||
$sql = "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)";
|
||||
break;
|
||||
default:
|
||||
throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver));
|
||||
}
|
||||
$sql = match ($this->driver) {
|
||||
// We use varbinary for the ID column because it prevents unwanted conversions:
|
||||
// - character set conversions between server and client
|
||||
// - trailing space removal
|
||||
// - case-insensitivity
|
||||
// - language processing like é == e
|
||||
'mysql' => "CREATE TABLE $this->table ($this->idCol VARBINARY(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER UNSIGNED NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8mb4_bin, ENGINE = InnoDB",
|
||||
'sqlite' => "CREATE TABLE $this->table ($this->idCol TEXT NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
|
||||
'pgsql' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol BYTEA NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
|
||||
'oci' => "CREATE TABLE $this->table ($this->idCol VARCHAR2(128) NOT NULL PRIMARY KEY, $this->dataCol BLOB NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
|
||||
'sqlsrv' => "CREATE TABLE $this->table ($this->idCol VARCHAR(128) NOT NULL PRIMARY KEY, $this->dataCol VARBINARY(MAX) NOT NULL, $this->lifetimeCol INTEGER NOT NULL, $this->timeCol INTEGER NOT NULL)",
|
||||
default => throw new \DomainException(sprintf('Creating the session table is currently not implemented for PDO driver "%s".', $this->driver)),
|
||||
};
|
||||
|
||||
try {
|
||||
$this->pdo->exec($sql);
|
||||
$this->pdo->exec("CREATE INDEX EXPIRY ON $this->table ($this->lifetimeCol)");
|
||||
$this->pdo->exec("CREATE INDEX expiry ON $this->table ($this->lifetimeCol)");
|
||||
} catch (\PDOException $e) {
|
||||
$this->rollback();
|
||||
|
||||
@@ -267,34 +219,24 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
* Returns true when the current session exists but expired according to session.gc_maxlifetime.
|
||||
*
|
||||
* Can be used to distinguish between a new session and one that expired due to inactivity.
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function isSessionExpired()
|
||||
public function isSessionExpired(): bool
|
||||
{
|
||||
return $this->sessionExpired;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function open($savePath, $sessionName)
|
||||
public function open(string $savePath, string $sessionName): bool
|
||||
{
|
||||
$this->sessionExpired = false;
|
||||
|
||||
if (null === $this->pdo) {
|
||||
if (!isset($this->pdo)) {
|
||||
$this->connect($this->dsn ?: $savePath);
|
||||
}
|
||||
|
||||
return parent::open($savePath, $sessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function read($sessionId)
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
try {
|
||||
return parent::read($sessionId);
|
||||
@@ -305,11 +247,7 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
// We delay gc() to close() so that it is executed outside the transactional and blocking read-write process.
|
||||
// This way, pruning expired sessions does not block them from being started while the current session is used.
|
||||
@@ -318,10 +256,7 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId)
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
// delete the record associated with this id
|
||||
$sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
|
||||
@@ -339,12 +274,9 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doWrite(string $sessionId, string $data)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
$maxlifetime = (int) \ini_get('session.gc_maxlifetime');
|
||||
$maxlifetime = (int) (($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'));
|
||||
|
||||
try {
|
||||
// We use a single MERGE SQL query when supported by the database.
|
||||
@@ -385,13 +317,9 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
$expiry = time() + (int) \ini_get('session.gc_maxlifetime');
|
||||
$expiry = time() + (int) (($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime'));
|
||||
|
||||
try {
|
||||
$updateStmt = $this->pdo->prepare(
|
||||
@@ -410,11 +338,7 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close()
|
||||
public function close(): bool
|
||||
{
|
||||
$this->commit();
|
||||
|
||||
@@ -426,27 +350,14 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
$this->gcCalled = false;
|
||||
|
||||
// delete the session records that have expired
|
||||
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time AND $this->lifetimeCol > :min";
|
||||
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time";
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
// to be removed in 6.0
|
||||
if ('mysql' === $this->driver) {
|
||||
$legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol + $this->timeCol < :time";
|
||||
} else {
|
||||
$legacySql = "DELETE FROM $this->table WHERE $this->lifetimeCol <= :min AND $this->lifetimeCol < :time - $this->timeCol";
|
||||
}
|
||||
|
||||
$stmt = $this->pdo->prepare($legacySql);
|
||||
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':min', self::MAX_LIFETIME, \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
}
|
||||
|
||||
if (false !== $this->dsn) {
|
||||
$this->pdo = null; // only close lazy-connection
|
||||
$this->driver = null;
|
||||
unset($this->pdo, $this->driver); // only close lazy-connection
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -533,7 +444,7 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
// If "unix_socket" is not in the query, we continue with the same process as pgsql
|
||||
// no break
|
||||
case 'pgsql':
|
||||
$dsn ?? $dsn = 'pgsql:';
|
||||
$dsn ??= 'pgsql:';
|
||||
|
||||
if (isset($params['host']) && '' !== $params['host']) {
|
||||
$dsn .= 'host='.$params['host'].';';
|
||||
@@ -649,10 +560,8 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
*
|
||||
* We need to make sure we do not return session data that is already considered garbage according
|
||||
* to the session.gc_maxlifetime setting because gc() is called after read() and only sometimes.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function doRead(string $sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
if (self::LOCK_ADVISORY === $this->lockMode) {
|
||||
$this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
|
||||
@@ -669,9 +578,6 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
|
||||
if ($sessionRows) {
|
||||
$expiry = (int) $sessionRows[0][1];
|
||||
if ($expiry <= self::MAX_LIFETIME) {
|
||||
$expiry += $sessionRows[0][2];
|
||||
}
|
||||
|
||||
if ($expiry < time()) {
|
||||
$this->sessionExpired = true;
|
||||
@@ -687,7 +593,7 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
throw new \RuntimeException('Failed to read session: INSERT reported a duplicate id but next SELECT did not return any data.');
|
||||
}
|
||||
|
||||
if (!filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
|
||||
if (!filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOL) && self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
|
||||
// In strict mode, session fixation is not possible: new sessions always start with a unique
|
||||
// random id, so that concurrency is not possible and this code path can be skipped.
|
||||
// Exclusive-reading of non-existent rows does not block, so we need to do an insert to block
|
||||
@@ -804,14 +710,13 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
|
||||
$this->beginTransaction();
|
||||
|
||||
// selecting the time column should be removed in 6.0
|
||||
switch ($this->driver) {
|
||||
case 'mysql':
|
||||
case 'oci':
|
||||
case 'pgsql':
|
||||
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
|
||||
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id FOR UPDATE";
|
||||
case 'sqlsrv':
|
||||
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
|
||||
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WITH (UPDLOCK, ROWLOCK) WHERE $this->idCol = :id";
|
||||
case 'sqlite':
|
||||
// we already locked when starting transaction
|
||||
break;
|
||||
@@ -820,7 +725,7 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
}
|
||||
}
|
||||
|
||||
return "SELECT $this->dataCol, $this->lifetimeCol, $this->timeCol FROM $this->table WHERE $this->idCol = :id";
|
||||
return "SELECT $this->dataCol, $this->lifetimeCol FROM $this->table WHERE $this->idCol = :id";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -929,12 +834,10 @@ class PdoSessionHandler extends AbstractSessionHandler
|
||||
|
||||
/**
|
||||
* Return a PDO instance.
|
||||
*
|
||||
* @return \PDO
|
||||
*/
|
||||
protected function getConnection()
|
||||
protected function getConnection(): \PDO
|
||||
{
|
||||
if (null === $this->pdo) {
|
||||
if (!isset($this->pdo)) {
|
||||
$this->connect($this->dsn ?: \ini_get('session.save_path'));
|
||||
}
|
||||
|
||||
|
@@ -12,8 +12,6 @@
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
use Predis\Response\ErrorInterface;
|
||||
use Symfony\Component\Cache\Traits\RedisClusterProxy;
|
||||
use Symfony\Component\Cache\Traits\RedisProxy;
|
||||
|
||||
/**
|
||||
* Redis based session storage handler based on the Redis class
|
||||
@@ -23,70 +21,48 @@ use Symfony\Component\Cache\Traits\RedisProxy;
|
||||
*/
|
||||
class RedisSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
private $redis;
|
||||
/**
|
||||
* Key prefix for shared environments.
|
||||
*/
|
||||
private string $prefix;
|
||||
|
||||
/**
|
||||
* @var string Key prefix for shared environments
|
||||
* Time to live in seconds.
|
||||
*/
|
||||
private $prefix;
|
||||
|
||||
/**
|
||||
* @var int Time to live in seconds
|
||||
*/
|
||||
private $ttl;
|
||||
private int|\Closure|null $ttl;
|
||||
|
||||
/**
|
||||
* List of available options:
|
||||
* * prefix: The prefix to use for the keys in order to avoid collision on the Redis server
|
||||
* * ttl: The time to live in seconds.
|
||||
*
|
||||
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $redis
|
||||
*
|
||||
* @throws \InvalidArgumentException When unsupported client or options are passed
|
||||
*/
|
||||
public function __construct($redis, array $options = [])
|
||||
{
|
||||
if (
|
||||
!$redis instanceof \Redis &&
|
||||
!$redis instanceof \RedisArray &&
|
||||
!$redis instanceof \RedisCluster &&
|
||||
!$redis instanceof \Predis\ClientInterface &&
|
||||
!$redis instanceof RedisProxy &&
|
||||
!$redis instanceof RedisClusterProxy
|
||||
) {
|
||||
throw new \InvalidArgumentException(sprintf('"%s()" expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\ClientInterface, "%s" given.', __METHOD__, get_debug_type($redis)));
|
||||
}
|
||||
|
||||
public function __construct(
|
||||
private \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface $redis,
|
||||
array $options = [],
|
||||
) {
|
||||
if ($diff = array_diff(array_keys($options), ['prefix', 'ttl'])) {
|
||||
throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff)));
|
||||
}
|
||||
|
||||
$this->redis = $redis;
|
||||
$this->prefix = $options['prefix'] ?? 'sf_s';
|
||||
$this->ttl = $options['ttl'] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
return $this->redis->get($this->prefix.$sessionId) ?: '';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
$result = $this->redis->setEx($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')), $data);
|
||||
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
|
||||
$result = $this->redis->setEx($this->prefix.$sessionId, (int) $ttl, $data);
|
||||
|
||||
return $result && !$result instanceof ErrorInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
static $unlink = true;
|
||||
@@ -94,7 +70,7 @@ class RedisSessionHandler extends AbstractSessionHandler
|
||||
if ($unlink) {
|
||||
try {
|
||||
$unlink = false !== $this->redis->unlink($this->prefix.$sessionId);
|
||||
} catch (\Throwable $e) {
|
||||
} catch (\Throwable) {
|
||||
$unlink = false;
|
||||
}
|
||||
}
|
||||
@@ -106,32 +82,21 @@ class RedisSessionHandler extends AbstractSessionHandler
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return (bool) $this->redis->expire($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')));
|
||||
$ttl = ($this->ttl instanceof \Closure ? ($this->ttl)() : $this->ttl) ?? \ini_get('session.gc_maxlifetime');
|
||||
|
||||
return $this->redis->expire($this->prefix.$sessionId, (int) $ttl);
|
||||
}
|
||||
}
|
||||
|
@@ -13,34 +13,28 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
use Doctrine\DBAL\DriverManager;
|
||||
use Symfony\Component\Cache\Adapter\AbstractAdapter;
|
||||
use Symfony\Component\Cache\Traits\RedisClusterProxy;
|
||||
use Symfony\Component\Cache\Traits\RedisProxy;
|
||||
|
||||
/**
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
class SessionHandlerFactory
|
||||
{
|
||||
/**
|
||||
* @param \Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy|\Memcached|\PDO|string $connection Connection or DSN
|
||||
*/
|
||||
public static function createHandler($connection): AbstractSessionHandler
|
||||
public static function createHandler(object|string $connection, array $options = []): AbstractSessionHandler
|
||||
{
|
||||
if (!\is_string($connection) && !\is_object($connection)) {
|
||||
throw new \TypeError(sprintf('Argument 1 passed to "%s()" must be a string or a connection object, "%s" given.', __METHOD__, get_debug_type($connection)));
|
||||
}
|
||||
if ($query = \is_string($connection) ? parse_url($connection) : false) {
|
||||
parse_str($query['query'] ?? '', $query);
|
||||
|
||||
if ($options = \is_string($connection) ? parse_url($connection) : false) {
|
||||
parse_str($options['query'] ?? '', $options);
|
||||
if (($options['ttl'] ?? null) instanceof \Closure) {
|
||||
$query['ttl'] = $options['ttl'];
|
||||
}
|
||||
}
|
||||
$options = ($query ?: []) + $options;
|
||||
|
||||
switch (true) {
|
||||
case $connection instanceof \Redis:
|
||||
case $connection instanceof \RedisArray:
|
||||
case $connection instanceof \RedisCluster:
|
||||
case $connection instanceof \Predis\ClientInterface:
|
||||
case $connection instanceof RedisProxy:
|
||||
case $connection instanceof RedisClusterProxy:
|
||||
return new RedisSessionHandler($connection);
|
||||
|
||||
case $connection instanceof \Memcached:
|
||||
@@ -65,7 +59,7 @@ class SessionHandlerFactory
|
||||
$handlerClass = str_starts_with($connection, 'memcached:') ? MemcachedSessionHandler::class : RedisSessionHandler::class;
|
||||
$connection = AbstractAdapter::createConnection($connection, ['lazy' => true]);
|
||||
|
||||
return new $handlerClass($connection, array_intersect_key($options ?: [], ['prefix' => 1, 'ttl' => 1]));
|
||||
return new $handlerClass($connection, array_intersect_key($options, ['prefix' => 1, 'ttl' => 1]));
|
||||
|
||||
case str_starts_with($connection, 'pdo_oci://'):
|
||||
if (!class_exists(DriverManager::class)) {
|
||||
@@ -83,7 +77,7 @@ class SessionHandlerFactory
|
||||
case str_starts_with($connection, 'sqlsrv://'):
|
||||
case str_starts_with($connection, 'sqlite://'):
|
||||
case str_starts_with($connection, 'sqlite3://'):
|
||||
return new PdoSessionHandler($connection, $options ?: []);
|
||||
return new PdoSessionHandler($connection, $options);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported Connection: "%s".', $connection));
|
||||
|
@@ -18,8 +18,8 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
*/
|
||||
class StrictSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
private $handler;
|
||||
private $doDestroy;
|
||||
private \SessionHandlerInterface $handler;
|
||||
private bool $doDestroy;
|
||||
|
||||
public function __construct(\SessionHandlerInterface $handler)
|
||||
{
|
||||
@@ -40,47 +40,29 @@ class StrictSessionHandler extends AbstractSessionHandler
|
||||
return $this->handler instanceof \SessionHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function open($savePath, $sessionName)
|
||||
public function open(string $savePath, string $sessionName): bool
|
||||
{
|
||||
parent::open($savePath, $sessionName);
|
||||
|
||||
return $this->handler->open($savePath, $sessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doRead(string $sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
return $this->handler->read($sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function updateTimestamp($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->write($sessionId, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doWrite(string $sessionId, string $data)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->handler->write($sessionId, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function destroy($sessionId)
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
$this->doDestroy = true;
|
||||
$destroyed = parent::destroy($sessionId);
|
||||
@@ -88,30 +70,19 @@ class StrictSessionHandler extends AbstractSessionHandler
|
||||
return $this->doDestroy ? $this->doDestroy($sessionId) : $destroyed;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId)
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
$this->doDestroy = false;
|
||||
|
||||
return $this->handler->destroy($sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close()
|
||||
public function close(): bool
|
||||
{
|
||||
return $this->handler->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int|false
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function gc($maxlifetime)
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return $this->handler->gc($maxlifetime);
|
||||
}
|
||||
|
Reference in New Issue
Block a user