GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 7ce72c...a45381 )
by Cees-Jan
12s
created

SessionMiddleware::fetchSessionFromRequest()   A

Complexity

Conditions 3
Paths 6

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3.054

Importance

Changes 0
Metric Value
dl 0
loc 20
ccs 9
cts 11
cp 0.8182
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 11
nc 6
nop 1
crap 3.054
1
<?php declare(strict_types=1);
2
3
namespace WyriHaximus\React\Http\Middleware;
4
5
use HansOtt\PSR7Cookies\RequestCookies;
6
use HansOtt\PSR7Cookies\SetCookie;
7
use Psr\Http\Message\ResponseInterface;
8
use Psr\Http\Message\ServerRequestInterface;
9
use React\Cache\CacheInterface;
10
use React\Promise\PromiseInterface;
11
use Throwable;
12
use WyriHaximus\React\Http\Middleware\SessionId\RandomBytes;
13
use function React\Promise\resolve;
14
15
final class SessionMiddleware
16
{
17
    const ATTRIBUTE_NAME = 'wyrihaximus.react.http.middleware.session';
18
19
    const DEFAULT_COOKIE_PARAMS = [
20
        0,
21
        '',
22
        '',
23
        false,
24
        false,
25
    ];
26
27
    /**
28
     * @var string
29
     */
30
    private $cookieName = '';
31
32
    /**
33
     * @var CacheInterface
34
     */
35
    private $cache;
36
37
    /**
38
     * @var array
39
     */
40
    private $cookieParams = [];
41
42
    /**
43
     * @var SessionIdInterface
44
     */
45
    private $sessionId;
46
47
    /**
48
     * @param string         $cookieName
49
     * @param CacheInterface $cache
50
     * @param array          $cookieParams
51
     */
52 12
    public function __construct(
53
        string $cookieName,
54
        CacheInterface $cache,
55
        array $cookieParams = [],
56
        SessionIdInterface $sessionId = null
57
    ) {
58 12
        $this->cookieName = $cookieName;
59 12
        $this->cache = $cache;
60 12
        $this->cookieParams = array_replace(self::DEFAULT_COOKIE_PARAMS, $cookieParams);
61
62 12
        if ($sessionId === null) {
63 12
            $sessionId = new RandomBytes();
64
        }
65 12
        $this->sessionId = $sessionId;
66 12
    }
67
68
    public function __invoke(ServerRequestInterface $request, callable $next)
69
    {
70 12
        return $this->fetchSessionFromRequest($request)->then(function (Session $session) use ($next, $request) {
71 12
            $request = $request->withAttribute(self::ATTRIBUTE_NAME, $session);
0 ignored issues
show
Bug introduced by
Consider using a different name than the imported variable $request, or did you forget to import by reference?

It seems like you are assigning to a variable which was imported through a use statement which was not imported by reference.

For clarity, we suggest to use a different name or import by reference depending on whether you would like to have the change visibile in outer-scope.

Change not visible in outer-scope

$x = 1;
$callable = function() use ($x) {
    $x = 2; // Not visible in outer scope. If you would like this, how
            // about using a different variable name than $x?
};

$callable();
var_dump($x); // integer(1)

Change visible in outer-scope

$x = 1;
$callable = function() use (&$x) {
    $x = 2;
};

$callable();
var_dump($x); // integer(2)
Loading history...
72
73 12
            return resolve(
74 12
                $next($request)
75
            )->then(function (ResponseInterface $response) use ($session) {
76 12
                return $this->updateCache($session)->then(function () use ($response) {
77 12
                    return $response;
78 12
                });
79
            })->then(function ($response) use ($session) {
80 12
                $cookie = $this->getCookie($session);
81 12
                $response = $cookie->addToResponse($response);
82
83 12
                return $response;
84 12
            });
85 12
        });
86
    }
87
88 12
    private function fetchSessionFromRequest(ServerRequestInterface $request): PromiseInterface
89
    {
90 12
        $id = '';
91 12
        $cookies = RequestCookies::createFromRequest($request);
92
93
        try {
94 12
            if (!$cookies->has($this->cookieName)) {
95 10
                return resolve(new Session($id, [], $this->sessionId));
96
            }
97 2
            $id = $cookies->get($this->cookieName)->getValue();
98
99 2
            return $this->fetchSessionDataFromCache($id)->then(function (array $sessionData) use ($id) {
100 2
                return new Session($id, $sessionData, $this->sessionId);
101 2
            });
102
        } catch (Throwable $et) {
103
            // Do nothing, only a not found will be thrown so generating our own id now
104
        }
105
106
        return resolve(new Session($id, [], $this->sessionId));
107
    }
108
109 2
    private function fetchSessionDataFromCache(string $id): PromiseInterface
110
    {
111 2
        if ($id === '') {
112
            return resolve([]);
113
        }
114
115 2
        return $this->cache->get($id)->otherwise(function () {
116 1
            return resolve([]);
117 2
        });
118
    }
119
120 12
    private function updateCache(Session $session): PromiseInterface
121
    {
122 12
        foreach ($session->getOldIds() as $oldId) {
123 1
            $this->cache->remove($oldId);
124
        }
125
126 12
        if ($session->isActive()) {
127 10
            return resolve($this->cache->set($session->getId(), $session->getContents()));
128
        }
129
130 2
        return resolve();
131
    }
132
133 12
    private function getCookie(Session $session): SetCookie
134
    {
135 12
        $cookieParams = $this->cookieParams;
136
137 12
        if ($session->isActive()) {
138
            // Only set time when expires is set in the future
139 10
            if ($cookieParams[0] > 0) {
140 8
                $cookieParams[0] += time();
141
            }
142
143 10
            return new SetCookie($this->cookieName, $session->getId(), ...$cookieParams);
0 ignored issues
show
Documentation introduced by
$cookieParams is of type array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
144
        }
145 2
        unset($cookieParams[0]);
146
147 2
        return SetCookie::thatDeletesCookie($this->cookieName, ...$cookieParams);
0 ignored issues
show
Documentation introduced by
$cookieParams is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
148
    }
149
}
150