Completed
Push — 11401-fix-dbsession-concurrenc... ( 3ed3ac )
by Alexander
41:37 queued 38:18
created

DbSession   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 192
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 8

Test Coverage

Coverage 46.03%

Importance

Changes 0
Metric Value
wmc 18
lcom 1
cbo 8
dl 0
loc 192
ccs 29
cts 63
cp 0.4603
rs 10
c 0
b 0
f 0

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B regenerateID() 0 42 5
A readSession() 0 14 4
A writeSession() 0 15 2
A destroySession() 0 8 1
A gcSession() 0 8 1
A typecastFields() 0 8 4
1
<?php
2
/**
3
 * @link http://www.yiiframework.com/
4
 * @copyright Copyright (c) 2008 Yii Software LLC
5
 * @license http://www.yiiframework.com/license/
6
 */
7
8
namespace yii\web;
9
10
use Yii;
11
use yii\base\InvalidConfigException;
12
use yii\db\Connection;
13
use yii\db\PdoValue;
14
use yii\db\Query;
15
use yii\di\Instance;
16
use yii\helpers\ArrayHelper;
17
18
/**
19
 * DbSession extends [[Session]] by using database as session data storage.
20
 *
21
 * By default, DbSession stores session data in a DB table named 'session'. This table
22
 * must be pre-created. The table name can be changed by setting [[sessionTable]].
23
 *
24
 * The following example shows how you can configure the application to use DbSession:
25
 * Add the following to your application config under `components`:
26
 *
27
 * ```php
28
 * 'session' => [
29
 *     'class' => 'yii\web\DbSession',
30
 *     // 'db' => 'mydb',
31
 *     // 'sessionTable' => 'my_session',
32
 * ]
33
 * ```
34
 *
35
 * DbSession extends [[MultiFieldSession]], thus it allows saving extra fields into the [[sessionTable]].
36
 * Refer to [[MultiFieldSession]] for more details.
37
 *
38
 * @author Qiang Xue <[email protected]>
39
 * @since 2.0
40
 */
