1
|
|
|
<?php |
2
|
|
|
// +---------------------------------------------------------------------- |
|
|
|
|
3
|
|
|
// | ThinkPHP [ WE CAN DO IT JUST THINK ] |
4
|
|
|
// +---------------------------------------------------------------------- |
5
|
|
|
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved. |
6
|
|
|
// +---------------------------------------------------------------------- |
7
|
|
|
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) |
8
|
|
|
// +---------------------------------------------------------------------- |
9
|
|
|
// | Author: liu21st <[email protected]> |
10
|
|
|
// +---------------------------------------------------------------------- |
11
|
|
|
declare (strict_types = 1); |
12
|
|
|
|
13
|
|
|
namespace think\middleware; |
14
|
|
|
|
15
|
|
|
use Closure; |
16
|
|
|
use think\App; |
17
|
|
|
use think\Request; |
18
|
|
|
use think\Session; |
19
|
|
|
|
20
|
|
|
class SessionInit |
|
|
|
|
21
|
|
|
{ |
22
|
|
|
|
23
|
|
|
/** @var Session */ |
|
|
|
|
24
|
|
|
protected $session; |
25
|
|
|
|
26
|
|
|
/** @var App */ |
|
|
|
|
27
|
|
|
protected $app; |
28
|
|
|
|
29
|
|
|
public function __construct(App $app, Session $session) |
|
|
|
|
30
|
|
|
{ |
31
|
|
|
$this->app = $app; |
32
|
|
|
$this->session = $session; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Session初始化 |
37
|
|
|
* @access public |
38
|
|
|
* @param Request $request |
|
|
|
|
39
|
|
|
* @param Closure $next |
|
|
|
|
40
|
|
|
* @return void |
41
|
|
|
*/ |
42
|
|
|
public function handle($request, Closure $next) |
43
|
|
|
{ |
44
|
|
|
// Session初始化 |
45
|
|
|
$varSessionId = $this->app->config->get('route.var_session_id'); |
46
|
|
|
|
47
|
|
|
if ($varSessionId && $request->request($varSessionId)) { |
48
|
|
|
$this->session->setId($request->request($varSessionId)); |
|
|
|
|
49
|
|
|
} else { |
50
|
|
|
$cookieName = $this->app->config->get('session.cookie_name', 'PHPSESSID'); |
51
|
|
|
$sessionId = $request->cookie($cookieName) ?: ''; |
|
|
|
|
52
|
|
|
$this->session->setId($sessionId); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$request->withSession($this->session); |
56
|
|
|
|
57
|
|
|
$response = $next($request); |
58
|
|
|
|
59
|
|
|
if (isset($cookieName)) { |
60
|
|
|
$this->app->cookie->set($cookieName, $this->session->getId()); |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
return $response; |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|