Failed Conditions
Push — master ( b1d4df...5a9cf3 )
by David
04:05
created

RefreshSessionTimestampMiddleware   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 13
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 2
eloc 5
c 1
b 0
f 0
dl 0
loc 13
ccs 5
cts 5
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
A process() 0 11 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Middleware;
6
7
use Mezzio\Session\SessionMiddleware;
8
use Psr\Http\Message\ResponseInterface;
9
use Psr\Http\Message\ServerRequestInterface;
10
use Psr\Http\Server\MiddlewareInterface;
11
use Psr\Http\Server\RequestHandlerInterface;
12
13
/**
14
 * Middleware that writes to the session if a user is connected,
15
 * in order to refresh the mtime of the session file.
16
 *
17
 * If the Mezzio setting non_locking is set to true (i.e., PHP's read_and_close()),
18
 * the session may be garbage collected even if it was accessed within gc_maxlifetime.
19
 * This happens because PHP relies on the mtime of the session file,
20
 * which is updated only when the session is written.
21
 *
22
 * As a result, users may be randomly logged out.
23
 *
24
 * So as long as the user is connected, we write an arbitrary data to the
25
 * session to update the mtime of the file to prevent its garbage collection.
26
 */
27
class RefreshSessionTimestampMiddleware implements MiddlewareInterface
28
{
29 1
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
30
    {
31 1
        $session = $request->getAttribute(SessionMiddleware::SESSION_ATTRIBUTE);
32
33 1
        if ($session->has('user')) {
34
            // Setting a value to trigger session write.
35
            // Harmless if set twice by concurrent requests.
36 1
            $session->set('_last_access', time());
37
        }
38
39 1
        return $handler->handle($request);
40
    }
41
}
42