Completed
Push — master ( 54ccda...232c7c )
by Changwan
04:16
created

Sessionify::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
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