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\Response; |
19
|
|
|
use think\Session; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Session初始化 |
23
|
|
|
*/ |
24
|
|
|
class SessionInit |
25
|
|
|
{ |
26
|
|
|
|
27
|
|
|
/** @var App */ |
|
|
|
|
28
|
|
|
protected $app; |
29
|
|
|
|
30
|
|
|
/** @var Session */ |
|
|
|
|
31
|
|
|
protected $session; |
32
|
|
|
|
33
|
|
|
public function __construct(App $app, Session $session) |
|
|
|
|
34
|
|
|
{ |
35
|
|
|
$this->app = $app; |
36
|
|
|
$this->session = $session; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Session初始化 |
41
|
|
|
* @access public |
42
|
|
|
* @param Request $request |
|
|
|
|
43
|
|
|
* @param Closure $next |
|
|
|
|
44
|
|
|
* @return Response |
45
|
|
|
*/ |
46
|
|
|
public function handle($request, Closure $next) |
47
|
|
|
{ |
48
|
|
|
// Session初始化 |
49
|
|
|
$varSessionId = $this->app->config->get('session.var_session_id'); |
50
|
|
|
$cookieName = $this->session->getName(); |
|
|
|
|
51
|
|
|
|
52
|
|
|
if ($varSessionId && $request->request($varSessionId)) { |
53
|
|
|
$sessionId = $request->request($varSessionId); |
54
|
|
|
} else { |
55
|
|
|
$sessionId = $request->cookie($cookieName); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$this->session->setId($sessionId); |
|
|
|
|
59
|
|
|
$this->session->init(); |
|
|
|
|
60
|
|
|
|
61
|
|
|
$request->withSession($this->session); |
62
|
|
|
|
63
|
|
|
/** @var Response $response */ |
|
|
|
|
64
|
|
|
$response = $next($request); |
65
|
|
|
|
66
|
|
|
$response->setSession($this->session); |
67
|
|
|
|
68
|
|
|
$this->app->cookie->set($cookieName, $this->session->getId()); |
|
|
|
|
69
|
|
|
|
70
|
|
|
return $response; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
public function end(Response $response) |
|
|
|
|
74
|
|
|
{ |
75
|
|
|
$this->session->save(); |
|
|
|
|
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|