summaryrefslogtreecommitdiff
path: root/src/Middleware/SessionHandler.php
blob: 8c53b0fdcc41b7aa4e7b376a7032a4524531fb93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php

namespace Engelsystem\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\SessionStorageInterface;

class SessionHandler implements MiddlewareInterface
{
    /** @var SessionStorageInterface */
    protected $session;

    /** @var string[] */
    protected $paths = [];

    /**
     * @param SessionStorageInterface $session
     * @param array                   $paths
     */
    public function __construct(SessionStorageInterface $session, array $paths = [])
    {
        $this->paths = $paths;
        $this->session = $session;
    }

    /**
     * @param ServerRequestInterface  $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $return = $handler->handle($request);

        $cookies = $request->getCookieParams();
        if (
            $this->session instanceof NativeSessionStorage
            && in_array($request->getAttribute('route-request-path'), $this->paths)
            && !isset($cookies[$this->session->getName()])
        ) {
            $this->destroyNative();
        }

        return $return;
    }

    /**
     * @return bool
     * @codeCoverageIgnore
     */
    protected function destroyNative()
    {
        return session_destroy();
    }
}