41
class DbSession extends MultiFieldSession
42
{
43
    /**
44
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
45
     * After the DbSession object is created, if you want to change this property, you should only assign it
46
     * with a DB connection object.
47
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
48
     */
49
    public $db = 'db';
50
    /**
51
     * @var string the name of the DB table that stores the session data.
52
     * The table should be pre-created as follows:
53
     *
54
     * ```sql
55
     * CREATE TABLE session
56
     * (
57
     *     id CHAR(40) NOT NULL PRIMARY KEY,
58
     *     expire INTEGER,
59
     *     data BLOB
60
     * )
61
     * ```
62
     *
63
     * where 'BLOB' refers to the BLOB-type of your preferred DBMS. Below are the BLOB type
64
     * that can be used for some popular DBMS:
65
     *
66
     * - MySQL: LONGBLOB
67
     * - PostgreSQL: BYTEA
68
     * - MSSQL: BLOB
69
     *
70
     * When using DbSession in a production server, we recommend you create a DB index for the 'expire'
71
     * column in the session table to improve the performance.
72
     *
73
     * Note that according to the php.ini setting of `session.hash_function`, you may need to adjust
74
     * the length of the `id` column. For example, if `session.hash_function=sha256`, you should use
75
     * length 64 instead of 40.
76
     */
77
    public $sessionTable = '{{%session}}';
78
79
80
    /**
81
     * Initializes the DbSession component.
82
     * This method will initialize the [[db]] property to make sure it refers to a valid DB connection.
83
     * @throws InvalidConfigException if [[db]] is invalid.
84
     */
85 15
    public function __construct(array $config = [])
86
    {
87
        // db component should be initialized before configuring DbSession component
88
        // @see https://github.com/yiisoft/yii2/pull/15523#discussion_r166701079
89 15
        $this->db = Instance::ensure(ArrayHelper::remove($config, 'db', $this->db), Connection::className());
90 15
        parent::__construct($config);
91 15
    }
92
93
    /**
94
     * Updates the current session ID with a newly generated one .
95
     * Please refer to <http://php.net/session_regenerate_id> for more details.
96
     * @param bool $deleteOldSession Whether to delete the old associated session file or not.
97
     */
98
    public function regenerateID($deleteOldSession = false)
99
    {
100
        $oldID = session_id();
101
102
        // if no session is started, there is nothing to regenerate
103
        if (empty($oldID)) {
104
            return;
105
        }
106
107
        parent::regenerateID(false);
108
        $newID = session_id();
109
        // if session id regeneration failed, no need to create/update it.
110
        if (empty($newID)) {
111
            Yii::warning('Failed to generate new session ID', __METHOD__);
112
            return;
113
        }
114
115
        $row = $this->db->useMaster(function() use ($oldID) {
116
            return (new Query())->from($this->sessionTable)
117
               ->where(['id' => $oldID])
118
               ->createCommand($this->db)
119
               ->queryOne();
120
        });
121
122
        if ($row !== false) {
123
            if ($deleteOldSession) {
124
                $this->db->createCommand()
125
                    ->update($this->sessionTable, ['id' => $newID], ['id' => $oldID])
126
                    ->execute();
127
            } else {
128
                $row['id'] = $newID;
129
                $this->db->createCommand()
130
                    ->insert($this->sessionTable, $row)
131
                    ->execute();
132
            }
133
        } else {
134
            // shouldn't reach here normally
135
            $this->db->createCommand()
136
                ->insert($this->sessionTable, $this->composeFields($newID, ''))
137
                ->execute();
138
        }
139
    }
140
141
    /**
142
     * Session read handler.
143
     * @internal Do not call this method directly.
144
     * @param string $id session ID
145
     * @return string the session data
146
     */
147 15
    public function readSession($id)
148
    {
149 15
        $query = new Query();
150 15
        $query->from($this->sessionTable)
151 15
            ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
152
153 15
        if ($this->readCallback !== null) {
154
            $fields = $query->one($this->db);
155
            return $fields === false ? '' : $this->extractData($fields);
156
        }
157
158 15
        $data = $query->select(['data'])->scalar($this->db);
159 15
        return $data === false ? '' : $data;
160
    }
161
162
    /**
163
     * Session write handler.
164
     * @internal Do not call this method directly.
165
     * @param string $id session ID
166
     * @param string $data session data
167
     * @return bool whether session write is successful
168
     */
169 15
    public function writeSession($id, $data)
170
    {
171
        // exception must be caught in session write handler
172
        // http://us.php.net/manual/en/function.session-set-save-handler.php#refsect1-function.session-set-save-handler-notes
173
        try {
174 15
            $fields = $this->composeFields($id, $data);
175 15
            $fields = $this->typecastFields($fields);
176 15
            $this->db->createCommand()->upsert($this->sessionTable, $fields)->execute();
177
        } catch (\Exception $e) {
178
            Yii::$app->errorHandler->handleException($e);
179
            return false;
180
        }
181
182 15
        return true;
183
    }
184
185
    /**
186
     * Session destroy handler.
187
     * @internal Do not call this method directly.
188
     * @param string $id session ID
189
     * @return bool whether session is destroyed successfully
190
     */
191 3
    public function destroySession($id)
192
    {
193 3
        $this->db->createCommand()
194 3
            ->delete($this->sessionTable, ['id' => $id])
195 3
            ->execute();
196
197 3
        return true;
198
    }
199
200
    /**
201
     * Session GC (garbage collection) handler.
202
     * @internal Do not call this method directly.
203
     * @param int $maxLifetime the number of seconds after which data will be seen as 'garbage' and cleaned up.
204
     * @return bool whether session is GCed successfully
205
     */
206 6
    public function gcSession($maxLifetime)
207
    {
208 6
        $this->db->createCommand()
209 6
            ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
210 6
            ->execute();
211
212 6
        return true;
213
    }
214
215
    /**
216
     * Method typecasts $fields before passing them to PDO.
217
     * Default implementation casts field `data` to `\PDO::PARAM_LOB`.
218
     * You can override this method in case you need special type casting.
219
     *
220
     * @param array $fields Fields, that will be passed to PDO. Key - name, Value - value
221
     * @return array
222
     * @since 2.0.13
223
     */
224 15
    protected function typecastFields($fields)
225
    {
226 15
        if (isset($fields['data']) && is_array($fields['data'] && is_object($fields['data']))) {
227
            $fields['data'] = new PdoValue($fields['data'], \PDO::PARAM_LOB);
228
        }
229
230 15
        return $fields;
231
    }
232
}
233