SessionCookieMiddleware   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 25
dl 0
loc 50
ccs 0
cts 29
cp 0
rs 10
c 1
b 0
f 0
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A process() 0 34 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace TMV\OpenIdClient\Middleware;
6
7
use function class_exists;
8
use Dflydev\FigCookies\Cookies;
9
use Dflydev\FigCookies\FigResponseCookies;
10
use Dflydev\FigCookies\Modifier\SameSite;
11
use Dflydev\FigCookies\SetCookie;
12
use function is_array;
13
use function json_decode;
14
use function json_encode;
15
use Psr\Http\Message\ResponseInterface;
16
use Psr\Http\Message\ServerRequestInterface;
17
use Psr\Http\Server\MiddlewareInterface;
18
use Psr\Http\Server\RequestHandlerInterface;
19
use TMV\OpenIdClient\Exception\LogicException;
20
use TMV\OpenIdClient\Session\AuthSession;
21
use TMV\OpenIdClient\Session\AuthSessionInterface;
22
23
class SessionCookieMiddleware implements MiddlewareInterface
24
{
25
    public const SESSION_ATTRIBUTE = AuthSessionInterface::class;
26
27
    /** @var string */
28
    private $cookieName;
29
30
    /** @var null|int */
31
    private $cookieMaxAge;
32
33
    public function __construct(string $cookieName = 'openid', ?int $cookieMaxAge = null)
34
    {
35
        $this->cookieName = $cookieName;
36
        $this->cookieMaxAge = $cookieMaxAge;
37
    }
38
39
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
40
    {
41
        if (! class_exists(Cookies::class)) {
42
            throw new LogicException('To use the SessionCookieMiddleware you should install dflydev/fig-cookies package');
43
        }
44
45
        $cookies = Cookies::fromRequest($request);
46
        $sessionCookie = $cookies->get($this->cookieName);
47
48
        $cookieValue = null !== $sessionCookie ? $sessionCookie->getValue() : null;
49
        $data = null !== $cookieValue ? json_decode($cookieValue, true) : [];
50
51
        if (! is_array($data)) {
52
            $data = [];
53
        }
54
55
        $authSession = AuthSession::fromArray($data);
56
57
        $response = $handler->handle($request->withAttribute(self::SESSION_ATTRIBUTE, $authSession));
58
59
        /** @var string $cookieValue */
60
        $cookieValue = json_encode($authSession->jsonSerialize());
61
62
        $sessionCookie = SetCookie::create($this->cookieName)
63
            ->withValue($cookieValue)
64
            ->withMaxAge($this->cookieMaxAge)
65
            ->withHttpOnly()
66
            ->withSecure()
67
            ->withPath('/')
68
            ->withSameSite(SameSite::strict());
69
70
        $response = FigResponseCookies::set($response, $sessionCookie);
71
72
        return $response;
73
    }
74
}
75