Upgrade framework
This commit is contained in:
111
vendor/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php
vendored
Normal file
111
vendor/symfony/http-foundation/Session/Storage/Handler/AbstractSessionHandler.php
vendored
Normal file
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
use Symfony\Component\HttpFoundation\Session\SessionUtils;
|
||||
|
||||
/**
|
||||
* This abstract session handler provides a generic implementation
|
||||
* of the PHP 7.0 SessionUpdateTimestampHandlerInterface,
|
||||
* enabling strict and lazy session handling.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
abstract class AbstractSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
|
||||
{
|
||||
private string $sessionName;
|
||||
private string $prefetchId;
|
||||
private string $prefetchData;
|
||||
private ?string $newSessionId = null;
|
||||
private string $igbinaryEmptyData;
|
||||
|
||||
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')) {
|
||||
header(sprintf('Cache-Control: max-age=%d, private, must-revalidate', 60 * (int) \ini_get('session.cache_expire')));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
abstract protected function doRead(string $sessionId): string;
|
||||
|
||||
abstract protected function doWrite(string $sessionId, string $data): bool;
|
||||
|
||||
abstract protected function doDestroy(string $sessionId): bool;
|
||||
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
$this->prefetchData = $this->read($sessionId);
|
||||
$this->prefetchId = $sessionId;
|
||||
|
||||
return '' !== $this->prefetchData;
|
||||
}
|
||||
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
if (isset($this->prefetchId)) {
|
||||
$prefetchId = $this->prefetchId;
|
||||
$prefetchData = $this->prefetchData;
|
||||
unset($this->prefetchId, $this->prefetchData);
|
||||
|
||||
if ($prefetchId === $sessionId || '' === $prefetchData) {
|
||||
$this->newSessionId = '' === $prefetchData ? $sessionId : null;
|
||||
|
||||
return $prefetchData;
|
||||
}
|
||||
}
|
||||
|
||||
$data = $this->doRead($sessionId);
|
||||
$this->newSessionId = '' === $data ? $sessionId : null;
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
public function write(string $sessionId, string $data): bool
|
||||
{
|
||||
// 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);
|
||||
}
|
||||
$this->newSessionId = null;
|
||||
|
||||
return $this->doWrite($sessionId, $data);
|
||||
}
|
||||
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
if (!headers_sent() && filter_var(\ini_get('session.use_cookies'), \FILTER_VALIDATE_BOOLEAN)) {
|
||||
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);
|
||||
|
||||
/*
|
||||
* We send an invalidation Set-Cookie header (zero lifetime)
|
||||
* when either the session was started or a cookie with
|
||||
* the session name was sent by the client (in which case
|
||||
* we know it's invalid as a valid session cookie would've
|
||||
* started the session).
|
||||
*/
|
||||
if (null === $cookie || isset($_COOKIE[$this->sessionName])) {
|
||||
$params = session_get_cookie_params();
|
||||
unset($params['lifetime']);
|
||||
setcookie($this->sessionName, '', $params);
|
||||
}
|
||||
}
|
||||
|
||||
return $this->newSessionId === $sessionId || $this->doDestroy($sessionId);
|
||||
}
|
||||
}
|
||||
42
vendor/symfony/http-foundation/Session/Storage/Handler/IdentityMarshaller.php
vendored
Normal file
42
vendor/symfony/http-foundation/Session/Storage/Handler/IdentityMarshaller.php
vendored
Normal file
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
|
||||
|
||||
/**
|
||||
* @author Ahmed TAILOULOUTE <ahmed.tailouloute@gmail.com>
|
||||
*/
|
||||
class IdentityMarshaller implements MarshallerInterface
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function marshall(array $values, ?array &$failed): array
|
||||
{
|
||||
foreach ($values as $key => $value) {
|
||||
if (!\is_string($value)) {
|
||||
throw new \LogicException(sprintf('%s accepts only string as data.', __METHOD__));
|
||||
}
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function unmarshall(string $value): string
|
||||
{
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
76
vendor/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php
vendored
Normal file
76
vendor/symfony/http-foundation/Session/Storage/Handler/MarshallingSessionHandler.php
vendored
Normal file
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
use Symfony\Component\Cache\Marshaller\MarshallerInterface;
|
||||
|
||||
/**
|
||||
* @author Ahmed TAILOULOUTE <ahmed.tailouloute@gmail.com>
|
||||
*/
|
||||
class MarshallingSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
|
||||
{
|
||||
private $handler;
|
||||
private $marshaller;
|
||||
|
||||
public function __construct(AbstractSessionHandler $handler, MarshallerInterface $marshaller)
|
||||
{
|
||||
$this->handler = $handler;
|
||||
$this->marshaller = $marshaller;
|
||||
}
|
||||
|
||||
public function open(string $savePath, string $name): bool
|
||||
{
|
||||
return $this->handler->open($savePath, $name);
|
||||
}
|
||||
|
||||
public function close(): bool
|
||||
{
|
||||
return $this->handler->close();
|
||||
}
|
||||
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
return $this->handler->destroy($sessionId);
|
||||
}
|
||||
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return $this->handler->gc($maxlifetime);
|
||||
}
|
||||
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
return $this->marshaller->unmarshall($this->handler->read($sessionId));
|
||||
}
|
||||
|
||||
public function write(string $sessionId, string $data): bool
|
||||
{
|
||||
$failed = [];
|
||||
$marshalledData = $this->marshaller->marshall(['data' => $data], $failed);
|
||||
|
||||
if (isset($failed['data'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->handler->write($sessionId, $marshalledData['data']);
|
||||
}
|
||||
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
return $this->handler->validateId($sessionId);
|
||||
}
|
||||
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->handler->updateTimestamp($sessionId, $data);
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* MemcacheSessionHandler.
|
||||
*
|
||||
* @author Drak <drak@zikula.org>
|
||||
*/
|
||||
class MemcacheSessionHandler implements \SessionHandlerInterface
|
||||
{
|
||||
/**
|
||||
* @var \Memcache Memcache driver
|
||||
*/
|
||||
private $memcache;
|
||||
|
||||
/**
|
||||
* @var int Time to live in seconds
|
||||
*/
|
||||
private $ttl;
|
||||
|
||||
/**
|
||||
* @var string Key prefix for shared environments
|
||||
*/
|
||||
private $prefix;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* List of available options:
|
||||
* * prefix: The prefix to use for the memcache keys in order to avoid collision
|
||||
* * expiretime: The time to live in seconds
|
||||
*
|
||||
* @param \Memcache $memcache A \Memcache instance
|
||||
* @param array $options An associative array of Memcache options
|
||||
*
|
||||
* @throws \InvalidArgumentException When unsupported options are passed
|
||||
*/
|
||||
public function __construct(\Memcache $memcache, array $options = array())
|
||||
{
|
||||
if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) {
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'The following options are not supported "%s"', implode(', ', $diff)
|
||||
));
|
||||
}
|
||||
|
||||
$this->memcache = $memcache;
|
||||
$this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400;
|
||||
$this->prefix = isset($options['prefix']) ? $options['prefix'] : 'sf2s';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function open($savePath, $sessionName)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read($sessionId)
|
||||
{
|
||||
return $this->memcache->get($this->prefix.$sessionId) ?: '';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function write($sessionId, $data)
|
||||
{
|
||||
return $this->memcache->set($this->prefix.$sessionId, $data, 0, time() + $this->ttl);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function destroy($sessionId)
|
||||
{
|
||||
return $this->memcache->delete($this->prefix.$sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function gc($maxlifetime)
|
||||
{
|
||||
// not required here because memcache will auto expire the records anyhow.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a Memcache instance.
|
||||
*
|
||||
* @return \Memcache
|
||||
*/
|
||||
protected function getMemcache()
|
||||
{
|
||||
return $this->memcache;
|
||||
}
|
||||
}
|
||||
@@ -12,113 +12,109 @@
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* MemcachedSessionHandler.
|
||||
*
|
||||
* Memcached based session storage handler based on the Memcached class
|
||||
* provided by the PHP memcached extension.
|
||||
*
|
||||
* @see http://php.net/memcached
|
||||
* @see https://php.net/memcached
|
||||
*
|
||||
* @author Drak <drak@zikula.org>
|
||||
*/
|
||||
class MemcachedSessionHandler implements \SessionHandlerInterface
|
||||
class MemcachedSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
/**
|
||||
* @var \Memcached Memcached driver
|
||||
*/
|
||||
private $memcached;
|
||||
|
||||
/**
|
||||
* @var int Time to live in seconds
|
||||
* Time to live in seconds.
|
||||
*/
|
||||
private $ttl;
|
||||
private ?int $ttl;
|
||||
|
||||
/**
|
||||
* @var string Key prefix for shared environments
|
||||
* Key prefix for shared environments.
|
||||
*/
|
||||
private $prefix;
|
||||
private string $prefix;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* List of available options:
|
||||
* * prefix: The prefix to use for the memcached keys in order to avoid collision
|
||||
* * expiretime: The time to live in seconds
|
||||
*
|
||||
* @param \Memcached $memcached A \Memcached instance
|
||||
* @param array $options An associative array of Memcached options
|
||||
* * ttl: The time to live in seconds.
|
||||
*
|
||||
* @throws \InvalidArgumentException When unsupported options are passed
|
||||
*/
|
||||
public function __construct(\Memcached $memcached, array $options = array())
|
||||
public function __construct(\Memcached $memcached, array $options = [])
|
||||
{
|
||||
$this->memcached = $memcached;
|
||||
|
||||
if ($diff = array_diff(array_keys($options), array('prefix', 'expiretime'))) {
|
||||
throw new \InvalidArgumentException(sprintf(
|
||||
'The following options are not supported "%s"', implode(', ', $diff)
|
||||
));
|
||||
if ($diff = array_diff(array_keys($options), ['prefix', 'expiretime', 'ttl'])) {
|
||||
throw new \InvalidArgumentException(sprintf('The following options are not supported "%s".', implode(', ', $diff)));
|
||||
}
|
||||
|
||||
$this->ttl = isset($options['expiretime']) ? (int) $options['expiretime'] : 86400;
|
||||
$this->prefix = isset($options['prefix']) ? $options['prefix'] : 'sf2s';
|
||||
$this->ttl = $options['expiretime'] ?? $options['ttl'] ?? null;
|
||||
$this->prefix = $options['prefix'] ?? 'sf2s';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function open($savePath, $sessionName)
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
return $this->memcached->quit();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read($sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
return $this->memcached->get($this->prefix.$sessionId) ?: '';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function write($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->memcached->set($this->prefix.$sessionId, $data, time() + $this->ttl);
|
||||
}
|
||||
$this->memcached->touch($this->prefix.$sessionId, $this->getCompatibleTtl());
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function destroy($sessionId)
|
||||
{
|
||||
return $this->memcached->delete($this->prefix.$sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function gc($maxlifetime)
|
||||
{
|
||||
// not required here because memcached will auto expire the records anyhow.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a Memcached instance.
|
||||
*
|
||||
* @return \Memcached
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function getMemcached()
|
||||
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'));
|
||||
|
||||
// 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.
|
||||
if ($ttl > 60 * 60 * 24 * 30) {
|
||||
$ttl += time();
|
||||
}
|
||||
|
||||
return $ttl;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
$result = $this->memcached->delete($this->prefix.$sessionId);
|
||||
|
||||
return $result || \Memcached::RES_NOTFOUND == $this->memcached->getResultCode();
|
||||
}
|
||||
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
// not required here because memcached will auto expire the records anyhow.
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a Memcached instance.
|
||||
*/
|
||||
protected function getMemcached(): \Memcached
|
||||
{
|
||||
return $this->memcached;
|
||||
}
|
||||
|
||||
107
vendor/symfony/http-foundation/Session/Storage/Handler/MigratingSessionHandler.php
vendored
Normal file
107
vendor/symfony/http-foundation/Session/Storage/Handler/MigratingSessionHandler.php
vendored
Normal file
@@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* Migrating session handler for migrating from one handler to another. It reads
|
||||
* from the current handler and writes both the current and new ones.
|
||||
*
|
||||
* It ignores errors from the new handler.
|
||||
*
|
||||
* @author Ross Motley <ross.motley@amara.com>
|
||||
* @author Oliver Radwell <oliver.radwell@amara.com>
|
||||
*/
|
||||
class MigratingSessionHandler implements \SessionHandlerInterface, \SessionUpdateTimestampHandlerInterface
|
||||
{
|
||||
/**
|
||||
* @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface
|
||||
*/
|
||||
private \SessionHandlerInterface $currentHandler;
|
||||
|
||||
/**
|
||||
* @var \SessionHandlerInterface&\SessionUpdateTimestampHandlerInterface
|
||||
*/
|
||||
private \SessionHandlerInterface $writeOnlyHandler;
|
||||
|
||||
public function __construct(\SessionHandlerInterface $currentHandler, \SessionHandlerInterface $writeOnlyHandler)
|
||||
{
|
||||
if (!$currentHandler instanceof \SessionUpdateTimestampHandlerInterface) {
|
||||
$currentHandler = new StrictSessionHandler($currentHandler);
|
||||
}
|
||||
if (!$writeOnlyHandler instanceof \SessionUpdateTimestampHandlerInterface) {
|
||||
$writeOnlyHandler = new StrictSessionHandler($writeOnlyHandler);
|
||||
}
|
||||
|
||||
$this->currentHandler = $currentHandler;
|
||||
$this->writeOnlyHandler = $writeOnlyHandler;
|
||||
}
|
||||
|
||||
public function close(): bool
|
||||
{
|
||||
$result = $this->currentHandler->close();
|
||||
$this->writeOnlyHandler->close();
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
$result = $this->currentHandler->destroy($sessionId);
|
||||
$this->writeOnlyHandler->destroy($sessionId);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
$result = $this->currentHandler->gc($maxlifetime);
|
||||
$this->writeOnlyHandler->gc($maxlifetime);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function open(string $savePath, string $sessionName): bool
|
||||
{
|
||||
$result = $this->currentHandler->open($savePath, $sessionName);
|
||||
$this->writeOnlyHandler->open($savePath, $sessionName);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
// No reading from new handler until switch-over
|
||||
return $this->currentHandler->read($sessionId);
|
||||
}
|
||||
|
||||
public function write(string $sessionId, string $sessionData): bool
|
||||
{
|
||||
$result = $this->currentHandler->write($sessionId, $sessionData);
|
||||
$this->writeOnlyHandler->write($sessionId, $sessionData);
|
||||
|
||||
return $result;
|
||||
}
|
||||
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
// No reading from new handler until switch-over
|
||||
return $this->currentHandler->validateId($sessionId);
|
||||
}
|
||||
|
||||
public function updateTimestamp(string $sessionId, string $sessionData): bool
|
||||
{
|
||||
$result = $this->currentHandler->updateTimestamp($sessionId, $sessionData);
|
||||
$this->writeOnlyHandler->updateTimestamp($sessionId, $sessionData);
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -11,27 +11,24 @@
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
use MongoDB\BSON\Binary;
|
||||
use MongoDB\BSON\UTCDateTime;
|
||||
use MongoDB\Client;
|
||||
use MongoDB\Collection;
|
||||
|
||||
/**
|
||||
* MongoDB session handler.
|
||||
* Session handler using the mongodb/mongodb package and MongoDB driver extension.
|
||||
*
|
||||
* @author Markus Bachmann <markus.bachmann@bachi.biz>
|
||||
*
|
||||
* @see https://packagist.org/packages/mongodb/mongodb
|
||||
* @see https://php.net/mongodb
|
||||
*/
|
||||
class MongoDbSessionHandler implements \SessionHandlerInterface
|
||||
class MongoDbSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
/**
|
||||
* @var \Mongo|\MongoClient|\MongoDB\Client
|
||||
*/
|
||||
private $mongo;
|
||||
|
||||
/**
|
||||
* @var \MongoCollection
|
||||
*/
|
||||
private $collection;
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
private $options;
|
||||
private array $options;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
@@ -42,7 +39,7 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
|
||||
* * 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].
|
||||
*
|
||||
* It is strongly recommended to put an index on the `expiry_field` for
|
||||
* garbage-collection. Alternatively it's possible to automatically expire
|
||||
@@ -51,46 +48,35 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
|
||||
* A TTL collections can be used on MongoDB 2.2+ to cleanup expired sessions
|
||||
* automatically. Such an index can for example look like this:
|
||||
*
|
||||
* db.<session-collection>.ensureIndex(
|
||||
* db.<session-collection>.createIndex(
|
||||
* { "<expiry-field>": 1 },
|
||||
* { "expireAfterSeconds": 0 }
|
||||
* )
|
||||
*
|
||||
* More details on: http://docs.mongodb.org/manual/tutorial/expire-data/
|
||||
* More details on: https://docs.mongodb.org/manual/tutorial/expire-data/
|
||||
*
|
||||
* If you use such an index, you can drop `gc_probability` to 0 since
|
||||
* no garbage-collection is required.
|
||||
*
|
||||
* @param \Mongo|\MongoClient|\MongoDB\Client $mongo A MongoDB\Client, MongoClient or Mongo instance
|
||||
* @param array $options An associative array of field options
|
||||
*
|
||||
* @throws \InvalidArgumentException When MongoClient or Mongo instance not provided
|
||||
* @throws \InvalidArgumentException When "database" or "collection" not provided
|
||||
*/
|
||||
public function __construct($mongo, array $options)
|
||||
public function __construct(Client $mongo, array $options)
|
||||
{
|
||||
if (!($mongo instanceof \MongoDB\Client || $mongo instanceof \MongoClient || $mongo instanceof \Mongo)) {
|
||||
throw new \InvalidArgumentException('MongoClient or Mongo instance required');
|
||||
}
|
||||
|
||||
if (!isset($options['database']) || !isset($options['collection'])) {
|
||||
throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler');
|
||||
throw new \InvalidArgumentException('You must provide the "database" and "collection" option for MongoDBSessionHandler.');
|
||||
}
|
||||
|
||||
$this->mongo = $mongo;
|
||||
|
||||
$this->options = array_merge(array(
|
||||
$this->options = array_merge([
|
||||
'id_field' => '_id',
|
||||
'data_field' => 'data',
|
||||
'time_field' => 'time',
|
||||
'expiry_field' => 'expires_at',
|
||||
), $options);
|
||||
], $options);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function open($savePath, $sessionName)
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -98,66 +84,54 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function close()
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function destroy($sessionId)
|
||||
{
|
||||
$methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
|
||||
|
||||
$this->getCollection()->$methodName(array(
|
||||
$this->getCollection()->deleteOne([
|
||||
$this->options['id_field'] => $sessionId,
|
||||
));
|
||||
]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return $this->getCollection()->deleteMany([
|
||||
$this->options['expiry_field'] => ['$lt' => new UTCDateTime()],
|
||||
])->getDeletedCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function gc($maxlifetime)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
$methodName = $this->mongo instanceof \MongoDB\Client ? 'deleteOne' : 'remove';
|
||||
$expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000);
|
||||
|
||||
$this->getCollection()->$methodName(array(
|
||||
$this->options['expiry_field'] => array('$lt' => $this->createDateTime()),
|
||||
));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function write($sessionId, $data)
|
||||
{
|
||||
$expiry = $this->createDateTime(time() + (int) ini_get('session.gc_maxlifetime'));
|
||||
|
||||
$fields = array(
|
||||
$this->options['time_field'] => $this->createDateTime(),
|
||||
$fields = [
|
||||
$this->options['time_field'] => new UTCDateTime(),
|
||||
$this->options['expiry_field'] => $expiry,
|
||||
$this->options['data_field'] => new Binary($data, Binary::TYPE_OLD_BINARY),
|
||||
];
|
||||
|
||||
$this->getCollection()->updateOne(
|
||||
[$this->options['id_field'] => $sessionId],
|
||||
['$set' => $fields],
|
||||
['upsert' => true]
|
||||
);
|
||||
|
||||
$options = array('upsert' => true);
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($this->mongo instanceof \MongoDB\Client) {
|
||||
$fields[$this->options['data_field']] = new \MongoDB\BSON\Binary($data, \MongoDB\BSON\Binary::TYPE_OLD_BINARY);
|
||||
} else {
|
||||
$fields[$this->options['data_field']] = new \MongoBinData($data, \MongoBinData::BYTE_ARRAY);
|
||||
$options['multiple'] = false;
|
||||
}
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
$expiry = new UTCDateTime((time() + (int) \ini_get('session.gc_maxlifetime')) * 1000);
|
||||
|
||||
$methodName = $this->mongo instanceof \MongoDB\Client ? 'updateOne' : 'update';
|
||||
|
||||
$this->getCollection()->$methodName(
|
||||
array($this->options['id_field'] => $sessionId),
|
||||
array('$set' => $fields),
|
||||
$options
|
||||
$this->getCollection()->updateOne(
|
||||
[$this->options['id_field'] => $sessionId],
|
||||
['$set' => [
|
||||
$this->options['time_field'] => new UTCDateTime(),
|
||||
$this->options['expiry_field'] => $expiry,
|
||||
]]
|
||||
);
|
||||
|
||||
return true;
|
||||
@@ -166,67 +140,27 @@ class MongoDbSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read($sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
$dbData = $this->getCollection()->findOne(array(
|
||||
$dbData = $this->getCollection()->findOne([
|
||||
$this->options['id_field'] => $sessionId,
|
||||
$this->options['expiry_field'] => array('$gte' => $this->createDateTime()),
|
||||
));
|
||||
$this->options['expiry_field'] => ['$gte' => new UTCDateTime()],
|
||||
]);
|
||||
|
||||
if (null === $dbData) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($dbData[$this->options['data_field']] instanceof \MongoDB\BSON\Binary) {
|
||||
return $dbData[$this->options['data_field']]->getData();
|
||||
}
|
||||
|
||||
return $dbData[$this->options['data_field']]->bin;
|
||||
return $dbData[$this->options['data_field']]->getData();
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a "MongoCollection" instance.
|
||||
*
|
||||
* @return \MongoCollection
|
||||
*/
|
||||
private function getCollection()
|
||||
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 a Mongo instance.
|
||||
*
|
||||
* @return \Mongo|\MongoClient|\MongoDB\Client
|
||||
*/
|
||||
protected function getMongo()
|
||||
protected function getMongo(): Client
|
||||
{
|
||||
return $this->mongo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a date object using the class appropriate for the current mongo connection.
|
||||
*
|
||||
* Return an instance of a MongoDate or \MongoDB\BSON\UTCDateTime
|
||||
*
|
||||
* @param int $seconds An integer representing UTC seconds since Jan 1 1970. Defaults to now.
|
||||
*
|
||||
* @return \MongoDate|\MongoDB\BSON\UTCDateTime
|
||||
*/
|
||||
private function createDateTime($seconds = null)
|
||||
{
|
||||
if (null === $seconds) {
|
||||
$seconds = time();
|
||||
}
|
||||
|
||||
if ($this->mongo instanceof \MongoDB\Client) {
|
||||
return new \MongoDB\BSON\UTCDateTime($seconds * 1000);
|
||||
}
|
||||
|
||||
return new \MongoDate($seconds);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,36 +12,33 @@
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* NativeFileSessionHandler.
|
||||
*
|
||||
* Native session handler using PHP's built in file storage.
|
||||
*
|
||||
* @author Drak <drak@zikula.org>
|
||||
*/
|
||||
class NativeFileSessionHandler extends NativeSessionHandler
|
||||
class NativeFileSessionHandler extends \SessionHandler
|
||||
{
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* @param string $savePath Path of directory to save session files
|
||||
* Default null will leave setting as defined by PHP.
|
||||
* '/path', 'N;/path', or 'N;octal-mode;/path
|
||||
*
|
||||
* @see http://php.net/session.configuration.php#ini.session.save-path for further details.
|
||||
* @see https://php.net/session.configuration#ini.session.save-path for further details.
|
||||
*
|
||||
* @throws \InvalidArgumentException On invalid $savePath
|
||||
* @throws \RuntimeException When failing to create the save directory
|
||||
*/
|
||||
public function __construct($savePath = null)
|
||||
public function __construct(string $savePath = null)
|
||||
{
|
||||
if (null === $savePath) {
|
||||
$savePath = ini_get('session.save_path');
|
||||
$savePath = \ini_get('session.save_path');
|
||||
}
|
||||
|
||||
$baseDir = $savePath;
|
||||
|
||||
if ($count = substr_count($savePath, ';')) {
|
||||
if ($count > 2) {
|
||||
throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'', $savePath));
|
||||
throw new \InvalidArgumentException(sprintf('Invalid argument $savePath \'%s\'.', $savePath));
|
||||
}
|
||||
|
||||
// characters after last ';' are the path
|
||||
@@ -49,7 +46,7 @@ class NativeFileSessionHandler extends NativeSessionHandler
|
||||
}
|
||||
|
||||
if ($baseDir && !is_dir($baseDir) && !@mkdir($baseDir, 0777, true) && !is_dir($baseDir)) {
|
||||
throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s"', $baseDir));
|
||||
throw new \RuntimeException(sprintf('Session Storage was not able to create directory "%s".', $baseDir));
|
||||
}
|
||||
|
||||
ini_set('session.save_path', $savePath);
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* Adds SessionHandler functionality if available.
|
||||
*
|
||||
* @see http://php.net/sessionhandler
|
||||
*/
|
||||
class NativeSessionHandler extends \SessionHandler
|
||||
{
|
||||
}
|
||||
@@ -12,18 +12,18 @@
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* NullSessionHandler.
|
||||
*
|
||||
* Can be used in unit testing or in a situations where persisted sessions are not desired.
|
||||
*
|
||||
* @author Drak <drak@zikula.org>
|
||||
*/
|
||||
class NullSessionHandler implements \SessionHandlerInterface
|
||||
class NullSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function open($savePath, $sessionName)
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function validateId(string $sessionId): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -31,23 +31,12 @@ class NullSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read($sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function write($sessionId, $data)
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -55,7 +44,7 @@ class NullSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function destroy($sessionId)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
@@ -63,8 +52,13 @@ class NullSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function gc($maxlifetime)
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,13 +32,13 @@ namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
* Saving it in a character column could corrupt the data. You can use createTable()
|
||||
* to initialize a correctly defined table.
|
||||
*
|
||||
* @see http://php.net/sessionhandlerinterface
|
||||
* @see https://php.net/sessionhandlerinterface
|
||||
*
|
||||
* @author Fabien Potencier <fabien@symfony.com>
|
||||
* @author Michael Williams <michael.williams@funsational.com>
|
||||
* @author Tobias Schultze <http://tobion.de>
|
||||
*/
|
||||
class PdoSessionHandler implements \SessionHandlerInterface
|
||||
class PdoSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
/**
|
||||
* No locking is done. This means sessions are prone to loss of data due to
|
||||
@@ -46,7 +46,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
* write will win in this case. It might be useful when you implement your own
|
||||
* logic to deal with this like an optimistic approach.
|
||||
*/
|
||||
const LOCK_NONE = 0;
|
||||
public const LOCK_NONE = 0;
|
||||
|
||||
/**
|
||||
* Creates an application-level lock on a session. The disadvantage is that the
|
||||
@@ -55,7 +55,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
* does not require a transaction.
|
||||
* This mode is not available for SQLite and not yet implemented for oci and sqlsrv.
|
||||
*/
|
||||
const LOCK_ADVISORY = 1;
|
||||
public const LOCK_ADVISORY = 1;
|
||||
|
||||
/**
|
||||
* Issues a real row lock. Since it uses a transaction between opening and
|
||||
@@ -63,93 +63,65 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
* that you also use for your application logic. This mode is the default because
|
||||
* it's the only reliable solution across DBMSs.
|
||||
*/
|
||||
const LOCK_TRANSACTIONAL = 2;
|
||||
public const LOCK_TRANSACTIONAL = 2;
|
||||
|
||||
/**
|
||||
* @var \PDO|null PDO instance or null when not connected yet
|
||||
*/
|
||||
private $pdo;
|
||||
|
||||
/**
|
||||
* @var string|null|false DSN string or null for session.save_path or false when lazy connection disabled
|
||||
* DSN string or null for session.save_path or false when lazy connection disabled.
|
||||
*/
|
||||
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 Database driver
|
||||
* Username when lazy-connect.
|
||||
*/
|
||||
private $driver;
|
||||
private string $username = '';
|
||||
|
||||
/**
|
||||
* @var string Table name
|
||||
* Password when lazy-connect.
|
||||
*/
|
||||
private $table = 'sessions';
|
||||
private string $password = '';
|
||||
|
||||
/**
|
||||
* @var string Column for session id
|
||||
* Connection options when lazy-connect.
|
||||
*/
|
||||
private $idCol = 'sess_id';
|
||||
private array $connectionOptions = [];
|
||||
|
||||
/**
|
||||
* @var string Column for session data
|
||||
* The strategy for locking, see constants.
|
||||
*/
|
||||
private $dataCol = 'sess_data';
|
||||
|
||||
/**
|
||||
* @var string Column for lifetime
|
||||
*/
|
||||
private $lifetimeCol = 'sess_lifetime';
|
||||
|
||||
/**
|
||||
* @var string Column for timestamp
|
||||
*/
|
||||
private $timeCol = 'sess_time';
|
||||
|
||||
/**
|
||||
* @var string Username when lazy-connect
|
||||
*/
|
||||
private $username = '';
|
||||
|
||||
/**
|
||||
* @var string Password when lazy-connect
|
||||
*/
|
||||
private $password = '';
|
||||
|
||||
/**
|
||||
* @var array Connection options when lazy-connect
|
||||
*/
|
||||
private $connectionOptions = array();
|
||||
|
||||
/**
|
||||
* @var int The strategy for locking, see constants
|
||||
*/
|
||||
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 = array();
|
||||
private array $unlockStatements = [];
|
||||
|
||||
/**
|
||||
* @var bool True when the current session exists but expired according to session.gc_maxlifetime
|
||||
* True when the current session exists but expired according to session.gc_maxlifetime.
|
||||
*/
|
||||
private $sessionExpired = false;
|
||||
private bool $sessionExpired = false;
|
||||
|
||||
/**
|
||||
* @var bool Whether a transaction is active
|
||||
* Whether a transaction is active.
|
||||
*/
|
||||
private $inTransaction = false;
|
||||
private bool $inTransaction = false;
|
||||
|
||||
/**
|
||||
* @var bool Whether gc() has been called
|
||||
* Whether gc() has been called.
|
||||
*/
|
||||
private $gcCalled = false;
|
||||
private bool $gcCalled = false;
|
||||
|
||||
/**
|
||||
* Constructor.
|
||||
*
|
||||
* You can either pass an existing database connection as PDO instance or
|
||||
* pass a DSN string that will be used to lazy-connect to the database
|
||||
* when the session is actually used. Furthermore it's possible to pass null
|
||||
@@ -163,36 +135,37 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
* * db_time_col: The column where to store the timestamp [default: sess_time]
|
||||
* * db_username: The username when lazy-connect [default: '']
|
||||
* * db_password: The password when lazy-connect [default: '']
|
||||
* * db_connection_options: An array of driver-specific connection options [default: array()]
|
||||
* * db_connection_options: An array of driver-specific connection options [default: []]
|
||||
* * lock_mode: The strategy for locking, see constants [default: LOCK_TRANSACTIONAL]
|
||||
*
|
||||
* @param \PDO|string|null $pdoOrDsn A \PDO instance or DSN string or null
|
||||
* @param array $options An associative array of options
|
||||
* @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 = array())
|
||||
public function __construct(\PDO|string $pdoOrDsn = null, array $options = [])
|
||||
{
|
||||
if ($pdoOrDsn instanceof \PDO) {
|
||||
if (\PDO::ERRMODE_EXCEPTION !== $pdoOrDsn->getAttribute(\PDO::ATTR_ERRMODE)) {
|
||||
throw new \InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION))', __CLASS__));
|
||||
throw new \InvalidArgumentException(sprintf('"%s" requires PDO error mode attribute be set to throw Exceptions (i.e. $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION)).', __CLASS__));
|
||||
}
|
||||
|
||||
$this->pdo = $pdoOrDsn;
|
||||
$this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
|
||||
} elseif (\is_string($pdoOrDsn) && str_contains($pdoOrDsn, '://')) {
|
||||
$this->dsn = $this->buildDsnFromUrl($pdoOrDsn);
|
||||
} else {
|
||||
$this->dsn = $pdoOrDsn;
|
||||
}
|
||||
|
||||
$this->table = isset($options['db_table']) ? $options['db_table'] : $this->table;
|
||||
$this->idCol = isset($options['db_id_col']) ? $options['db_id_col'] : $this->idCol;
|
||||
$this->dataCol = isset($options['db_data_col']) ? $options['db_data_col'] : $this->dataCol;
|
||||
$this->lifetimeCol = isset($options['db_lifetime_col']) ? $options['db_lifetime_col'] : $this->lifetimeCol;
|
||||
$this->timeCol = isset($options['db_time_col']) ? $options['db_time_col'] : $this->timeCol;
|
||||
$this->username = isset($options['db_username']) ? $options['db_username'] : $this->username;
|
||||
$this->password = isset($options['db_password']) ? $options['db_password'] : $this->password;
|
||||
$this->connectionOptions = isset($options['db_connection_options']) ? $options['db_connection_options'] : $this->connectionOptions;
|
||||
$this->lockMode = isset($options['lock_mode']) ? $options['lock_mode'] : $this->lockMode;
|
||||
$this->table = $options['db_table'] ?? $this->table;
|
||||
$this->idCol = $options['db_id_col'] ?? $this->idCol;
|
||||
$this->dataCol = $options['db_data_col'] ?? $this->dataCol;
|
||||
$this->lifetimeCol = $options['db_lifetime_col'] ?? $this->lifetimeCol;
|
||||
$this->timeCol = $options['db_time_col'] ?? $this->timeCol;
|
||||
$this->username = $options['db_username'] ?? $this->username;
|
||||
$this->password = $options['db_password'] ?? $this->password;
|
||||
$this->connectionOptions = $options['db_connection_options'] ?? $this->connectionOptions;
|
||||
$this->lockMode = $options['lock_mode'] ?? $this->lockMode;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -218,7 +191,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
// - 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 MEDIUMINT NOT NULL, $this->timeCol INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB";
|
||||
$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)";
|
||||
@@ -238,6 +211,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
|
||||
try {
|
||||
$this->pdo->exec($sql);
|
||||
$this->pdo->exec("CREATE INDEX EXPIRY ON $this->table ($this->lifetimeCol)");
|
||||
} catch (\PDOException $e) {
|
||||
$this->rollback();
|
||||
|
||||
@@ -249,33 +223,27 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
* 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 Whether current session expired
|
||||
*/
|
||||
public function isSessionExpired()
|
||||
public function isSessionExpired(): bool
|
||||
{
|
||||
return $this->sessionExpired;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function open($savePath, $sessionName)
|
||||
public function open(string $savePath, string $sessionName): bool
|
||||
{
|
||||
if (null === $this->pdo) {
|
||||
$this->sessionExpired = false;
|
||||
|
||||
if (!isset($this->pdo)) {
|
||||
$this->connect($this->dsn ?: $savePath);
|
||||
}
|
||||
|
||||
return true;
|
||||
return parent::open($savePath, $sessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read($sessionId)
|
||||
public function read(string $sessionId): string
|
||||
{
|
||||
try {
|
||||
return $this->doRead($sessionId);
|
||||
return parent::read($sessionId);
|
||||
} catch (\PDOException $e) {
|
||||
$this->rollback();
|
||||
|
||||
@@ -283,22 +251,19 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
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.
|
||||
$this->gcCalled = true;
|
||||
|
||||
return true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function destroy($sessionId)
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
// delete the record associated with this id
|
||||
$sql = "DELETE FROM $this->table WHERE $this->idCol = :id";
|
||||
@@ -319,9 +284,9 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function write($sessionId, $data)
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
$maxlifetime = (int) ini_get('session.gc_maxlifetime');
|
||||
$maxlifetime = (int) \ini_get('session.gc_maxlifetime');
|
||||
|
||||
try {
|
||||
// We use a single MERGE SQL query when supported by the database.
|
||||
@@ -332,13 +297,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
return true;
|
||||
}
|
||||
|
||||
$updateStmt = $this->pdo->prepare(
|
||||
"UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :lifetime, $this->timeCol = :time WHERE $this->idCol = :id"
|
||||
);
|
||||
$updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$updateStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
||||
$updateStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
||||
$updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
$updateStmt = $this->getUpdateStatement($sessionId, $data, $maxlifetime);
|
||||
$updateStmt->execute();
|
||||
|
||||
// When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in
|
||||
@@ -348,17 +307,11 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
// false positives due to longer gap locking.
|
||||
if (!$updateStmt->rowCount()) {
|
||||
try {
|
||||
$insertStmt = $this->pdo->prepare(
|
||||
"INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
|
||||
);
|
||||
$insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$insertStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
||||
$insertStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
||||
$insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
$insertStmt = $this->getInsertStatement($sessionId, $data, $maxlifetime);
|
||||
$insertStmt->execute();
|
||||
} catch (\PDOException $e) {
|
||||
// Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys
|
||||
if (0 === strpos($e->getCode(), '23')) {
|
||||
if (str_starts_with($e->getCode(), '23')) {
|
||||
$updateStmt->execute();
|
||||
} else {
|
||||
throw $e;
|
||||
@@ -374,10 +327,28 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function close()
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
$expiry = time() + (int) \ini_get('session.gc_maxlifetime');
|
||||
|
||||
try {
|
||||
$updateStmt = $this->pdo->prepare(
|
||||
"UPDATE $this->table SET $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id"
|
||||
);
|
||||
$updateStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$updateStmt->bindParam(':expiry', $expiry, \PDO::PARAM_INT);
|
||||
$updateStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
$updateStmt->execute();
|
||||
} catch (\PDOException $e) {
|
||||
$this->rollback();
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public function close(): bool
|
||||
{
|
||||
$this->commit();
|
||||
|
||||
@@ -389,15 +360,14 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
$this->gcCalled = false;
|
||||
|
||||
// delete the session records that have expired
|
||||
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol + $this->timeCol < :time";
|
||||
|
||||
$sql = "DELETE FROM $this->table WHERE $this->lifetimeCol < :time";
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
$stmt->execute();
|
||||
}
|
||||
|
||||
if (false !== $this->dsn) {
|
||||
$this->pdo = null; // only close lazy-connection
|
||||
unset($this->pdo, $this->driver); // only close lazy-connection
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -405,16 +375,128 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
|
||||
/**
|
||||
* Lazy-connects to the database.
|
||||
*
|
||||
* @param string $dsn DSN string
|
||||
*/
|
||||
private function connect($dsn)
|
||||
private function connect(string $dsn): void
|
||||
{
|
||||
$this->pdo = new \PDO($dsn, $this->username, $this->password, $this->connectionOptions);
|
||||
$this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
|
||||
$this->driver = $this->pdo->getAttribute(\PDO::ATTR_DRIVER_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a PDO DSN from a URL-like connection string.
|
||||
*
|
||||
* @todo implement missing support for oci DSN (which look totally different from other PDO ones)
|
||||
*/
|
||||
private function buildDsnFromUrl(string $dsnOrUrl): string
|
||||
{
|
||||
// (pdo_)?sqlite3?:///... => (pdo_)?sqlite3?://localhost/... or else the URL will be invalid
|
||||
$url = preg_replace('#^((?:pdo_)?sqlite3?):///#', '$1://localhost/', $dsnOrUrl);
|
||||
|
||||
$params = parse_url($url);
|
||||
|
||||
if (false === $params) {
|
||||
return $dsnOrUrl; // If the URL is not valid, let's assume it might be a DSN already.
|
||||
}
|
||||
|
||||
$params = array_map('rawurldecode', $params);
|
||||
|
||||
// Override the default username and password. Values passed through options will still win over these in the constructor.
|
||||
if (isset($params['user'])) {
|
||||
$this->username = $params['user'];
|
||||
}
|
||||
|
||||
if (isset($params['pass'])) {
|
||||
$this->password = $params['pass'];
|
||||
}
|
||||
|
||||
if (!isset($params['scheme'])) {
|
||||
throw new \InvalidArgumentException('URLs without scheme are not supported to configure the PdoSessionHandler.');
|
||||
}
|
||||
|
||||
$driverAliasMap = [
|
||||
'mssql' => 'sqlsrv',
|
||||
'mysql2' => 'mysql', // Amazon RDS, for some weird reason
|
||||
'postgres' => 'pgsql',
|
||||
'postgresql' => 'pgsql',
|
||||
'sqlite3' => 'sqlite',
|
||||
];
|
||||
|
||||
$driver = $driverAliasMap[$params['scheme']] ?? $params['scheme'];
|
||||
|
||||
// Doctrine DBAL supports passing its internal pdo_* driver names directly too (allowing both dashes and underscores). This allows supporting the same here.
|
||||
if (str_starts_with($driver, 'pdo_') || str_starts_with($driver, 'pdo-')) {
|
||||
$driver = substr($driver, 4);
|
||||
}
|
||||
|
||||
$dsn = null;
|
||||
switch ($driver) {
|
||||
case 'mysql':
|
||||
$dsn = 'mysql:';
|
||||
if ('' !== ($params['query'] ?? '')) {
|
||||
$queryParams = [];
|
||||
parse_str($params['query'], $queryParams);
|
||||
if ('' !== ($queryParams['charset'] ?? '')) {
|
||||
$dsn .= 'charset='.$queryParams['charset'].';';
|
||||
}
|
||||
|
||||
if ('' !== ($queryParams['unix_socket'] ?? '')) {
|
||||
$dsn .= 'unix_socket='.$queryParams['unix_socket'].';';
|
||||
|
||||
if (isset($params['path'])) {
|
||||
$dbName = substr($params['path'], 1); // Remove the leading slash
|
||||
$dsn .= 'dbname='.$dbName.';';
|
||||
}
|
||||
|
||||
return $dsn;
|
||||
}
|
||||
}
|
||||
// If "unix_socket" is not in the query, we continue with the same process as pgsql
|
||||
// no break
|
||||
case 'pgsql':
|
||||
$dsn ?? $dsn = 'pgsql:';
|
||||
|
||||
if (isset($params['host']) && '' !== $params['host']) {
|
||||
$dsn .= 'host='.$params['host'].';';
|
||||
}
|
||||
|
||||
if (isset($params['port']) && '' !== $params['port']) {
|
||||
$dsn .= 'port='.$params['port'].';';
|
||||
}
|
||||
|
||||
if (isset($params['path'])) {
|
||||
$dbName = substr($params['path'], 1); // Remove the leading slash
|
||||
$dsn .= 'dbname='.$dbName.';';
|
||||
}
|
||||
|
||||
return $dsn;
|
||||
|
||||
case 'sqlite':
|
||||
return 'sqlite:'.substr($params['path'], 1);
|
||||
|
||||
case 'sqlsrv':
|
||||
$dsn = 'sqlsrv:server=';
|
||||
|
||||
if (isset($params['host'])) {
|
||||
$dsn .= $params['host'];
|
||||
}
|
||||
|
||||
if (isset($params['port']) && '' !== $params['port']) {
|
||||
$dsn .= ','.$params['port'];
|
||||
}
|
||||
|
||||
if (isset($params['path'])) {
|
||||
$dbName = substr($params['path'], 1); // Remove the leading slash
|
||||
$dsn .= ';Database='.$dbName;
|
||||
}
|
||||
|
||||
return $dsn;
|
||||
|
||||
default:
|
||||
throw new \InvalidArgumentException(sprintf('The scheme "%s" is not supported by the PdoSessionHandler URL configuration. Pass a PDO DSN directly.', $params['scheme']));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to begin a transaction.
|
||||
*
|
||||
@@ -424,10 +506,10 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
* PDO::rollback or PDO::inTransaction for SQLite.
|
||||
*
|
||||
* Also MySQLs default isolation, REPEATABLE READ, causes deadlock for different sessions
|
||||
* due to http://www.mysqlperformanceblog.com/2013/12/12/one-more-innodb-gap-lock-to-avoid/ .
|
||||
* due to https://percona.com/blog/2013/12/12/one-more-innodb-gap-lock-to-avoid/ .
|
||||
* So we change it to READ COMMITTED.
|
||||
*/
|
||||
private function beginTransaction()
|
||||
private function beginTransaction(): void
|
||||
{
|
||||
if (!$this->inTransaction) {
|
||||
if ('sqlite' === $this->driver) {
|
||||
@@ -445,7 +527,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* Helper method to commit a transaction.
|
||||
*/
|
||||
private function commit()
|
||||
private function commit(): void
|
||||
{
|
||||
if ($this->inTransaction) {
|
||||
try {
|
||||
@@ -467,7 +549,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
/**
|
||||
* Helper method to rollback a transaction.
|
||||
*/
|
||||
private function rollback()
|
||||
private function rollback(): void
|
||||
{
|
||||
// We only need to rollback if we are in a transaction. Otherwise the resulting
|
||||
// error would hide the real problem why rollback was called. We might not be
|
||||
@@ -488,15 +570,9 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* @param string $sessionId Session ID
|
||||
*
|
||||
* @return string The session data
|
||||
*/
|
||||
private function doRead($sessionId)
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
$this->sessionExpired = false;
|
||||
|
||||
if (self::LOCK_ADVISORY === $this->lockMode) {
|
||||
$this->unlockStatements[] = $this->doAdvisoryLock($sessionId);
|
||||
}
|
||||
@@ -504,37 +580,41 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
$selectSql = $this->getSelectSql();
|
||||
$selectStmt = $this->pdo->prepare($selectSql);
|
||||
$selectStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$insertStmt = null;
|
||||
|
||||
do {
|
||||
while (true) {
|
||||
$selectStmt->execute();
|
||||
$sessionRows = $selectStmt->fetchAll(\PDO::FETCH_NUM);
|
||||
|
||||
if ($sessionRows) {
|
||||
if ($sessionRows[0][1] + $sessionRows[0][2] < time()) {
|
||||
$expiry = (int) $sessionRows[0][1];
|
||||
|
||||
if ($expiry < time()) {
|
||||
$this->sessionExpired = true;
|
||||
|
||||
return '';
|
||||
}
|
||||
|
||||
return is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
|
||||
return \is_resource($sessionRows[0][0]) ? stream_get_contents($sessionRows[0][0]) : $sessionRows[0][0];
|
||||
}
|
||||
|
||||
if (self::LOCK_TRANSACTIONAL === $this->lockMode && 'sqlite' !== $this->driver) {
|
||||
if (null !== $insertStmt) {
|
||||
$this->rollback();
|
||||
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) {
|
||||
// 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
|
||||
// until other connections to the session are committed.
|
||||
try {
|
||||
$insertStmt = $this->pdo->prepare(
|
||||
"INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)"
|
||||
);
|
||||
$insertStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$insertStmt->bindValue(':data', '', \PDO::PARAM_LOB);
|
||||
$insertStmt->bindValue(':lifetime', 0, \PDO::PARAM_INT);
|
||||
$insertStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
$insertStmt = $this->getInsertStatement($sessionId, '', 0);
|
||||
$insertStmt->execute();
|
||||
} catch (\PDOException $e) {
|
||||
// Catch duplicate key error because other connection created the session already.
|
||||
// It would only not be the case when the other connection destroyed the session.
|
||||
if (0 === strpos($e->getCode(), '23')) {
|
||||
if (str_starts_with($e->getCode(), '23')) {
|
||||
// Retrieve finished session data written by concurrent connection by restarting the loop.
|
||||
// We have to start a new transaction as a failed query will mark the current transaction as
|
||||
// aborted in PostgreSQL and disallow further queries within it.
|
||||
@@ -548,14 +628,12 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
}
|
||||
|
||||
return '';
|
||||
} while (true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Executes an application-level lock on the database.
|
||||
*
|
||||
* @param string $sessionId Session ID
|
||||
*
|
||||
* @return \PDOStatement The statement that needs to be executed later to release the lock
|
||||
*
|
||||
* @throws \DomainException When an unsupported PDO driver is used
|
||||
@@ -564,27 +642,29 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
* - for oci using DBMS_LOCK.REQUEST
|
||||
* - for sqlsrv using sp_getapplock with LockOwner = Session
|
||||
*/
|
||||
private function doAdvisoryLock($sessionId)
|
||||
private function doAdvisoryLock(string $sessionId): \PDOStatement
|
||||
{
|
||||
switch ($this->driver) {
|
||||
case 'mysql':
|
||||
// MySQL 5.7.5 and later enforces a maximum length on lock names of 64 characters. Previously, no limit was enforced.
|
||||
$lockId = substr($sessionId, 0, 64);
|
||||
// should we handle the return value? 0 on timeout, null on error
|
||||
// we use a timeout of 50 seconds which is also the default for innodb_lock_wait_timeout
|
||||
$stmt = $this->pdo->prepare('SELECT GET_LOCK(:key, 50)');
|
||||
$stmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
|
||||
$stmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
|
||||
$stmt->execute();
|
||||
|
||||
$releaseStmt = $this->pdo->prepare('DO RELEASE_LOCK(:key)');
|
||||
$releaseStmt->bindValue(':key', $sessionId, \PDO::PARAM_STR);
|
||||
$releaseStmt->bindValue(':key', $lockId, \PDO::PARAM_STR);
|
||||
|
||||
return $releaseStmt;
|
||||
case 'pgsql':
|
||||
// Obtaining an exclusive session level advisory lock requires an integer key.
|
||||
// So we convert the HEX representation of the session id to an integer.
|
||||
// Since integers are signed, we have to skip one hex char to fit in the range.
|
||||
if (4 === PHP_INT_SIZE) {
|
||||
$sessionInt1 = hexdec(substr($sessionId, 0, 7));
|
||||
$sessionInt2 = hexdec(substr($sessionId, 7, 7));
|
||||
// When session.sid_bits_per_character > 4, the session id can contain non-hex-characters.
|
||||
// So we cannot just use hexdec().
|
||||
if (4 === \PHP_INT_SIZE) {
|
||||
$sessionInt1 = $this->convertStringToInt($sessionId);
|
||||
$sessionInt2 = $this->convertStringToInt(substr($sessionId, 4, 4));
|
||||
|
||||
$stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key1, :key2)');
|
||||
$stmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
|
||||
@@ -595,7 +675,7 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
$releaseStmt->bindValue(':key1', $sessionInt1, \PDO::PARAM_INT);
|
||||
$releaseStmt->bindValue(':key2', $sessionInt2, \PDO::PARAM_INT);
|
||||
} else {
|
||||
$sessionBigInt = hexdec(substr($sessionId, 0, 15));
|
||||
$sessionBigInt = $this->convertStringToInt($sessionId);
|
||||
|
||||
$stmt = $this->pdo->prepare('SELECT pg_advisory_lock(:key)');
|
||||
$stmt->bindValue(':key', $sessionBigInt, \PDO::PARAM_INT);
|
||||
@@ -614,13 +694,28 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a locking or nonlocking SQL query to read session information.
|
||||
* Encodes the first 4 (when PHP_INT_SIZE == 4) or 8 characters of the string as an integer.
|
||||
*
|
||||
* @return string The SQL string
|
||||
* Keep in mind, PHP integers are signed.
|
||||
*/
|
||||
private function convertStringToInt(string $string): int
|
||||
{
|
||||
if (4 === \PHP_INT_SIZE) {
|
||||
return (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
|
||||
}
|
||||
|
||||
$int1 = (\ord($string[7]) << 24) + (\ord($string[6]) << 16) + (\ord($string[5]) << 8) + \ord($string[4]);
|
||||
$int2 = (\ord($string[3]) << 24) + (\ord($string[2]) << 16) + (\ord($string[1]) << 8) + \ord($string[0]);
|
||||
|
||||
return $int2 + ($int1 << 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a locking or nonlocking SQL query to read session information.
|
||||
*
|
||||
* @throws \DomainException When an unsupported PDO driver is used
|
||||
*/
|
||||
private function getSelectSql()
|
||||
private function getSelectSql(): string
|
||||
{
|
||||
if (self::LOCK_TRANSACTIONAL === $this->lockMode) {
|
||||
$this->beginTransaction();
|
||||
@@ -629,9 +724,9 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
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;
|
||||
@@ -640,80 +735,120 @@ class PdoSessionHandler implements \SessionHandlerInterface
|
||||
}
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an insert statement supported by the database for writing session data.
|
||||
*/
|
||||
private function getInsertStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
|
||||
{
|
||||
switch ($this->driver) {
|
||||
case 'oci':
|
||||
$data = fopen('php://memory', 'r+');
|
||||
fwrite($data, $sessionData);
|
||||
rewind($data);
|
||||
$sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, EMPTY_BLOB(), :expiry, :time) RETURNING $this->dataCol into :data";
|
||||
break;
|
||||
default:
|
||||
$data = $sessionData;
|
||||
$sql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)";
|
||||
break;
|
||||
}
|
||||
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
||||
$stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
|
||||
return $stmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns an update statement supported by the database for writing session data.
|
||||
*/
|
||||
private function getUpdateStatement(string $sessionId, string $sessionData, int $maxlifetime): \PDOStatement
|
||||
{
|
||||
switch ($this->driver) {
|
||||
case 'oci':
|
||||
$data = fopen('php://memory', 'r+');
|
||||
fwrite($data, $sessionData);
|
||||
rewind($data);
|
||||
$sql = "UPDATE $this->table SET $this->dataCol = EMPTY_BLOB(), $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id RETURNING $this->dataCol into :data";
|
||||
break;
|
||||
default:
|
||||
$data = $sessionData;
|
||||
$sql = "UPDATE $this->table SET $this->dataCol = :data, $this->lifetimeCol = :expiry, $this->timeCol = :time WHERE $this->idCol = :id";
|
||||
break;
|
||||
}
|
||||
|
||||
$stmt = $this->pdo->prepare($sql);
|
||||
$stmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$stmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
||||
$stmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
|
||||
$stmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
|
||||
return $stmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a merge/upsert (i.e. insert or update) statement when supported by the database for writing session data.
|
||||
*
|
||||
* @param string $sessionId Session ID
|
||||
* @param string $data Encoded session data
|
||||
* @param int $maxlifetime session.gc_maxlifetime
|
||||
*
|
||||
* @return \PDOStatement|null The merge statement or null when not supported
|
||||
*/
|
||||
private function getMergeStatement($sessionId, $data, $maxlifetime)
|
||||
private function getMergeStatement(string $sessionId, string $data, int $maxlifetime): ?\PDOStatement
|
||||
{
|
||||
$mergeSql = null;
|
||||
switch (true) {
|
||||
case 'mysql' === $this->driver:
|
||||
$mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
|
||||
$mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ".
|
||||
"ON DUPLICATE KEY UPDATE $this->dataCol = VALUES($this->dataCol), $this->lifetimeCol = VALUES($this->lifetimeCol), $this->timeCol = VALUES($this->timeCol)";
|
||||
break;
|
||||
case 'oci' === $this->driver:
|
||||
// DUAL is Oracle specific dummy table
|
||||
$mergeSql = "MERGE INTO $this->table USING DUAL ON ($this->idCol = ?) ".
|
||||
"WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
|
||||
"WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?";
|
||||
break;
|
||||
case 'sqlsrv' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '10', '>='):
|
||||
// MERGE is only available since SQL Server 2008 and must be terminated by semicolon
|
||||
// It also requires HOLDLOCK according to http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx
|
||||
// It also requires HOLDLOCK according to https://weblogs.sqlteam.com/dang/2009/01/31/upsert-race-condition-with-merge/
|
||||
$mergeSql = "MERGE INTO $this->table WITH (HOLDLOCK) USING (SELECT 1 AS dummy) AS src ON ($this->idCol = ?) ".
|
||||
"WHEN NOT MATCHED THEN INSERT ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (?, ?, ?, ?) ".
|
||||
"WHEN MATCHED THEN UPDATE SET $this->dataCol = ?, $this->lifetimeCol = ?, $this->timeCol = ?;";
|
||||
break;
|
||||
case 'sqlite' === $this->driver:
|
||||
$mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time)";
|
||||
$mergeSql = "INSERT OR REPLACE INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time)";
|
||||
break;
|
||||
case 'pgsql' === $this->driver && version_compare($this->pdo->getAttribute(\PDO::ATTR_SERVER_VERSION), '9.5', '>='):
|
||||
$mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :lifetime, :time) ".
|
||||
$mergeSql = "INSERT INTO $this->table ($this->idCol, $this->dataCol, $this->lifetimeCol, $this->timeCol) VALUES (:id, :data, :expiry, :time) ".
|
||||
"ON CONFLICT ($this->idCol) DO UPDATE SET ($this->dataCol, $this->lifetimeCol, $this->timeCol) = (EXCLUDED.$this->dataCol, EXCLUDED.$this->lifetimeCol, EXCLUDED.$this->timeCol)";
|
||||
break;
|
||||
default:
|
||||
// MERGE is not supported with LOBs: https://oracle.com/technetwork/articles/fuecks-lobs-095315.html
|
||||
return null;
|
||||
}
|
||||
|
||||
if (null !== $mergeSql) {
|
||||
$mergeStmt = $this->pdo->prepare($mergeSql);
|
||||
$mergeStmt = $this->pdo->prepare($mergeSql);
|
||||
|
||||
if ('sqlsrv' === $this->driver || 'oci' === $this->driver) {
|
||||
$mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR);
|
||||
$mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR);
|
||||
$mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB);
|
||||
$mergeStmt->bindParam(4, $maxlifetime, \PDO::PARAM_INT);
|
||||
$mergeStmt->bindValue(5, time(), \PDO::PARAM_INT);
|
||||
$mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB);
|
||||
$mergeStmt->bindParam(7, $maxlifetime, \PDO::PARAM_INT);
|
||||
$mergeStmt->bindValue(8, time(), \PDO::PARAM_INT);
|
||||
} else {
|
||||
$mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
||||
$mergeStmt->bindParam(':lifetime', $maxlifetime, \PDO::PARAM_INT);
|
||||
$mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
}
|
||||
|
||||
return $mergeStmt;
|
||||
if ('sqlsrv' === $this->driver) {
|
||||
$mergeStmt->bindParam(1, $sessionId, \PDO::PARAM_STR);
|
||||
$mergeStmt->bindParam(2, $sessionId, \PDO::PARAM_STR);
|
||||
$mergeStmt->bindParam(3, $data, \PDO::PARAM_LOB);
|
||||
$mergeStmt->bindValue(4, time() + $maxlifetime, \PDO::PARAM_INT);
|
||||
$mergeStmt->bindValue(5, time(), \PDO::PARAM_INT);
|
||||
$mergeStmt->bindParam(6, $data, \PDO::PARAM_LOB);
|
||||
$mergeStmt->bindValue(7, time() + $maxlifetime, \PDO::PARAM_INT);
|
||||
$mergeStmt->bindValue(8, time(), \PDO::PARAM_INT);
|
||||
} else {
|
||||
$mergeStmt->bindParam(':id', $sessionId, \PDO::PARAM_STR);
|
||||
$mergeStmt->bindParam(':data', $data, \PDO::PARAM_LOB);
|
||||
$mergeStmt->bindValue(':expiry', time() + $maxlifetime, \PDO::PARAM_INT);
|
||||
$mergeStmt->bindValue(':time', time(), \PDO::PARAM_INT);
|
||||
}
|
||||
|
||||
return $mergeStmt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a PDO instance.
|
||||
*
|
||||
* @return \PDO
|
||||
*/
|
||||
protected function getConnection()
|
||||
protected function getConnection(): \PDO
|
||||
{
|
||||
if (null === $this->pdo) {
|
||||
$this->connect($this->dsn ?: ini_get('session.save_path'));
|
||||
if (!isset($this->pdo)) {
|
||||
$this->connect($this->dsn ?: \ini_get('session.save_path'));
|
||||
}
|
||||
|
||||
return $this->pdo;
|
||||
|
||||
114
vendor/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php
vendored
Normal file
114
vendor/symfony/http-foundation/Session/Storage/Handler/RedisSessionHandler.php
vendored
Normal file
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
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
|
||||
* provided by the PHP redis extension.
|
||||
*
|
||||
* @author Dalibor Karlović <dalibor@flexolabs.io>
|
||||
*/
|
||||
class RedisSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
private $redis;
|
||||
|
||||
/**
|
||||
* Key prefix for shared environments.
|
||||
*/
|
||||
private string $prefix;
|
||||
|
||||
/**
|
||||
* Time to live in seconds.
|
||||
*/
|
||||
private ?int $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.
|
||||
*
|
||||
* @throws \InvalidArgumentException When unsupported client or options are passed
|
||||
*/
|
||||
public function __construct(\Redis|\RedisArray|\RedisCluster|\Predis\ClientInterface|RedisProxy|RedisClusterProxy $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);
|
||||
|
||||
return $result && !$result instanceof ErrorInterface;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
static $unlink = true;
|
||||
|
||||
if ($unlink) {
|
||||
try {
|
||||
$unlink = false !== $this->redis->unlink($this->prefix.$sessionId);
|
||||
} catch (\Throwable $e) {
|
||||
$unlink = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$unlink) {
|
||||
$this->redis->del($this->prefix.$sessionId);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
#[\ReturnTypeWillChange]
|
||||
public function close(): bool
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->redis->expire($this->prefix.$sessionId, (int) ($this->ttl ?? \ini_get('session.gc_maxlifetime')));
|
||||
}
|
||||
}
|
||||
84
vendor/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php
vendored
Normal file
84
vendor/symfony/http-foundation/Session/Storage/Handler/SessionHandlerFactory.php
vendored
Normal file
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
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
|
||||
{
|
||||
public static function createHandler(object|string $connection): AbstractSessionHandler
|
||||
{
|
||||
if ($options = \is_string($connection) ? parse_url($connection) : false) {
|
||||
parse_str($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:
|
||||
return new MemcachedSessionHandler($connection);
|
||||
|
||||
case $connection instanceof \PDO:
|
||||
return new PdoSessionHandler($connection);
|
||||
|
||||
case !\is_string($connection):
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported Connection: "%s".', get_debug_type($connection)));
|
||||
case str_starts_with($connection, 'file://'):
|
||||
$savePath = substr($connection, 7);
|
||||
|
||||
return new StrictSessionHandler(new NativeFileSessionHandler('' === $savePath ? null : $savePath));
|
||||
|
||||
case str_starts_with($connection, 'redis:'):
|
||||
case str_starts_with($connection, 'rediss:'):
|
||||
case str_starts_with($connection, 'memcached:'):
|
||||
if (!class_exists(AbstractAdapter::class)) {
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported DSN "%s". Try running "composer require symfony/cache".', $connection));
|
||||
}
|
||||
$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]));
|
||||
|
||||
case str_starts_with($connection, 'pdo_oci://'):
|
||||
if (!class_exists(DriverManager::class)) {
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported DSN "%s". Try running "composer require doctrine/dbal".', $connection));
|
||||
}
|
||||
$connection = DriverManager::getConnection(['url' => $connection])->getWrappedConnection();
|
||||
// no break;
|
||||
|
||||
case str_starts_with($connection, 'mssql://'):
|
||||
case str_starts_with($connection, 'mysql://'):
|
||||
case str_starts_with($connection, 'mysql2://'):
|
||||
case str_starts_with($connection, 'pgsql://'):
|
||||
case str_starts_with($connection, 'postgres://'):
|
||||
case str_starts_with($connection, 'postgresql://'):
|
||||
case str_starts_with($connection, 'sqlsrv://'):
|
||||
case str_starts_with($connection, 'sqlite://'):
|
||||
case str_starts_with($connection, 'sqlite3://'):
|
||||
return new PdoSessionHandler($connection, $options ?: []);
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException(sprintf('Unsupported Connection: "%s".', $connection));
|
||||
}
|
||||
}
|
||||
98
vendor/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php
vendored
Normal file
98
vendor/symfony/http-foundation/Session/Storage/Handler/StrictSessionHandler.php
vendored
Normal file
@@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* Adds basic `SessionUpdateTimestampHandlerInterface` behaviors to another `SessionHandlerInterface`.
|
||||
*
|
||||
* @author Nicolas Grekas <p@tchwork.com>
|
||||
*/
|
||||
class StrictSessionHandler extends AbstractSessionHandler
|
||||
{
|
||||
private \SessionHandlerInterface $handler;
|
||||
private bool $doDestroy;
|
||||
|
||||
public function __construct(\SessionHandlerInterface $handler)
|
||||
{
|
||||
if ($handler instanceof \SessionUpdateTimestampHandlerInterface) {
|
||||
throw new \LogicException(sprintf('"%s" is already an instance of "SessionUpdateTimestampHandlerInterface", you cannot wrap it with "%s".', get_debug_type($handler), self::class));
|
||||
}
|
||||
|
||||
$this->handler = $handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if this handler wraps an internal PHP session save handler using \SessionHandler.
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
public function isWrapper(): bool
|
||||
{
|
||||
return $this->handler instanceof \SessionHandler;
|
||||
}
|
||||
|
||||
public function open(string $savePath, string $sessionName): bool
|
||||
{
|
||||
parent::open($savePath, $sessionName);
|
||||
|
||||
return $this->handler->open($savePath, $sessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doRead(string $sessionId): string
|
||||
{
|
||||
return $this->handler->read($sessionId);
|
||||
}
|
||||
|
||||
public function updateTimestamp(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->write($sessionId, $data);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doWrite(string $sessionId, string $data): bool
|
||||
{
|
||||
return $this->handler->write($sessionId, $data);
|
||||
}
|
||||
|
||||
public function destroy(string $sessionId): bool
|
||||
{
|
||||
$this->doDestroy = true;
|
||||
$destroyed = parent::destroy($sessionId);
|
||||
|
||||
return $this->doDestroy ? $this->doDestroy($sessionId) : $destroyed;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
protected function doDestroy(string $sessionId): bool
|
||||
{
|
||||
$this->doDestroy = false;
|
||||
|
||||
return $this->handler->destroy($sessionId);
|
||||
}
|
||||
|
||||
public function close(): bool
|
||||
{
|
||||
return $this->handler->close();
|
||||
}
|
||||
|
||||
public function gc(int $maxlifetime): int|false
|
||||
{
|
||||
return $this->handler->gc($maxlifetime);
|
||||
}
|
||||
}
|
||||
@@ -1,91 +0,0 @@
|
||||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the Symfony package.
|
||||
*
|
||||
* (c) Fabien Potencier <fabien@symfony.com>
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Symfony\Component\HttpFoundation\Session\Storage\Handler;
|
||||
|
||||
/**
|
||||
* Wraps another SessionHandlerInterface to only write the session when it has been modified.
|
||||
*
|
||||
* @author Adrien Brault <adrien.brault@gmail.com>
|
||||
*/
|
||||
class WriteCheckSessionHandler implements \SessionHandlerInterface
|
||||
{
|
||||
/**
|
||||
* @var \SessionHandlerInterface
|
||||
*/
|
||||
private $wrappedSessionHandler;
|
||||
|
||||
/**
|
||||
* @var array sessionId => session
|
||||
*/
|
||||
private $readSessions;
|
||||
|
||||
public function __construct(\SessionHandlerInterface $wrappedSessionHandler)
|
||||
{
|
||||
$this->wrappedSessionHandler = $wrappedSessionHandler;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function close()
|
||||
{
|
||||
return $this->wrappedSessionHandler->close();
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function destroy($sessionId)
|
||||
{
|
||||
return $this->wrappedSessionHandler->destroy($sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function gc($maxlifetime)
|
||||
{
|
||||
return $this->wrappedSessionHandler->gc($maxlifetime);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function open($savePath, $sessionName)
|
||||
{
|
||||
return $this->wrappedSessionHandler->open($savePath, $sessionName);
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function read($sessionId)
|
||||
{
|
||||
$session = $this->wrappedSessionHandler->read($sessionId);
|
||||
|
||||
$this->readSessions[$sessionId] = $session;
|
||||
|
||||
return $session;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@inheritdoc}
|
||||
*/
|
||||
public function write($sessionId, $data)
|
||||
{
|
||||
if (isset($this->readSessions[$sessionId]) && $data === $this->readSessions[$sessionId]) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $this->wrappedSessionHandler->write($sessionId, $data);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user