|
- <?php
-
-
- namespace yii\web;
-
- use Yii;
- use yii\db\Connection;
- use yii\db\Query;
- use yii\base\InvalidConfigException;
- use yii\di\Instance;
-
-
- class DbSession extends MultiFieldSession
- {
-
-
- public $db = 'db';
-
-
- public $sessionTable = '{{%session}}';
-
-
-
-
- public function init()
- {
- parent::init();
- $this->db = Instance::ensure($this->db, Connection::className());
- }
-
-
-
- public function regenerateID($deleteOldSession = false)
- {
- $oldID = session_id();
-
-
- if (empty($oldID)) {
- return;
- }
-
- parent::regenerateID(false);
- $newID = session_id();
-
- $query = new Query();
- $row = $query->from($this->sessionTable)
- ->where(['id' => $oldID])
- ->createCommand($this->db)
- ->queryOne();
- if ($row !== false) {
- if ($deleteOldSession) {
- $this->db->createCommand()
- ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
- ->execute();
- } else {
- $row['id'] = $newID;
- $this->db->createCommand()
- ->insert($this->sessionTable, $row)
- ->execute();
- }
- } else {
-
- $this->db->createCommand()
- ->insert($this->sessionTable, $this->composeFields($newID, ''))
- ->execute();
- }
- }
-
-
-
- public function readSession($id)
- {
- $query = new Query();
- $query->from($this->sessionTable)
- ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
-
- if ($this->readCallback !== null) {
- $fields = $query->one($this->db);
- return $fields === false ? '' : $this->extractData($fields);
- }
-
- $data = $query->select(['data'])->scalar($this->db);
- return $data === false ? '' : $data;
- }
-
-
-
- public function writeSession($id, $data)
- {
-
-
- try {
- $query = new Query;
- $exists = $query->select(['id'])
- ->from($this->sessionTable)
- ->where(['id' => $id])
- ->createCommand($this->db)
- ->queryScalar();
- $fields = $this->composeFields($id, $data);
- if ($exists === false) {
- $this->db->createCommand()
- ->insert($this->sessionTable, $fields)
- ->execute();
- } else {
- unset($fields['id']);
- $this->db->createCommand()
- ->update($this->sessionTable, $fields, ['id' => $id])
- ->execute();
- }
- } catch (\Exception $e) {
- $exception = ErrorHandler::convertExceptionToString($e);
-
- error_log($exception);
- if (YII_DEBUG) {
- echo $exception;
- }
- return false;
- }
-
- return true;
- }
-
-
-
- public function destroySession($id)
- {
- $this->db->createCommand()
- ->delete($this->sessionTable, ['id' => $id])
- ->execute();
-
- return true;
- }
-
-
-
- public function gcSession($maxLifetime)
- {
- $this->db->createCommand()
- ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
- ->execute();
-
- return true;
- }
- }
|