Completed
Branch 2.x (133470)
by Julián
06:39
created

SessionHandling::withSessionCookie()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 5
nc 2
nop 1
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
        return $this->withSessionCookie($response);
78
    }
79
80
    /**
81
     * Return response with added session cookie.
82
     *
83
     * @param ResponseInterface $response
84
     *
85
     * @return ResponseInterface
86
     */
87
    protected function withSessionCookie(ResponseInterface $response) : ResponseInterface
88
    {
89
        $cookieString = $this->session->getSessionCookieString();
90
91
        if (!empty($cookieString)) {
92
            $response = $response->withAddedHeader('Set-Cookie', $cookieString);
93
        }
94
95
        return $response;
96
    }
97
}
98