SessionMiddleware   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 2
dl 0
loc 58
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B __invoke() 0 53 5
1
<?php
2
3
/**
4
 * @author Jared King <[email protected]>
5
 *
6
 * @see http://jaredtking.com
7
 *
8
 * @copyright 2015 Jared King
9
 * @license MIT
10
 */
11
12
namespace Infuse\Middleware;
13
14
use Infuse\HasApp;
15
use Infuse\Request;
16
use Infuse\Response;
17
18
class SessionMiddleware
19
{
20
    use HasApp;
21
22
    public function __invoke(Request $req, Response $res, callable $next)
23
    {
24
        $config = $this->app['config'];
25
        if (!$config->get('sessions.enabled') || $req->isApi()) {
26
            return $next($req, $res);
27
        }
28
29
        // Check if sessions are disabled for the route
30
        $route = (array) array_value($this->app['routeInfo'], 1);
31
        $params = (array) array_value($route, 2);
32
        if (array_value($params, 'no_session')) {
33
            return $next($req, $res);
34
        }
35
36
        $lifetime = $config->get('sessions.lifetime');
37
        $hostname = $config->get('app.hostname');
38
        ini_set('session.use_trans_sid', false);
39
        ini_set('session.use_only_cookies', true);
40
        ini_set('url_rewriter.tags', '');
41
        ini_set('session.gc_maxlifetime', $lifetime);
42
43
        // set the session name
44
        $defaultSessionTitle = $config->get('app.title').'-'.$hostname;
45
        $sessionTitle = $config->get('sessions.name', $defaultSessionTitle);
46
        $safeSessionTitle = str_replace(['.', ' ', "'", '"'], ['', '_', '', ''], $sessionTitle);
47
        session_name($safeSessionTitle);
48
49
        // set the session cookie parameters
50
        session_set_cookie_params(
51
            $lifetime, // lifetime
52
            '/', // path
53
            '.'.$hostname, // domain
54
            $req->isSecure(), // secure
55
            true // http only
56
        );
57
58
        // register session_write_close as a shutdown function
59
        session_register_shutdown();
60
61
        // install any custom session handlers
62
        $class = $config->get('sessions.driver');
63
        if ($class) {
64
            $handler = new $class($this->app);
65
            $handler::registerHandler($handler);
66
        }
67
68
        session_start();
69
70
        // make the newly started session in our request
71
        $req->setSession($_SESSION);
72
73
        return $next($req, $res);
74
    }
75
}
76