1
|
|
|
<?php |
2
|
|
|
namespace Wandu\Router\Middleware; |
3
|
|
|
|
4
|
|
|
use Closure; |
5
|
|
|
use Psr\Http\Message\ServerRequestInterface; |
6
|
|
|
use SessionHandlerInterface; |
7
|
|
|
use Wandu\Http\Contracts\CookieJarInterface; |
8
|
|
|
use Wandu\Http\Contracts\SessionInterface; |
9
|
|
|
use Wandu\Http\Exception\HttpException; |
10
|
|
|
use Wandu\Http\Parameters\CookieJar; |
11
|
|
|
use Wandu\Http\Parameters\Session; |
12
|
|
|
use Wandu\Http\Session\Configuration; |
13
|
|
|
use Wandu\Router\Contracts\MiddlewareInterface; |
14
|
|
|
|
15
|
|
|
class Sessionify implements MiddlewareInterface |
16
|
|
|
{ |
17
|
|
|
/** @var \SessionHandlerInterface */ |
18
|
|
|
protected $handler; |
19
|
|
|
|
20
|
|
|
/** @var \Wandu\Http\Session\Configuration */ |
21
|
|
|
protected $config; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param \SessionHandlerInterface $handler |
25
|
|
|
* @param \Wandu\Http\Session\Configuration $config |
26
|
|
|
*/ |
27
|
1 |
|
public function __construct(SessionHandlerInterface $handler, Configuration $config = null) |
28
|
|
|
{ |
29
|
1 |
|
$this->handler = $handler; |
30
|
1 |
|
$this->config = $config; |
31
|
1 |
|
} |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* {@inheritdoc} |
35
|
|
|
*/ |
36
|
1 |
|
public function __invoke(ServerRequestInterface $request, Closure $next) |
37
|
|
|
{ |
38
|
1 |
|
$cookieJar = new CookieJar($request); |
39
|
1 |
|
$session = new Session($cookieJar, $this->handler, $this->config); |
40
|
|
|
|
41
|
|
|
$request = $request |
42
|
1 |
|
->withAttribute('cookie', $cookieJar) |
43
|
1 |
|
->withAttribute(CookieJar::class, $cookieJar) |
44
|
1 |
|
->withAttribute(CookieJarInterface::class, $cookieJar) |
45
|
1 |
|
->withAttribute('session', $session) |
46
|
1 |
|
->withAttribute(Session::class, $session) |
47
|
1 |
|
->withAttribute(SessionInterface::class, $session); |
48
|
|
|
|
49
|
|
|
// run next |
50
|
|
|
try { |
51
|
1 |
|
$response = $next($request); |
52
|
|
|
} catch (HttpException $exception) { |
53
|
|
|
$response = $exception->getResponse(); |
54
|
|
|
|
55
|
|
|
$session->applyToCookieJar($cookieJar); |
56
|
|
|
$exception->setResponse($cookieJar->applyToResponse($response)); |
57
|
|
|
throw $exception; |
58
|
|
|
} |
59
|
|
|
|
60
|
1 |
|
$session->applyToCookieJar($cookieJar); |
61
|
1 |
|
return $cookieJar->applyToResponse($response); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|