Completed
Branch 2.x (1ad542)
by Julián
02:11
created

SessionHandling::__invoke()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 3
1
<?php
2
3
/*
4
 * sessionware (https://github.com/juliangut/sessionware).
5
 * PSR7 compatible session management.
6
 *
7
 * @license BSD-3-Clause
8
 * @link https://github.com/juliangut/sessionware
9
 * @author Julián Gutiérrez <[email protected]>
10
 */
11
12
declare(strict_types=1);
13
14
namespace Jgut\Sessionware\Middleware;
15
16
use Jgut\Sessionware\Session;
17
use Psr\Http\Message\ResponseInterface;
18
use Psr\Http\Message\ServerRequestInterface;
19
20
/**
21
 * Session handling middleware.
22
 */
23
class SessionHandling
24
{
25
    const SESSION_KEY = '__SESSIONWARE_SESSION__';
26
27
    /**
28
     * @var Session
29
     */
30
    protected $session;
31
32
    /**
33
     * Middleware constructor.
34
     *
35
     * @param Session $session
36
     */
37
    public function __construct(Session $session)
38
    {
39
        $this->session = $session;
40
    }
41
42
    /**
43
     * Get session from request.
44
     *
45
     * @param ServerRequestInterface $request
46
     *
47
     * @return Session|null
48
     */
49
    public static function getSession(ServerRequestInterface $request)
50
    {
51
        return $request->getAttribute(static::SESSION_KEY);
52
    }
53
54
    /**
55
     * Execute middleware.
56
     *
57
     * @param ServerRequestInterface $request
58
     * @param ResponseInterface      $response
59
     * @param callable               $next
60
     *
61
     * @throws \RuntimeException
62
     *
63
     * @return ResponseInterface
64
     */
65
    public function __invoke(
66
        ServerRequestInterface $request,
67
        ResponseInterface $response,
68
        callable $next
69
    ) : ResponseInterface {
70
        $this->session->loadIdFromRequest($request);
71
72
        /* @var ResponseInterface $response */
73
        $response = $next($request->withAttribute(static::SESSION_KEY, $this->session), $response);
74
75
        $this->session->close();
76
77
        $response = $this->session->withSessionCookie($response);
78
79
        return $response;
80
    }
81
}
82