Completed
Push — master ( 2faf77...993eb5 )
by Dmitry
11:18
created

DbSession   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 203
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 6

Test Coverage

Coverage 53.33%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 18
lcom 1
cbo 6
dl 0
loc 203
ccs 40
cts 75
cp 0.5333
rs 10
c 1
b 0
f 0

7 Methods

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