1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Autarky\Http;
12:
13: use Symfony\Component\HttpKernel\HttpKernelInterface;
14: use Symfony\Component\HttpFoundation\Request;
15: use Symfony\Component\HttpFoundation\Response;
16: use Symfony\Component\HttpFoundation\Cookie;
17: use Symfony\Component\HttpFoundation\Session\SessionInterface;
18: use Autarky\Application;
19:
20: 21: 22:
23: class SessionMiddleware implements HttpKernelInterface
24: {
25: 26: 27:
28: protected $kernel;
29:
30: 31: 32:
33: protected $session;
34:
35: 36: 37: 38: 39: 40:
41: protected $forceStart;
42:
43: 44: 45: 46: 47:
48: protected $cookies;
49:
50: 51: 52: 53:
54: public function __construct(HttpKernelInterface $kernel, Application $app)
55: {
56: $this->kernel = $kernel;
57: $this->session = $app->getContainer()
58: ->resolve('Symfony\Component\HttpFoundation\Session\SessionInterface');
59: $this->forceStart = $app->getConfig()
60: ->get('session.force', false);
61: $this->cookies = $app->getConfig()
62: ->get('session.cookies', []);
63: }
64:
65: 66: 67:
68: public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
69: {
70:
71: $request->setSession($this->session);
72:
73:
74:
75:
76: if ($type !== HttpKernelInterface::MASTER_REQUEST) {
77: return $this->kernel->handle($request, $type, $catch);
78: }
79:
80:
81:
82:
83: if (!$this->session->isStarted()) {
84: $this->initSession($request);
85: }
86:
87: $response = $this->kernel->handle($request, $type, $catch);
88:
89:
90:
91:
92: if ($this->session->isStarted()) {
93: $this->closeSession($request, $response);
94: }
95:
96: return $response;
97: }
98:
99: protected function initSession(Request $request)
100: {
101:
102: $sessionName = $this->session->getName();
103:
104:
105: if ($request->cookies->has($sessionName)) {
106: $this->session->setId($request->cookies->get($sessionName));
107: }
108:
109:
110:
111: if ($this->forceStart) {
112: $this->session->start();
113: }
114: }
115:
116: protected function closeSession(Request $request, Response $response)
117: {
118:
119: $this->session->save();
120:
121:
122: $response->headers->setCookie($this->makeCookie($request));
123: }
124:
125: protected function makeCookie(Request $request)
126: {
127:
128: $params = array_replace(session_get_cookie_params(), $this->cookies);
129:
130:
131:
132:
133: if ($params['lifetime'] !== 0) {
134: $params['lifetime'] = $request->server->get('REQUEST_TIME') + $params['lifetime'];
135: }
136:
137: return new Cookie(
138: $this->session->getName(),
139: $this->session->getId(),
140: $params['lifetime'],
141: $params['path'],
142: $params['domain'],
143: $params['secure'],
144: $params['httponly']
145: );
146: }
147: }
148: