Completed
Push — feature/0.7.0 ( 79c386...7f3169 )
by Ryuichi
03:02
created

Session   A

Complexity

Total Complexity 26

Size/Duplication

Total Lines 214
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 26
c 3
b 0
f 0
lcom 1
cbo 2
dl 0
loc 214
rs 10

14 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __destruct() 0 4 1
B initialize() 0 30 6
B start() 0 26 4
A restart() 0 11 2
A createInitializeCookie() 0 5 1
A isSessionTimeout() 0 5 2
A isInitialStart() 0 4 1
A destroy() 0 10 1
A id() 0 4 1
A set() 0 4 1
A delete() 0 4 1
A get() 0 6 3
A timeout() 0 4 1
1
<?php
2
namespace WebStream\Http;
3
4
use WebStream\DI\Injector;
5
use WebStream\Exception\Extend\SessionTimeoutException;
6
7
/**
8
 * セッションクラス
9
 * @author Ryuichi TANAKA.
10
 * @since 2010/08/24
11
 * @version 0.7
12
 */
13
class Session
14
{
15
    use Injector;
16
17
    /** セッション名 */
18
    const SESSION_NAME = 'WSSESS';
19
    /** 初回起動チェッククッキー名 */
20
    const INITIAL_STARTED_COOKIE_NAME = 'WSSESS_STARTED';
21
    /** セッション有効期限を保存するクッキー名 */
22
    const SESSION_EXPIRE_COOKIE_NAME = 'WSSESS_LIFE';
23
24
    /**
25
     * コンストラクタ
26
     * @param int セッションの有効期限(秒)
27
     * @param string Cookieを有効にするパス
28
     * @param string Cookieを有効にするドメイン
29
     * @param boolean Secure属性を有効にする
30
     * @param boolean HttpOnly属性を有効にする
31
     */
32
    public function __construct($expire = null, $path = '/', $domain = "", $secure = false, $httpOnly = false)
33
    {
34
        $this->initialize($expire, $path, $domain, $secure, $httpOnly);
35
    }
36
37
    /**
38
     * デストラクタ
39
     */
40
    public function __destruct()
41
    {
42
        $this->logger->debug("Session is clear.");
0 ignored issues
show
Documentation introduced by
The property logger does not exist on object<WebStream\Http\Session>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
43
    }
44
45
    /**
46
     * 初期設定
47
     * @param integer セッションの有効期限(秒)
48
     * @param string Cookieを有効にするパス
49
     * @param string Cookieを有効にするドメイン
50
     * @param boolean Secure属性を有効にする
51
     * @param boolean HttpOnly属性を有効にする
52
     */
53
    private function initialize($expire, $path, $domain, $secure, $httpOnly)
54
    {
55
        // 有効期限が設定されている場合のみ、Cookieに値をセットする
56
        if ($expire !== null) {
57
            session_set_cookie_params($expire, $path, $domain, $secure, $httpOnly);
58
        }
59
60
        // セッションIDの予測リスクを低減する
61
        // /dev/urandomまたは/dev/randomがある場合、
62
        // session.entropy_fileに設定し、session.entropy_lengthを32に設定する
63
        if (PHP_OS !== "WIN32" && PHP_OS !== "WINNT") {
64
            if (file_exists('/dev/urandom')) {
65
                ini_set('session.entropy_file', '/dev/urandom');
66
                ini_set('session.entropy_length', '32');
67
            } elseif (file_exists('/dev/random')) {
68
                ini_set('session.entropy_file', '/dev/random');
69
                ini_set('session.entropy_length', '32');
70
            }
71
            ini_set('session.save_path', '/tmp');
72
        } else {
73
            ini_set('session.save_path', 'C:\\tmp');
74
        }
75
76
        ini_set('session.hash_function', 'sha256');
77
78
        // RefererによるセッションID漏洩を防止する
79
        // セッションIDはCookieにのみ保存する
80
        ini_set('session.use_cookies', '1');
81
        ini_set('session.use_only_cookies', '1');
82
    }
83
84
    /**
85
     * セッションを開始する
86
     */
87
    public function start()
88
    {
89
        if (headers_sent()) {
90
            return;
91
        }
92
93
        // セッション名を設定
94
        session_name(self::SESSION_NAME);
95
        // セッションを開始
96
        session_start();
97
98
        // セッション固定化を防止
99
        // 注意:これをやるとセッション破棄される問題があるため外す。
100
        //session_regenerate_id(true);
101
102
        // 初回起動処理
103
        if ($this->isInitialStart()) {
104
            $this->createInitializeCookie();
105
        }
106
107
        // セッションタイムアウトかどうか。初回起動の場合は除く。
108
        if ($this->isSessionTimeout()) {
109
            $this->destroy();
110
            throw new SessionTimeoutException("Session timeout");
111
        }
112
    }
113
114
    /**
115
     * セッションを再始動する
116
     * @param integer セッションの有効期限(秒)
117
     * @param string Cookieを有効にするパス
118
     * @param string Cookieを有効にするドメイン
119
     * @param boolean Secure属性を有効にする
120
     * @param boolean HttpOnly属性を有効にする
121
     */
122
    public function restart($expire = null, $path = '/', $domain = '', $secure = false, $httpOnly = false)
123
    {
124
        if ($expire === null) {
125
            // 初期化する
126
            $this->createInitializeCookie();
127
        } else {
128
            // 再設定する
129
            setcookie(self::SESSION_EXPIRE_COOKIE_NAME, time(), time() + $expire, $path, $domain, $secure, $httpOnly);
130
            $_SESSION[self::SESSION_EXPIRE_COOKIE_NAME] = time() + $expire;
131
        }
132
    }
133
134
    /**
135
     * 初回起動時に生成するCookieを設定する
136
     */
137
    private function createInitializeCookie()
138
    {
139
        $_SESSION = [];
140
        setcookie(self::INITIAL_STARTED_COOKIE_NAME, time(), null, '/', null);
141
    }
142
143
    /**
144
     * セッションタイムアウト状態かどうか
145
     * WSSESS_LIFEクッキーが送られてこない場合、セッションタイムアウトとする
146
     * @return boolean セッションタイムアウトかどうか
147
     */
148
    private function isSessionTimeout()
149
    {
150
        return isset($_SESSION[self::SESSION_EXPIRE_COOKIE_NAME]) &&
151
               !isset($_COOKIE[self::SESSION_EXPIRE_COOKIE_NAME]);
152
    }
153
154
    /**
155
     * 初回起動時かどうか
156
     * WSSESS_STARTEDクッキーが削除されていた場合は強制的に初期化扱いする
157
     * @return boolean 初回起動時かどうか
158
     */
159
    private function isInitialStart()
160
    {
161
        return !isset($_COOKIE[self::INITIAL_STARTED_COOKIE_NAME]);
162
    }
163
164
    /**
165
     * セッションおよびCookieを破棄する
166
     */
167
    public function destroy()
168
    {
169
        // セッション変数を全て初期化
170
        $_SESSION = [];
171
        // Cookieを削除
172
        setcookie(session_name(), '', time() - 3600, '/');
173
        setcookie(self::INITIAL_STARTED_COOKIE_NAME, '', time() - 3600, '/');
174
        // セッションファイルを破棄
175
        session_destroy();
176
    }
177
178
    /**
179
     * セッションIDを返却する
180
     * @return string セッションID
181
     */
182
    public function id()
183
    {
184
        return session_id();
185
    }
186
187
    /**
188
     * セッションをセットする
189
     * @param string セッションキー
190
     * @param string セッション値
191
     */
192
    public function set($name, $value)
193
    {
194
        $_SESSION[$name] = $value;
195
    }
196
197
    /**
198
     * セッションを破棄する
199
     * @param string セッションキー
200
     */
201
    public function delete($key)
202
    {
203
        unset($_SESSION[$key]);
204
    }
205
206
    /**
207
     * セッションを取得する
208
     * @param string セッションキー
209
     * @return string セッション値
210
     */
211
    public function get($name)
212
    {
213
        if (isset($_SESSION) && array_key_exists($name, $_SESSION)) {
214
            return $_SESSION[$name];
215
        }
216
    }
217
218
    /**
219
     * セッションタイムアウトしたか返却する
220
     * @return boolean セッションタイムアウトしたかどうか
221
     */
222
    public function timeout()
223
    {
224
        return $this->isSessionTimeout();
225
    }
226
}
227