Completed
Push — master ( 745775...2faf77 )
by Alexander
48:08 queued 38:58
created

DbSession::typecastFields()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 8
ccs 0
cts 0
cp 0
rs 9.4285
cc 3
eloc 4
nc 2
nop 1
crap 12
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 3
    public function init()
84
    {
85 3
        parent::init();
86 3
        $this->db = Instance::ensure($this->db, Connection::className());
87 3
    }
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 2
    public function readSession($id)
142
    {
143 2
        $query = new Query();
144 2
        $query->from($this->sessionTable)
145 2
            ->where('[[expire]]>:expire AND [[id]]=:id', [':expire' => time(), ':id' => $id]);
146
147 2
        if ($this->readCallback !== null) {
148
            $fields = $query->one($this->db);
149
            return $fields === false ? '' : $this->extractData($fields);
150
        }
151
152 2
        $data = $query->select(['data'])->scalar($this->db);
153 2
        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 3
    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 3
            $query = new Query();
169 3
            $exists = $query->select(['id'])
170 3
                ->from($this->sessionTable)
171 3
                ->where(['id' => $id])
172 3
                ->createCommand($this->db)
173 3
                ->queryScalar();
174 3
            $fields = $this->composeFields($id, $data);
175 3
            $fields = $this->typecastFields($fields);
176 3
            if ($exists === false) {
177 3
                $this->db->createCommand()
178 3
                    ->insert($this->sessionTable, $fields)
179
                    ->execute();
180
            } else {
181
                unset($fields['id']);
182
                $this->db->createCommand()
183 3
                    ->update($this->sessionTable, $fields, ['id' => $id])
184
                    ->execute();
185
            }
186
        } catch (\Exception $e) {
187
            Yii::$app->errorHandler->handleException($e);
188
            return false;
189
        }
190 3
191
        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 1
     */
200
    public function destroySession($id)
201 1
    {
202 1
        $this->db->createCommand()
203 1
            ->delete($this->sessionTable, ['id' => $id])
204
            ->execute();
205 1
206
        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 1
     */
215
    public function gcSession($maxLifetime)
216 1
    {
217 1
        $this->db->createCommand()
218 1
            ->delete($this->sessionTable, '[[expire]]<:expire', [':expire' => time()])
219
            ->execute();
220 1
221
        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
    protected function typecastFields($fields)
234
    {
235
        if (isset($fields['data']) && !is_array($fields['data'])) {
236
            $fields['data'] = [$fields['data'], \PDO::PARAM_LOB];
237
        }
238
239
        return $fields;
240
    }
241
}
242