105 lines
2.3 KiB
PHP
105 lines
2.3 KiB
PHP
|
<?php namespace SokoWeb\Session;
|
||
|
|
||
|
use DateTime;
|
||
|
use SokoWeb\Database\Query\Modify;
|
||
|
use SokoWeb\Database\Query\Select;
|
||
|
use SokoWeb\Interfaces\Database\IResultSet;
|
||
|
use SokoWeb\Interfaces\Session\ISessionHandler;
|
||
|
|
||
|
class DatabaseSessionHandler implements ISessionHandler
|
||
|
{
|
||
|
private bool $exists = false;
|
||
|
|
||
|
private bool $written = false;
|
||
|
|
||
|
public function open($savePath, $sessionName): bool
|
||
|
{
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
public function close(): bool
|
||
|
{
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
public function read($id): string
|
||
|
{
|
||
|
$select = new Select(\Container::$dbConnection, 'sessions');
|
||
|
$select->columns(['data']);
|
||
|
$select->whereId(substr($id, 0, 32));
|
||
|
|
||
|
$result = $select->execute()->fetch(IResultSet::FETCH_ASSOC);
|
||
|
|
||
|
if ($result === null) {
|
||
|
return '';
|
||
|
}
|
||
|
|
||
|
$this->exists = true;
|
||
|
|
||
|
return $result['data'];
|
||
|
}
|
||
|
|
||
|
public function write($id, $data): bool
|
||
|
{
|
||
|
$modify = new Modify(\Container::$dbConnection, 'sessions');
|
||
|
|
||
|
if ($this->exists) {
|
||
|
$modify->setId(substr($id, 0, 32));
|
||
|
} else {
|
||
|
$modify->setExternalId(substr($id, 0, 32));
|
||
|
}
|
||
|
|
||
|
$modify->set('data', $data);
|
||
|
$modify->set('updated', (new DateTime())->format('Y-m-d H:i:s'));
|
||
|
$modify->save();
|
||
|
|
||
|
$this->written = true;
|
||
|
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
public function destroy($id): bool
|
||
|
{
|
||
|
$modify = new Modify(\Container::$dbConnection, 'sessions');
|
||
|
$modify->setId(substr($id, 0, 32));
|
||
|
$modify->delete();
|
||
|
|
||
|
$this->exists = false;
|
||
|
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
public function gc($maxlifetime): bool
|
||
|
{
|
||
|
// empty on purpose
|
||
|
// old sessions are deleted by MaintainDatabaseCommand
|
||
|
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
public function create_sid(): string
|
||
|
{
|
||
|
return bin2hex(random_bytes(16));
|
||
|
}
|
||
|
|
||
|
public function validateId($id): bool
|
||
|
{
|
||
|
return preg_match('/^[a-f0-9]{32}$/', $id) === 1;
|
||
|
}
|
||
|
|
||
|
public function updateTimestamp($id, $data): bool
|
||
|
{
|
||
|
if ($this->written) {
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
$modify = new Modify(\Container::$dbConnection, 'sessions');
|
||
|
|
||
|
$modify->setId(substr($id, 0, 32));
|
||
|
$modify->set('updated', (new DateTime())->format('Y-m-d H:i:s'));
|
||
|
$modify->save();
|
||
|
|
||
|
return true;
|
||
|
}
|
||
|
}
|